repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
apaleyes/xfer
[ "99cd83424bc7e76a2c2def9d5b1dacd06f6e9eb5", "99cd83424bc7e76a2c2def9d5b1dacd06f6e9eb5" ]
[ "xfer/contrib/xfer_leap/synthetic_data.py", "tests/unit/test_bnn_repurposer.py" ]
[ "# Copyright 2018 Amazon.com, Inc. or its 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# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# ==============================================================================\nimport os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom mxnet.gluon.data import ArrayDataset\nimport mxnet\n\nfrom .data import MetaTaskDataContainer, TaskDataContainer\nfrom .config import DEFAULT_CONFIG_SYNTHETIC\n\n\nclass MetaTaskSynthetic(MetaTaskDataContainer):\n def __init__(self, config=None, weights=None, bias=None, seed=1, context=None):\n\n \"\"\"\n :param config: If None, DEFAULT_CONFIG_SYNTHETIC is loaded.\n :param weights: Tasks' weights matrix. Row k corresponds to the weight parameters of task k. If None, w is\n sampled from a N(0,1).\n :param bias: Tasks' biases vector. Row k corresponds to the bias parameters of task k. If None, w is sampled\n from a N(0,1).\n :param seed: Seed for random generator.\n \"\"\"\n\n if config is None:\n config = DEFAULT_CONFIG_SYNTHETIC\n\n self.config = config\n self.weights = weights\n self.bias = bias\n\n if context is None:\n context = mxnet.cpu()\n self.context = context\n\n self.seed = seed\n random.seed(self.seed)\n\n num_tasks_train = config[\"num_tasks_train\"]\n num_tasks_test = config[\"num_tasks_test\"]\n num_tasks_val = config[\"num_tasks_val\"]\n num_tasks = num_tasks_train + num_tasks_test + num_tasks_val\n\n self.num_tasks = num_tasks\n\n self._generate_parameters()\n self._validate_parameters()\n\n num_examples = config[\"num_examples_per_task\"]\n std_x = config[\"std_x\"]\n hold_out = config[\"hold_out\"]\n noise = config[\"std_noise\"]\n\n # Generate the training/test/val dataset.\n # Each dataset is a list of TaskSynthetic objects (one per task)\n data_train = [TaskSynthetic(self.weights[t, :], self.bias[t], num_examples, std_x, noise, hold_out,\n context=context)\n for t in np.arange(0, num_tasks_train)]\n data_test = [TaskSynthetic(self.weights[t, :], self.bias[t], num_examples, std_x, noise, hold_out,\n context=context)\n for t in np.arange(num_tasks_train, num_tasks_train + num_tasks_test)]\n data_val = [TaskSynthetic(self.weights[t, :], self.bias[t], num_examples, std_x, noise, hold_out,\n context=context)\n for t in np.arange(num_tasks_train + num_tasks_test, num_tasks)]\n\n super().__init__(data_train, data_test, data_val, context=context)\n\n def plot_sample(self, root=\"./sample_synth\"):\n\n \"\"\"Plot N images from each alphabet and store the images in root.\"\"\"\n\n if self.weights.shape[1] != 2:\n raise ValueError(\"Only 2D datasets can be plot.\")\n\n if not os.path.exists(root):\n os.makedirs(root)\n\n fig_train = self._plot([dd._train_dataset for dd in self.train_tasks],\n \"Training Samples for Training Tasks\")\n fig_train.savefig(os.path.join(root, \"sample_train_train_tasks.png\"))\n del fig_train\n fig_test = self._plot([dd._train_dataset for dd in self.test_tasks],\n \"Training Samples for Test Tasks\")\n fig_test.savefig(os.path.join(root, \"sample_train_test_tasks.png\"))\n del fig_test\n fig_val = self._plot([dd._train_dataset for dd in self.val_tasks],\n \"Training Samples for Validation Tasks\")\n fig_val.savefig(os.path.join(root, \"sample_train_val_tasks.png\"))\n del fig_val\n\n if self.config[\"hold_out\"] > 0:\n fig_train = self._plot([dd._val_dataset for dd in self.train_tasks],\n \"Validation Samples for Training Tasks\")\n fig_train.savefig(os.path.join(root, \"sample_val_train_tasks.png\"))\n del fig_train\n fig_test = self._plot([dd._val_dataset for dd in self.test_tasks],\n \"Validation Samples for Test Tasks\")\n fig_test.savefig(os.path.join(root, \"sample_val_test_tasks.png\"))\n del fig_test\n fig_val = self._plot([dd._val_dataset for dd in self.val_tasks],\n \"Validation Samples for Validation Tasks\")\n fig_val.savefig(os.path.join(root, \"sample_val_val_tasks.png\"))\n del fig_val\n\n def _plot(self, data, title):\n\n \"\"\"Helper function for plotting.\"\"\"\n\n num_tasks = len(data)\n fig, ax = plt.subplots(1, num_tasks, figsize=(num_tasks*5, 5))\n fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=0.5)\n for mm in range(num_tasks):\n X, y = data[mm][:]\n X = X.asnumpy()\n y = y.asnumpy()\n ax[mm].scatter(X[:, 0], X[:, 1], c=y.flatten())\n fig.suptitle(title, size=18)\n return fig\n\n def _validate_parameters(self):\n if self.weights.shape[0] != self.num_tasks:\n raise ValueError(\"Number of rows in w must be equal to the total number of tasks\")\n\n if len(self.bias) != self.num_tasks:\n raise ValueError(\"Length of b must be equal to the total number of tasks\")\n\n def _generate_parameters(self):\n if self.weights is None:\n dim = self.config[\"dim\"]\n self.weights = self.config[\"global_bias\"] + mxnet.nd.random_normal(shape=(self.num_tasks, dim),\n ctx=self.context)\n\n if self.bias is None:\n if self.config[\"task_bias\"]:\n self.bias = mxnet.nd.random_normal(shape=self.num_tasks, ctx=self.context)\n else:\n self.bias = mxnet.nd.zeros(num_tasks, ctx=self.context)\n\n\nclass TaskSynthetic(TaskDataContainer):\n\n \"\"\"\n Synthetic Task Container: Linear Regression.\n \"\"\"\n\n def __init__(self, w, b, num_examples, std_x, noise, hold_out=None, seed=None, context=None):\n\n \"\"\"\n :param w: Task's weights vector.\n :param b: Task's bias.\n :param num_examples: Total number of examples per task.\n :param std_x: The covariates are sampled from a zero mean normal distribution with\n standard deviation equal to std_x.\n :param hold_out: Number of examples to hold out for validation\n :param seed: seed for the random generator\n \"\"\"\n\n self.w = w\n self.b = b\n self.num_examples = num_examples\n self.seed = seed\n\n if context is None:\n context = mxnet.cpu()\n self.context = context\n\n if seed:\n random.seed(seed)\n if hold_out and hold_out < num_examples:\n Xtr, Ytr = self._real_fn(std_x * mxnet.nd.random_normal(shape=(num_examples - hold_out, len(w)),\n ctx=context), noise)\n train_dataset = ArrayDataset(Xtr, Ytr)\n Xval, Yval = self._real_fn(std_x * mxnet.nd.random_normal(shape=(hold_out, len(w)), ctx=context), noise)\n val_dataset = ArrayDataset(Xval, Yval)\n else:\n Xtr, Ytr = self._real_fn(std_x * mxnet.nd.random_normal(shape=(num_examples, len(w)), ctx=context), noise)\n train_dataset = ArrayDataset(Xtr, Ytr)\n val_dataset = None\n\n super().__init__(train_dataset, val_dataset, context=context)\n\n def _real_fn(self, X, noise):\n y = mxnet.nd.dot(X, mxnet.nd.expand_dims(self.w, axis=1)) + self.b\n if noise > 0.0:\n y += mxnet.nd.expand_dims(noise * mxnet.nd.random_normal(shape=(X.shape[0],)), axis=1)\n return X, y\n\n\nif __name__ == '__main__':\n\n s1 = MetaTaskSynthetic()\n s1.plot_sample()\n\n batch_size = 20\n train_tasks = s1.train_tasks\n\n assert len(s1.train_tasks) == 3\n for task in train_tasks:\n tr_iterator = task.get_train_iterator(batch_size)\n for data in tr_iterator:\n assert (data[0].shape == (batch_size, 2))\n assert (data[1].shape == (batch_size, 1))\n assert (data[1].asnumpy().dtype == np.float32)\n break\n val_iterator = task.get_val_iterator(batch_size)\n for data in val_iterator:\n assert (data[0].shape == (batch_size, 2))\n assert (data[1].shape == (batch_size, 1))\n assert (data[1].asnumpy().dtype == np.float32)\n break\n\n dim = 2\n num_tasks = 15\n w = mxnet.nd.random_normal(shape=(num_tasks, dim))\n b = mxnet.nd.random_normal(shape=num_tasks)\n\n s2 = MetaTaskSynthetic(weights=w, bias=b)\n s2.plot_sample(root=\"./sample_synth_w_b_given\")\n\n batch_size = 20\n train_tasks = s2.train_tasks\n\n assert len(train_tasks) == 3\n for task in train_tasks:\n tr_iterator = task.get_train_iterator(batch_size)\n for data in tr_iterator:\n assert (data[0].shape == (batch_size, 2))\n assert (data[1].shape == (batch_size, 1))\n assert (data[1].asnumpy().dtype == np.float32)\n break\n val_iterator = task.get_val_iterator(batch_size)\n for data in val_iterator:\n assert (data[0].shape == (batch_size, 2))\n assert (data[1].shape == (batch_size, 1))\n assert (data[1].asnumpy().dtype == np.float32)\n break\n", "# Copyright 2018 Amazon.com, Inc. or its 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# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# ==============================================================================\nimport numpy as np\nimport random\nfrom unittest.mock import patch\n\nimport mxnet as mx\nfrom mxnet import gluon\n\nfrom xfer import BnnRepurposer\nfrom xfer.bnn_classifier import BnnClassifier\nfrom .test_meta_model_repurposer import MetaModelRepurposerTestCase\nfrom ..repurposer_test_utils import RepurposerTestUtils\n\n\nclass BnnRepurposerTestCase(MetaModelRepurposerTestCase):\n\n def setUp(self):\n np.random.seed(1)\n random.seed(1)\n mx.random.seed(1)\n\n super(BnnRepurposerTestCase, self).setUp()\n\n N = 10\n self.train_features = self.train_features[:N]\n self.train_labels = self.train_labels[:N]\n\n # Override base repurpose_class with 'BnnRepurposer' to run base tests with instance of BNN Repurposer\n self.repurposer_class = BnnRepurposer\n\n # Minimum expected performance\n self.minimum_expected_accuracy = 0.2\n\n def test_train_model_from_features(self):\n bnn_repurposer = BnnRepurposer(self.source_model, self.source_model_layers, num_epochs=3)\n bnn_model = bnn_repurposer._train_model_from_features(self.train_features, self.train_labels)\n self._validate_trained_model(bnn_model)\n\n def test_predict_probability_from_features(self):\n self._test_predict_from_features(test_predict_probability=True,\n expected_accuracy=self.minimum_expected_accuracy)\n\n def test_predict_label_from_features(self):\n self._test_predict_from_features(test_predict_probability=False,\n expected_accuracy=self.minimum_expected_accuracy)\n\n # TODO: This overrides the method in _test_predict_from_features due to the lack of serialization functionality for\n # the bnn repurposer. Once the serialization is implemented this method will be deleted.\n def _test_predict_from_features(self, test_predict_probability, expected_accuracy):\n \"\"\" Used to test 'predict_from_features' implementation in derived classes \"\"\"\n # Create repurposer\n repurposer = self.repurposer_class(self.source_model, self.source_model_layers, num_samples_mc_prediction=5,\n num_epochs=2, num_samples_mc=1)\n\n repurposer.target_model = repurposer._train_model_from_features(self.train_features, self.train_labels)\n\n if test_predict_probability:\n results = repurposer._predict_probability_from_features(self.test_features)\n else:\n results = repurposer._predict_label_from_features(self.test_features)\n\n self._validate_prediction_results(results, test_predict_probability, expected_accuracy)\n\n @patch.object(BnnRepurposer, RepurposerTestUtils.VALIDATE_PREDICT_METHOD_NAME)\n @patch(RepurposerTestUtils.META_MODEL_REPURPOSER_MODEL_HANDLER_CLASS)\n def test_predict_probability(self, mock_model_handler, validate_method):\n self._test_predict(mock_model_handler, validate_method, test_predict_probability=True,\n expected_accuracy=self.minimum_expected_accuracy)\n\n @patch.object(BnnRepurposer, RepurposerTestUtils.VALIDATE_PREDICT_METHOD_NAME)\n @patch(RepurposerTestUtils.META_MODEL_REPURPOSER_MODEL_HANDLER_CLASS)\n def test_predict_label(self, mock_model_handler, validate_method):\n self._test_predict(mock_model_handler, validate_method, test_predict_probability=False,\n expected_accuracy=self.minimum_expected_accuracy)\n\n # TODO: This overrides the method in test_meta_model_repurposer due to the lack of serialization fucntionality for\n # the bnn repurposer. Once the serialization is implemented this method will be deleted.\n def _test_predict(self, mock_model_handler, mock_validate_method, test_predict_probability, expected_accuracy):\n \"\"\" Test for predict wrapper in meta model base class \"\"\"\n # Patch model_handler and then create repurposer object\n mock_model_handler.return_value = RepurposerTestUtils.get_mock_model_handler_object()\n\n # Create repurposer\n repurposer = self.repurposer_class(self.source_model, self.source_model_layers, num_samples_mc_prediction=5,\n num_epochs=2)\n\n # Identify which predict function to test\n if test_predict_probability:\n predict_function = repurposer.predict_probability\n else:\n predict_function = repurposer.predict_label\n\n # Load target model from file\n model = repurposer._train_model_from_features(self.train_features, self.train_labels)\n repurposer.target_model = model\n\n # Call predict method and get prediction results\n mock_model_handler.return_value.get_layer_output.return_value = self.test_feature_dict, self.test_labels\n mock_validate_method.reset_mock()\n # Mocking iterator because get_layer_output is patched\n results = predict_function(test_iterator=self.mock_object)\n\n # Check if predict called validate\n self.assertTrue(mock_validate_method.call_count == 1,\n \"Predict expected to called {} once. Found {} calls\".\n format(RepurposerTestUtils.VALIDATE_PREDICT_METHOD_NAME, mock_validate_method.call_count))\n\n self._validate_prediction_results(results, test_predict_probability, expected_accuracy)\n\n def _validate_trained_model(self, model):\n # Validate type of model\n expected_type = BnnClassifier\n actual_type = type(model)\n self.assertTrue(actual_type == expected_type,\n \"Expected model of type: {}. Instead got: {}\".format(expected_type, actual_type))\n\n shapes_model = [x.shape for x in model.model.collect_params().values()]\n shapes_posterior = model.var_posterior.shapes\n for shape_model, shape_posterior in zip(shapes_model, shapes_posterior):\n self.assertTrue(shape_model == shape_posterior, \"Shapes of the model and the variational posterior do not \\\n match. {} vs {}\".format(shape_model, shape_posterior))\n\n @patch(RepurposerTestUtils.META_MODEL_REPURPOSER_MODEL_HANDLER_CLASS)\n def test_repurpose(self, mock_model_handler):\n # Patch model_handler and then create bnn_repurposer\n mock_model_handler.return_value = RepurposerTestUtils.get_mock_model_handler_object()\n N = 5\n train_feature_dict_subset = {k: v[:N] for k, v in self.train_feature_dict.items()}\n mock_model_handler.return_value.get_layer_output.return_value = train_feature_dict_subset, self.train_labels[:N]\n self._test_repurpose(n_jobs=-1) # Use all cores\n self._test_repurpose(n_jobs=1) # Use single core\n\n def _test_repurpose(self, n_jobs=-1):\n bnn_repurposer = BnnRepurposer(self.source_model, self.source_model_layers, num_epochs=2)\n\n # Target model is not initialized yet\n self.assertTrue(bnn_repurposer.target_model is None, \"Target model not expected to be initialized at this \\\n point\")\n\n # Call repurpose\n bnn_repurposer.repurpose(self.mock_object)\n\n # Validate target model is now set\n self.assertTrue(bnn_repurposer.target_model is not None, \"Repurpose failed to set target model\")\n\n # Validate trained model\n self._validate_trained_model(bnn_repurposer.target_model)\n\n def test_build_nn(self):\n bnn_repurposer = BnnRepurposer(self.source_model, self.source_model_layers)\n x_tr = self.train_features.astype(np.dtype(np.float32))\n y_tr = self.train_labels.astype(np.dtype(np.float32))\n train_data = gluon.data.DataLoader(gluon.data.ArrayDataset(x_tr, y_tr),\n batch_size=bnn_repurposer.batch_size, shuffle=True)\n\n neural_network, shapes = bnn_repurposer._build_nn(train_data, len(np.unique(y_tr)))\n for layer in neural_network:\n assert isinstance(layer, gluon.nn.Dense)\n\n # Input layer: Fully connected layer with 2 parameters (affine transformation plus bias)\n assert shapes[0] == (bnn_repurposer.n_hidden, self.train_features.shape[1])\n assert shapes[1] == (bnn_repurposer.n_hidden, )\n\n # Intermediate layers: Each of them is a Fully connected layer with 2 parameters (affine transformation plus\n # bias)\n for ss in range(2, len(shapes)-2):\n if ss % 2 == 0:\n assert shapes[ss] == (bnn_repurposer.n_hidden, bnn_repurposer.n_hidden)\n else:\n assert shapes[ss] == (bnn_repurposer.n_hidden, )\n\n # Output layer: Fully connected layer with 2 parameters (affine transformation plus bias)\n assert shapes[len(shapes)-2] == (self.n_classes, bnn_repurposer.n_hidden)\n assert shapes[len(shapes)-1] == (self.n_classes, )\n\n def _validate_prediction_results(self, results, test_predict_probability, expected_minimum_accuracy):\n # Validate type of prediction results\n self.assertTrue(type(results) == np.ndarray,\n \"Prediction results expected to be numpy array. Instead got: {}\".format(type(results)))\n\n # Validate shape of prediction results\n if test_predict_probability:\n expected_shape = (self.n_test_instances, self.n_classes)\n else:\n expected_shape = (self.n_test_instances,)\n self.assertTrue(results.shape == expected_shape,\n \"Prediction results shape is incorrect. Expected: {}. Got: {}\".format(expected_shape,\n results.shape))\n\n # Validate if prediction probabilities sum to 1\n if test_predict_probability:\n probability_sum = np.sum(results, axis=1)\n array_of_ones = np.ones(shape=(self.n_test_instances,))\n self.assertTrue(np.allclose(probability_sum, array_of_ones), \"Sum of predicted probabilities is not 1\")\n\n # Validate accuracy of prediction results\n labels = np.argmax(results, axis=1) if test_predict_probability else results\n\n self.assertTrue(np.mean(labels == self.test_labels) >= expected_minimum_accuracy, \"Prediction accuracy is \" +\n \"incorrect. Minimum accuracy expected: {}. Actual accuracy: {}\".format(\n expected_minimum_accuracy,\n np.mean(labels == self.test_labels)))\n\n def _assert_target_model_equal(self, model1, model2):\n assert model1.normalizer.__dict__ == model2.normalizer.__dict__\n\n assert model1.var_posterior.shapes == model2.var_posterior.shapes\n assert model1.var_posterior.ctx == model2.var_posterior.ctx\n\n for key in model1.var_posterior.raw_params.keys():\n for count, _ in enumerate(model1.var_posterior.raw_params[key]):\n assert np.array_equal(model1.var_posterior.raw_params[key][count].asnumpy(),\n model2.var_posterior.raw_params[key][count].asnumpy())\n\n for key in model1.var_posterior.params.keys():\n for count, value in enumerate(model1.var_posterior.params[key]):\n assert np.array_equal(value.data(), model2.var_posterior.params[key][count].data())\n assert value.grad_req == model2.var_posterior.params[key][count].grad_req\n assert value.name == model2.var_posterior.params[key][count].name\n\n def _assert_attributes_equal(self, repurposer1, repurposer2):\n super()._assert_attributes_equal(repurposer1, repurposer2)\n assert repurposer1.annealing_weight == repurposer2.annealing_weight\n\n def test_get_params(self):\n repurposer = BnnRepurposer(self.source_model, self.source_model_layers)\n\n params = repurposer.get_params()\n expected_params = {\n 'context_function': 'cpu',\n 'num_devices': 1,\n 'feature_layer_names': ['fc1', 'fc2'],\n 'bnn_context_function': 'cpu',\n 'sigma': 100.0,\n 'num_layers': 1,\n 'n_hidden': 10,\n 'num_samples_mc': 3,\n 'learning_rate': 0.001,\n 'batch_size': 20,\n 'num_epochs': 200,\n 'start_annealing': 20,\n 'end_annealing': 40,\n 'num_samples_mc_prediction': 100,\n 'verbose': 0\n }\n\n assert params == expected_params\n\n def test_verbose(self):\n bnn_repurposer = BnnRepurposer(self.source_model, self.source_model_layers, num_epochs=3, verbose=True,\n num_samples_mc=1)\n N = 2\n with self.assertLogs() as cm:\n bnn_repurposer._train_model_from_features(self.train_features[:N], self.train_labels[:N])\n print(cm.output)\n assert len(cm.output) == 3\n\n bnn_repurposer = BnnRepurposer(self.source_model, self.source_model_layers, num_epochs=3, verbose=False,\n num_samples_mc=1)\n with self.assertRaises(AssertionError):\n with self.assertLogs():\n bnn_repurposer._train_model_from_features(self.train_features[:N], self.train_labels[:N])\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.subplots" ], [ "numpy.allclose", "numpy.random.seed", "numpy.unique", "numpy.dtype", "numpy.ones", "numpy.argmax", "numpy.mean", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
idharmateja/tensorflow
[ "1712002ad02f044f7569224bf465e0ea00e6a6c4", "6f0dd0425c51360fe2be5a938a8f3fb39e420fa3" ]
[ "tensorflow/contrib/data/python/ops/readers.py", "tensorflow/contrib/kfac/python/ops/optimizer.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Python wrappers for reader Datasets.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.data.python.ops import interleave_ops\nfrom tensorflow.contrib.data.python.ops import shuffle_ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import readers as core_readers\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import gen_dataset_ops\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.util import deprecation\n\n_ACCEPTABLE_CSV_TYPES = (dtypes.float32, dtypes.float64, dtypes.int32,\n dtypes.int64, dtypes.string)\n\n\ndef make_csv_dataset(\n file_pattern,\n batch_size,\n column_keys,\n column_defaults,\n label_key=None,\n field_delim=\",\",\n use_quote_delim=True,\n skip=0,\n filter_fn=None,\n num_epochs=None,\n shuffle=True,\n shuffle_buffer_size=10000,\n shuffle_seed=None,\n prefetch_buffer_size=1,\n):\n \"\"\"Reads CSV files into a dataset.\n\n Reads CSV files into a dataset, where each element is a (features, labels)\n tuple that corresponds to a batch of CSV rows. The features dictionary\n maps feature column names to `Tensor`s containing the corresponding\n feature data, and labels is a `Tensor` containing the batch's label data.\n\n Args:\n file_pattern: List of files or patterns of file paths containing CSV\n records. See @{tf.gfile.Glob} for pattern rules.\n batch_size: An int representing the number of consecutive elements of this\n dataset to combine in a single batch.\n column_keys: A list of strings that corresponds to the CSV columns, in\n order. One per column of the input record.\n column_defaults: A list of default values for the CSV fields. One item per\n column of the input record. Each item in the list is either one of the\n following dtypes: float32, float64, int32, int64, or string, or a\n `Tensor` with one of the aforementioned types. One item per column of\n the input record, with either scalar default value for that column if it\n is required, or, if the column is required, an empty `Tensor` or a dtype.\n label_key: A optional string corresponding to the label column. If provided,\n the data for this column is returned as a separate `Tensor` from the\n features dictionary, so that the dataset complies with the format expected\n by a `tf.Estimator.train` or `tf.Estimator.evaluate` input function.\n field_delim: An optional `string`. Defaults to `\",\"`. Char delimiter to\n separate fields in a record.\n use_quote_delim: An optional bool. Defaults to `True`. If false, treats\n double quotation marks as regular characters inside of the string fields.\n skip: An integer that corresponds to the number of lines to skip at the\n head of each CSV file. Defaults to 0.\n filter_fn: A callable function that takes in a CSV string and returns a\n boolean that corresponds to whether the record should be included. If\n None, does not filter records.\n num_epochs: An int specifying the number of times this dataset is repeated.\n If None, cycles through the dataset forever.\n shuffle: A bool that indicates whether the input should be shuffled.\n shuffle_buffer_size: Buffer size to use for shuffling. A large buffer size\n ensures better shuffling, but would increase memory usage and startup\n time.\n shuffle_seed: Randomization seed to use for shuffling.\n prefetch_buffer_size: An int specifying the number of feature batches to\n prefetch for performance improvement. Recommended value is the number of\n batches consumed per training step.\n\n Returns:\n A dataset, where each element is a (features, labels) tuple that corresponds\n to a batch of `batch_size` CSV rows. The features dictionary maps feature\n column names to `Tensor`s containing the corresponding column data, and\n labels is a `Tensor` containing the column data for the label column\n specified by `label_key`.\n \"\"\"\n filenames = _get_file_names(file_pattern, False)\n column_defaults = [\n constant_op.constant([], dtype=x) if x in _ACCEPTABLE_CSV_TYPES else x\n for x in column_defaults\n ]\n\n dataset = dataset_ops.Dataset.from_tensor_slices(filenames)\n if label_key is not None:\n assert label_key in column_keys\n\n def filename_to_dataset(filename):\n ds = core_readers.TextLineDataset(filename)\n if skip > 0:\n ds = ds.skip(skip)\n if filter_fn is not None:\n ds = ds.filter(filter_fn)\n return ds\n\n def decode_csv(line):\n \"\"\"Decodes csv line into features.\n\n Args:\n line: String tensor corresponding to one csv record.\n Returns:\n A dictionary of feature names to values for that particular record. If\n label_key is provided, extracts the label feature to be returned as the\n second element of the tuple.\n \"\"\"\n columns = parsing_ops.decode_csv(\n line,\n column_defaults,\n field_delim=field_delim,\n use_quote_delim=use_quote_delim)\n features = dict(zip(column_keys, columns))\n if label_key is not None:\n label = features.pop(label_key)\n return features, label\n return features\n\n # TODO(rachelim): interleave records from files for better shuffling\n dataset = dataset.flat_map(filename_to_dataset)\n # TODO(rachelim): use fused shuffle_and_repeat for perf\n if shuffle:\n dataset = dataset.shuffle(shuffle_buffer_size, shuffle_seed)\n if num_epochs != 1:\n dataset = dataset.repeat(num_epochs)\n\n dataset = dataset.batch(batch_size)\n dataset = dataset.map(decode_csv)\n dataset = dataset.prefetch(prefetch_buffer_size)\n return dataset\n\n\ndef make_batched_features_dataset(file_pattern,\n batch_size,\n features,\n reader=core_readers.TFRecordDataset,\n reader_args=None,\n num_epochs=None,\n shuffle=True,\n shuffle_buffer_size=10000,\n shuffle_seed=None,\n prefetch_buffer_size=1,\n reader_num_threads=1,\n parser_num_threads=2,\n sloppy_ordering=False):\n \"\"\"Returns a `Dataset` of feature dictionaries from `Example` protos.\n\n Example:\n\n ```\n serialized_examples = [\n features {\n feature { key: \"age\" value { int64_list { value: [ 0 ] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n feature { key: \"kws\" value { bytes_list { value: [ \"code\", \"art\" ] } } }\n },\n features {\n feature { key: \"age\" value { int64_list { value: [] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n feature { key: \"kws\" value { bytes_list { value: [ \"sports\" ] } } }\n }\n ]\n ```\n\n We can use arguments:\n\n ```\n features: {\n \"age\": FixedLenFeature([], dtype=tf.int64, default_value=-1),\n \"gender\": FixedLenFeature([], dtype=tf.string),\n \"kws\": VarLenFeature(dtype=tf.string),\n }\n ```\n\n And the expected output is:\n\n ```python\n {\n \"age\": [[0], [-1]],\n \"gender\": [[\"f\"], [\"f\"]],\n \"kws\": SparseTensor(\n indices=[[0, 0], [0, 1], [1, 0]],\n values=[\"code\", \"art\", \"sports\"]\n dense_shape=[2, 2]),\n }\n ```\n\n Args:\n file_pattern: List of files or patterns of file paths containing\n `Example` records. See `tf.gfile.Glob` for pattern rules.\n batch_size: An int representing the number of consecutive elements of this\n dataset to combine in a single batch.\n features: A `dict` mapping feature keys to `FixedLenFeature` or\n `VarLenFeature` values. See `tf.parse_example`.\n reader: A function or class that can be\n called with a `filenames` tensor and (optional) `reader_args` and returns\n a `Dataset` of `Example` tensors. Defaults to `tf.data.TFRecordDataset`.\n reader_args: Additional arguments to pass to the reader class.\n num_epochs: Integer specifying the number of times to read through the\n dataset. If None, cycles through the dataset forever. Defaults to `None`.\n shuffle: A boolean, indicates whether the input should be shuffled. Defaults\n to `True`.\n shuffle_buffer_size: Buffer size of the ShuffleDataset. A large capacity\n ensures better shuffling but would increase memory usage and startup time.\n shuffle_seed: Randomization seed to use for shuffling.\n prefetch_buffer_size: Number of feature batches to prefetch in order to\n improve performance. Recommended value is the number of batches consumed\n per training step (default is 1).\n reader_num_threads: Number of threads used to read `Example` records. If >1,\n the results will be interleaved.\n parser_num_threads: Number of threads to use for parsing `Example` tensors\n into a dictionary of `Feature` tensors.\n sloppy_ordering: If `True`, reading performance will be improved at\n the cost of non-deterministic ordering. If `False`, the order of elements\n produced is deterministic prior to shuffling (elements are still\n randomized if `shuffle=True`. Note that if the seed is set, then order\n of elements after shuffling is deterministic). Defaults to `False`.\n\n Returns:\n A dataset of `dict` elements. Each `dict` maps feature keys to\n `Tensor` or `SparseTensor` objects.\n \"\"\"\n # Create dataset of all matching filenames\n if shuffle:\n dataset = dataset_ops.Dataset.list_files(file_pattern, shuffle=True)\n else:\n # TODO(b/73959787): Use Dataset.list_files() once ordering is deterministic.\n filenames = _get_file_names(file_pattern, shuffle)\n dataset = dataset_ops.Dataset.from_tensor_slices(filenames)\n\n # Read `Example` records from files as tensor objects.\n if reader_args is None:\n reader_args = []\n\n # Read files sequentially (if reader_num_threads=1) or in parallel\n dataset = dataset.apply(\n interleave_ops.parallel_interleave(\n lambda filename: reader(filename, *reader_args),\n cycle_length=reader_num_threads,\n sloppy=sloppy_ordering))\n\n # Extract values if the `Example` tensors are stored as key-value tuples.\n if dataset.output_types == (dtypes.string, dtypes.string):\n dataset = dataset.map(lambda _, v: v)\n\n # Apply dataset repeat and shuffle transformations.\n repeat_dataset = (num_epochs != 1)\n if repeat_dataset and shuffle:\n # Used fused shuffle_and_repeat operation for better performance\n dataset = dataset.apply(\n shuffle_ops.shuffle_and_repeat(shuffle_buffer_size, num_epochs,\n shuffle_seed))\n elif repeat_dataset:\n dataset = dataset.repeat(num_epochs)\n elif shuffle:\n dataset = dataset.shuffle(shuffle_buffer_size, shuffle_seed)\n\n dataset = dataset.batch(batch_size)\n\n # Parse `Example` tensors to a dictionary of `Feature` tensors.\n dataset = dataset.map(\n lambda x: parsing_ops.parse_example(x, features),\n num_parallel_calls=parser_num_threads)\n\n # TODO(rachelim): Add an optional label_key argument for extracting the label\n # from the features dictionary, to comply with the type expected by the\n # input_fn to a `tf.Estimator.train` or `tf.Estimator.evaluate` function.\n dataset = dataset.prefetch(prefetch_buffer_size)\n return dataset\n\n\[email protected](None,\n \"Use `tf.contrib.data.make_batched_features_dataset`\")\ndef read_batch_features(file_pattern,\n batch_size,\n features,\n reader=core_readers.TFRecordDataset,\n reader_args=None,\n randomize_input=True,\n num_epochs=None,\n capacity=10000):\n \"\"\"Reads batches of Examples.\n\n Example:\n\n ```\n serialized_examples = [\n features {\n feature { key: \"age\" value { int64_list { value: [ 0 ] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n feature { key: \"kws\" value { bytes_list { value: [ \"code\", \"art\" ] } } }\n },\n features {\n feature { key: \"age\" value { int64_list { value: [] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n feature { key: \"kws\" value { bytes_list { value: [ \"sports\" ] } } }\n }\n ]\n ```\n\n We can use arguments:\n\n ```\n features: {\n \"age\": FixedLenFeature([], dtype=tf.int64, default_value=-1),\n \"gender\": FixedLenFeature([], dtype=tf.string),\n \"kws\": VarLenFeature(dtype=tf.string),\n }\n ```\n\n And the expected output is:\n\n ```python\n {\n \"age\": [[0], [-1]],\n \"gender\": [[\"f\"], [\"f\"]],\n \"kws\": SparseTensor(\n indices=[[0, 0], [0, 1], [1, 0]],\n values=[\"code\", \"art\", \"sports\"]\n dense_shape=[2, 2]),\n }\n ```\n\n Args:\n file_pattern: List of files or patterns of file paths containing\n `Example` records. See `tf.gfile.Glob` for pattern rules.\n batch_size: An int representing the number of consecutive elements of this\n dataset to combine in a single batch.\n features: A `dict` mapping feature keys to `FixedLenFeature` or\n `VarLenFeature` values. See `tf.parse_example`.\n reader: A function or class that can be\n called with a `filenames` tensor and (optional) `reader_args` and returns\n a `Dataset` of `Example` tensors. Defaults to `tf.data.TFRecordDataset`.\n reader_args: Additional arguments to pass to the reader class.\n randomize_input: Whether the input should be randomized.\n num_epochs: Integer specifying the number of times to read through the\n dataset. If None, cycles through the dataset forever.\n capacity: Buffer size of the ShuffleDataset. A large capacity ensures better\n shuffling but would increase memory usage and startup time.\n Returns:\n A dict from keys in features to `Tensor` or `SparseTensor` objects.\n \"\"\"\n dataset = make_batched_features_dataset(\n file_pattern,\n batch_size,\n features,\n reader=reader,\n reader_args=reader_args,\n shuffle=randomize_input,\n num_epochs=num_epochs,\n shuffle_buffer_size=capacity)\n iterator = dataset.make_one_shot_iterator()\n outputs = iterator.get_next()\n return outputs\n\n\ndef _get_file_names(file_pattern, shuffle):\n \"\"\"Parse list of file names from pattern, optionally shuffled.\n\n Args:\n file_pattern: File glob pattern, or list of glob patterns.\n shuffle: Whether to shuffle the order of file names.\n\n Returns:\n List of file names matching `file_pattern`.\n\n Raises:\n ValueError: If `file_pattern` is empty, or pattern matches no files.\n \"\"\"\n if isinstance(file_pattern, list):\n if not file_pattern:\n raise ValueError(\"File pattern is empty.\")\n file_names = []\n for entry in file_pattern:\n file_names.extend(gfile.Glob(entry))\n else:\n file_names = list(gfile.Glob(file_pattern))\n\n if not file_names:\n raise ValueError(\"No files match %s.\" % file_pattern)\n\n # Sort files so it will be deterministic for unit tests.\n if not shuffle:\n file_names = sorted(file_names)\n return file_names\n\n\nclass SqlDataset(dataset_ops.Dataset):\n \"\"\"A `Dataset` consisting of the results from a SQL query.\"\"\"\n\n def __init__(self, driver_name, data_source_name, query, output_types):\n \"\"\"Creates a `SqlDataset`.\n\n `SqlDataset` allows a user to read data from the result set of a SQL query.\n For example:\n\n ```python\n dataset = tf.contrib.data.SqlDataset(\"sqlite\", \"/foo/bar.sqlite3\",\n \"SELECT name, age FROM people\",\n (tf.string, tf.int32))\n iterator = dataset.make_one_shot_iterator()\n next_element = iterator.get_next()\n # Prints the rows of the result set of the above query.\n while True:\n try:\n print(sess.run(next_element))\n except tf.errors.OutOfRangeError:\n break\n ```\n\n Args:\n driver_name: A 0-D `tf.string` tensor containing the database type.\n Currently, the only supported value is 'sqlite'.\n data_source_name: A 0-D `tf.string` tensor containing a connection string\n to connect to the database.\n query: A 0-D `tf.string` tensor containing the SQL query to execute.\n output_types: A tuple of `tf.DType` objects representing the types of the\n columns returned by `query`.\n \"\"\"\n super(SqlDataset, self).__init__()\n self._driver_name = ops.convert_to_tensor(\n driver_name, dtype=dtypes.string, name=\"driver_name\")\n self._data_source_name = ops.convert_to_tensor(\n data_source_name, dtype=dtypes.string, name=\"data_source_name\")\n self._query = ops.convert_to_tensor(\n query, dtype=dtypes.string, name=\"query\")\n self._output_types = output_types\n\n def _as_variant_tensor(self):\n return gen_dataset_ops.sql_dataset(self._driver_name,\n self._data_source_name, self._query,\n nest.flatten(self.output_types),\n nest.flatten(self.output_shapes))\n\n @property\n def output_classes(self):\n return nest.map_structure(lambda _: ops.Tensor, self._output_types)\n\n @property\n def output_shapes(self):\n return nest.map_structure(lambda _: tensor_shape.TensorShape([]),\n self._output_types)\n\n @property\n def output_types(self):\n return self._output_types\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"The KFAC optimizer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport warnings\n\n# pylint disable=long-line\nfrom tensorflow.contrib.kfac.python.ops import curvature_matrix_vector_products as cmvp\nfrom tensorflow.contrib.kfac.python.ops import estimator as est\n# pylint enable=long-line\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.training import gradient_descent\n\n\nclass KfacOptimizer(gradient_descent.GradientDescentOptimizer):\n \"\"\"The KFAC Optimizer (https://arxiv.org/abs/1503.05671).\"\"\"\n\n def __init__(self,\n learning_rate,\n cov_ema_decay,\n damping,\n layer_collection,\n var_list=None,\n momentum=0.9,\n momentum_type=\"regular\",\n norm_constraint=None,\n name=\"KFAC\",\n estimation_mode=\"gradients\",\n colocate_gradients_with_ops=True,\n batch_size=None,\n cov_devices=None,\n inv_devices=None):\n \"\"\"Initializes the KFAC optimizer with the given settings.\n\n Args:\n learning_rate: The base learning rate for the optimizer. Should probably\n be set to 1.0 when using momentum_type = 'qmodel', but can still be\n set lowered if desired (effectively lowering the trust in the\n quadratic model.)\n cov_ema_decay: The decay factor used when calculating the covariance\n estimate moving averages.\n damping: The damping factor used to stabilize training due to errors in\n the local approximation with the Fisher information matrix, and to\n regularize the update direction by making it closer to the gradient.\n If damping is adapted during training then this value is used for\n initializing damping varaible.\n (Higher damping means the update looks more like a standard gradient\n update - see Tikhonov regularization.)\n layer_collection: The layer collection object, which holds the fisher\n blocks, kronecker factors, and losses associated with the\n graph. The layer_collection cannot be modified after KfacOptimizer's\n initialization.\n var_list: Optional list or tuple of variables to train. Defaults to the\n list of variables collected in the graph under the key\n `GraphKeys.TRAINABLE_VARIABLES`.\n momentum: The momentum decay constant to use. Only applies when\n momentum_type is 'regular' or 'adam'. (Default: 0.9)\n momentum_type: The type of momentum to use in this optimizer, one of\n 'regular', 'adam', or 'qmodel'. (Default: 'regular')\n norm_constraint: float or Tensor. If specified, the update is scaled down\n so that its approximate squared Fisher norm v^T F v is at most the\n specified value. May only be used with momentum type 'regular'.\n (Default: None)\n name: The name for this optimizer. (Default: 'KFAC')\n estimation_mode: The type of estimator to use for the Fishers. Can be\n 'gradients', 'empirical', 'curvature_propagation', or 'exact'.\n (Default: 'gradients'). See the doc-string for FisherEstimator for\n more a more detailed description of these options.\n colocate_gradients_with_ops: Whether we should request gradients we\n compute in the estimator be colocated with their respective ops.\n (Default: True)\n batch_size: The size of the mini-batch. Only needed when momentum_type\n == 'qmodel' or when automatic adjustment is used. (Default: None)\n cov_devices: Iterable of device strings (e.g. '/gpu:0'). Covariance\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified. Only used\n with (soon-to-be-depcrecated \"convenience\" properties).\n inv_devices: Iterable of device strings (e.g. '/gpu:0'). Inversion\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified. Only used\n with (soon-to-be-depcrecated \"convenience\" properties).\n\n Raises:\n ValueError: If the momentum type is unsupported.\n ValueError: If clipping is used with momentum type other than 'regular'.\n ValueError: If no losses have been registered with layer_collection.\n ValueError: If momentum is non-zero and momentum_type is not 'regular'\n or 'adam'.\n \"\"\"\n\n variables = var_list\n if variables is None:\n variables = tf_variables.trainable_variables()\n\n # Parameters to be passed to the Fisher estimator:\n self._variables = variables\n self._cov_ema_decay = cov_ema_decay\n self._layers = layer_collection\n self._estimation_mode = estimation_mode\n self._colocate_gradients_with_ops = colocate_gradients_with_ops\n self._cov_devices = cov_devices\n self._inv_devices = inv_devices\n\n # The below paramaters are required only if damping needs to be adapated.\n # These parameters can be set by calling\n # set_damping_adaptation_params() explicitly.\n self._damping_adaptation_decay = 0.95\n self._damping_adaptation_interval = 5\n # Check section 6.5 KFAC paper. omega(1) = pow(damping decay, interval)\n self._omega = (\n self._damping_adaptation_decay**self._damping_adaptation_interval)\n self._adapt_damping = False\n self._min_damping = 1e-5\n self._prev_train_batch = None\n self._is_chief = False\n self._loss_fn = None\n self._damping_constant = damping\n self._damping = None\n self._rho = None\n self._prev_loss = None\n self._q_model_change = None\n self._update_damping_op = None\n\n momentum_type = momentum_type.lower()\n legal_momentum_types = [\"regular\", \"adam\", \"qmodel\"]\n\n if momentum_type not in legal_momentum_types:\n raise ValueError(\"Unsupported momentum type {}. Must be one of {}.\"\n .format(momentum_type, legal_momentum_types))\n if momentum_type != \"regular\" and norm_constraint is not None:\n raise ValueError(\"Update clipping is only supported with momentum \"\n \"type 'regular'.\")\n if momentum_type not in [\"regular\", \"adam\"] and momentum != 0:\n raise ValueError(\"Momentum must be unspecified if using a momentum_type \"\n \"other than 'regular' or 'adam'.\")\n\n # Extra parameters of the optimizer\n self._momentum = momentum\n self._momentum_type = momentum_type\n self._norm_constraint = norm_constraint\n self._batch_size = batch_size\n\n with variable_scope.variable_scope(name):\n self._fisher_est = est.FisherEstimator(\n self._variables,\n self._cov_ema_decay,\n self.damping,\n self._layers,\n exps=(-1,),\n estimation_mode=self._estimation_mode,\n colocate_gradients_with_ops=self._colocate_gradients_with_ops)\n\n super(KfacOptimizer, self).__init__(learning_rate, name=name)\n\n def set_damping_adaptation_params(self,\n is_chief,\n prev_train_batch,\n loss_fn,\n min_damping=1e-5,\n damping_adaptation_decay=0.99,\n damping_adaptation_interval=5):\n \"\"\"Sets parameters required to adapt damping during training.\n\n When called, enables damping adaptation according to the Levenberg-Marquardt\n style rule described in Section 6.5 of \"Optimizing Neural Networks with\n Kronecker-factored Approximate Curvature\".\n\n Note that this function creates Tensorflow variables which store a few\n scalars and are accessed by the ops which update the damping (as part\n of the training op returned by the minimize() method).\n\n Args:\n is_chief: `Boolean`, `True` if the worker is chief.\n prev_train_batch: Training data used to minimize loss in the previous\n step. This will be used to evaluate loss by calling\n `loss_fn(prev_train_batch)`.\n loss_fn: `function` that takes as input training data tensor and returns\n a scalar loss.\n min_damping: `float`(Optional), Minimum value the damping parameter\n can take. Default value 1e-5.\n damping_adaptation_decay: `float`(Optional), The `damping` parameter is\n multipled by the `damping_adaptation_decay` every\n `damping_adaptation_interval` number of iterations. Default value 0.99.\n damping_adaptation_interval: `int`(Optional), Number of steps in between\n updating the `damping` parameter. Default value 5.\n\n Raises:\n ValueError: If `set_damping_adaptation_params` is already called and the\n the `adapt_damping` is `True`.\n \"\"\"\n if self._adapt_damping:\n raise ValueError(\"Damping adaptation parameters already set.\")\n\n with variable_scope.variable_scope(self.get_name()):\n self._adapt_damping = True\n self._is_chief = is_chief\n self._prev_train_batch = prev_train_batch\n self._loss_fn = loss_fn\n self._damping_adaptation_decay = damping_adaptation_decay\n self._damping_adaptation_interval = damping_adaptation_interval\n self._omega = (\n self._damping_adaptation_decay**self._damping_adaptation_interval)\n self._min_damping = min_damping\n\n self._rho = variable_scope.get_variable(\n \"rho\", shape=(), dtype=dtypes.float32, trainable=False) # LM ratio.\n self._prev_loss = variable_scope.get_variable(\n \"prev_loss\", shape=(), dtype=dtypes.float32, trainable=False)\n self._q_model_change = variable_scope.get_variable(\n \"q_model_change\", shape=(), dtype=dtypes.float32, trainable=False)\n self._damping = variable_scope.get_variable(\n \"damping\", initializer=self._damping_constant, trainable=False)\n\n @property\n def cov_update_thunks(self):\n self._maybe_make_and_save_everything()\n return self._cov_update_thunks\n\n @property\n def cov_update_ops(self):\n self._maybe_make_and_save_everything()\n return self._cov_update_ops\n\n @property\n def cov_update_op(self):\n self._maybe_make_and_save_everything()\n return self._cov_update_op\n\n @property\n def inv_update_thunks(self):\n self._maybe_make_and_save_everything()\n return self._inv_update_thunks\n\n @property\n def inv_update_ops(self):\n self._maybe_make_and_save_everything()\n return self._inv_update_ops\n\n @property\n def inv_update_op(self):\n self._maybe_make_and_save_everything()\n return self._inv_update_op\n\n @property\n def variables(self):\n return self._variables\n\n @property\n def damping(self):\n if self._damping:\n return self._damping\n else:\n return self._damping_constant\n\n @property\n def damping_adaptation_interval(self):\n return self._damping_adaptation_interval\n\n def _maybe_make_and_save_everything(self):\n if not self._fisher_est.made_vars():\n warnings.warn(\"These convenience properties will be depcrecated soon. \"\n \"Please use explicit op/thunk creation methods instead \"\n \"(e.g. make_ops_and_vars_round_robin, etc).\",\n DeprecationWarning)\n (self._cov_update_ops, self._cov_update_op, self._inv_update_ops,\n self._inv_update_op, self._cov_update_thunks,\n self._inv_update_thunks) = self.make_ops_and_vars_round_robin(\n cov_devices=self._cov_devices,\n inv_devices=self._inv_devices)\n\n def make_ops_and_vars(self):\n \"\"\"Make ops and vars with no specific device placement.\n\n See make_ops_and_vars_round_robin for details.\n\n Returns:\n cov_update_ops: List of ops that compute the cov updates. Corresponds\n one-to-one with the list of factors given by the \"factors\" property.\n cov_update_op: cov_update_ops grouped into a single op.\n inv_update_ops: List of ops that compute the inv updates. Corresponds\n one-to-one with the list of factors given by the \"factors\" property.\n cov_update_op: cov_update_ops grouped into a single op.\n inv_update_op: inv_update_ops grouped into a single op.\n \"\"\"\n with variable_scope.variable_scope(self.get_name()):\n return self._fisher_est.make_ops_and_vars()\n\n def make_ops_and_vars_round_robin(self, cov_devices=None, inv_devices=None):\n \"\"\"Make ops and vars with a round-robin device placement strategy.\n\n For each factor, all of that factor's cov variables and their associated\n update ops will be placed on a particular device. A new device is chosen\n for each factor by cycling through list of devices in the cov_devices\n argument. If cov_devices is None then no explicit device placement occurs.\n\n An analogous strategy is followed for inverse update ops, with the list of\n devices being given by the inv_devices argument.\n\n Inverse variables on the other hand are not placed on any specific device\n (they will just use the current the device placement context, whatever\n that happens to be). The idea is that the inverse variable belong where\n they will be accessed most often, which is the device that actually applies\n the preconditioner to the gradient. The user will be responsible for setting\n the device context for this.\n\n Args:\n cov_devices: Iterable of device strings (e.g. '/gpu:0'). Covariance\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified.\n inv_devices: Iterable of device strings (e.g. '/gpu:0'). Inversion\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified.\n\n Returns:\n cov_update_ops: List of ops that compute the cov updates. Corresponds\n one-to-one with the list of factors given by the \"factors\" property.\n cov_update_op: cov_update_ops grouped into a single op.\n inv_update_ops: List of ops that compute the inv updates. Corresponds\n one-to-one with the list of factors given by the \"factors\" property.\n cov_update_op: cov_update_ops grouped into a single op.\n inv_update_op: inv_update_ops grouped into a single op.\n cov_update_thunks: Thunks that make the ops in cov_update_ops.\n inv_update_thunks: Thunks that make the ops in inv_update_ops.\n \"\"\"\n with variable_scope.variable_scope(self.get_name()):\n return self._fisher_est.make_ops_and_vars_round_robin(\n cov_devices=cov_devices, inv_devices=inv_devices)\n\n def make_vars_and_create_op_thunks_round_robin(self,\n cov_devices=None,\n inv_devices=None):\n \"\"\"Make vars and create op thunks w/ a round-robin device placement strat.\n\n For each factor, all of that factor's cov variables and their associated\n update ops will be placed on a particular device. A new device is chosen\n for each factor by cycling through list of devices in the cov_devices\n argument. If cov_devices is None then no explicit device placement occurs.\n\n An analogous strategy is followed for inverse update ops, with the list of\n devices being given by the inv_devices argument.\n\n Inverse variables on the other hand are not placed on any specific device\n (they will just use the current the device placement context, whatever\n that happens to be). The idea is that the inverse variable belong where\n they will be accessed most often, which is the device that actually applies\n the preconditioner to the gradient. The user will be responsible for setting\n the device context for this.\n\n Args:\n cov_devices: Iterable of device strings (e.g. '/gpu:0'). Covariance\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified.\n inv_devices: Iterable of device strings (e.g. '/gpu:0'). Inversion\n computations will be placed on these devices in a round-robin fashion.\n Can be None, which means that no devices are specified.\n Returns:\n cov_update_thunks: List of cov update thunks. Corresponds one-to-one with\n the list of factors given by the \"factors\" property.\n inv_update_thunks: List of inv update thunks. Corresponds one-to-one with\n the list of factors given by the \"factors\" property.\n \"\"\"\n scope = self.get_name() + \"/\" + self._fisher_est.name\n return self._fisher_est.make_vars_and_create_op_thunks_round_robin(\n scope=scope, cov_devices=cov_devices, inv_devices=inv_devices)\n\n def ops_and_vars_thunks(self):\n \"\"\"Create thunks that make the ops and vars on demand.\n\n This function returns 4 lists of thunks: cov_variable_thunks,\n cov_update_thunks, inv_variable_thunks, and inv_update_thunks.\n\n The length of each list is the number of factors and the i-th element of\n each list corresponds to the i-th factor (given by the \"factors\" property).\n\n Note that the execution of these thunks must happen in a certain\n partial order. The i-th element of cov_variable_thunks must execute\n before the i-th element of cov_update_thunks (and also the i-th element\n of inv_update_thunks). Similarly, the i-th element of inv_variable_thunks\n must execute before the i-th element of inv_update_thunks.\n\n TL;DR (oversimplified): Execute the thunks according to the order that\n they are returned.\n\n Returns:\n cov_variable_thunks: A list of thunks that make the cov variables.\n cov_update_thunks: A list of thunks that make the cov update ops.\n inv_variable_thunks: A list of thunks that make the inv variables.\n inv_update_thunks: A list of thunks that make the inv update ops.\n \"\"\"\n scope = self.get_name() + \"/\" + self._fisher_est.name\n return self._fisher_est.ops_and_vars_thunks(scope=scope)\n\n def minimize(self, *args, **kwargs):\n # Should this variable scope encompass everything below? Or will the super-\n # class make another copy of the same name scope?\n with variable_scope.variable_scope(self.get_name()):\n kwargs[\"var_list\"] = kwargs.get(\"var_list\") or self.variables\n if set(kwargs[\"var_list\"]) != set(self.variables):\n raise ValueError(\"var_list doesn't match with set of Fisher-estimating \"\n \"variables.\")\n if self._adapt_damping and self._is_chief:\n global_step = kwargs.get(\"global_step\", None)\n if not global_step:\n raise KeyError(\"global_step needs to be passed to optimizer.minimize \"\n \"if damping parameter is adapted.\")\n update_damping_op = self._update_damping(self._prev_train_batch,\n global_step)\n with ops.control_dependencies([update_damping_op]):\n loss = args[0]\n loss_assign_op = state_ops.assign(self._prev_loss, loss)\n train_op = super(KfacOptimizer, self).minimize(*args, **kwargs)\n return control_flow_ops.group(loss_assign_op, train_op)\n else:\n return super(KfacOptimizer, self).minimize(*args, **kwargs)\n\n def compute_gradients(self, *args, **kwargs):\n # args[1] could be our var_list\n if len(args) > 1:\n var_list = args[1]\n else:\n kwargs[\"var_list\"] = kwargs.get(\"var_list\") or self.variables\n var_list = kwargs[\"var_list\"]\n if set(var_list) != set(self.variables):\n raise ValueError(\"var_list doesn't match with set of Fisher-estimating \"\n \"variables.\")\n return super(KfacOptimizer, self).compute_gradients(*args, **kwargs)\n\n def apply_gradients(self, grads_and_vars, *args, **kwargs):\n \"\"\"Applies gradients to variables.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n *args: Additional arguments for super.apply_gradients.\n **kwargs: Additional keyword arguments for super.apply_gradients.\n\n Returns:\n An `Operation` that applies the specified gradients.\n \"\"\"\n self._maybe_make_and_save_everything()\n\n # In Python 3, grads_and_vars can be a zip() object which can only be\n # iterated over once. By converting it to a list, we ensure that it can be\n # iterated over more than once.\n grads_and_vars = list(grads_and_vars)\n\n # Compute step.\n steps_and_vars = self._compute_update_steps(grads_and_vars)\n\n # Update trainable variables with this step.\n return super(KfacOptimizer, self).apply_gradients(steps_and_vars, *args,\n **kwargs)\n\n def _squared_fisher_norm(self, grads_and_vars, precon_grads_and_vars):\n \"\"\"Computes the squared (approximate) Fisher norm of the updates.\n\n This is defined as v^T F v, where F is the approximate Fisher matrix\n as computed by the estimator, and v = F^{-1} g, where g is the gradient.\n This is computed efficiently as v^T g.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n precon_grads_and_vars: List of (preconditioned gradient, variable) pairs.\n Must be the result of calling `self._fisher_est.multiply_inverse`\n on `grads_and_vars`.\n\n Returns:\n Scalar representing the squared norm.\n\n Raises:\n ValueError: if the two list arguments do not contain the same variables,\n in the same order.\n \"\"\"\n for (_, gvar), (_, pgvar) in zip(grads_and_vars, precon_grads_and_vars):\n if gvar is not pgvar:\n raise ValueError(\"The variables referenced by the two arguments \"\n \"must match.\")\n terms = [\n math_ops.reduce_sum(grad * pgrad)\n for (grad, _), (pgrad, _) in zip(grads_and_vars, precon_grads_and_vars)\n ]\n return math_ops.reduce_sum(terms)\n\n def _update_clip_coeff(self, grads_and_vars, precon_grads_and_vars):\n \"\"\"Computes the scale factor for the update to satisfy the norm constraint.\n\n Defined as min(1, sqrt(c / r^T F r)), where c is the norm constraint,\n F is the approximate Fisher matrix, and r is the update vector, i.e.\n -alpha * v, where alpha is the learning rate, and v is the preconditioned\n gradient.\n\n This is based on Section 5 of Ba et al., Distributed Second-Order\n Optimization using Kronecker-Factored Approximations. Note that they\n absorb the learning rate alpha (which they denote eta_max) into the formula\n for the coefficient, while in our implementation, the rescaling is done\n before multiplying by alpha. Hence, our formula differs from theirs by a\n factor of alpha.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n precon_grads_and_vars: List of (preconditioned gradient, variable) pairs.\n Must be the result of calling `self._fisher_est.multiply_inverse`\n on `grads_and_vars`.\n\n Returns:\n Scalar representing the coefficient which should be applied to the\n preconditioned gradients to satisfy the norm constraint.\n \"\"\"\n sq_norm_grad = self._squared_fisher_norm(grads_and_vars,\n precon_grads_and_vars)\n sq_norm_up = sq_norm_grad * self._learning_rate**2\n return math_ops.minimum(1.,\n math_ops.sqrt(self._norm_constraint / sq_norm_up))\n\n def _clip_updates(self, grads_and_vars, precon_grads_and_vars):\n \"\"\"Rescales the preconditioned gradients to satisfy the norm constraint.\n\n Rescales the preconditioned gradients such that the resulting update r\n (after multiplying by the learning rate) will satisfy the norm constraint.\n This constraint is that r^T F r <= C, where F is the approximate Fisher\n matrix, and C is the norm_constraint attribute. See Section 5 of\n Ba et al., Distributed Second-Order Optimization using Kronecker-Factored\n Approximations.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n precon_grads_and_vars: List of (preconditioned gradient, variable) pairs.\n Must be the result of calling `self._fisher_est.multiply_inverse`\n on `grads_and_vars`.\n\n Returns:\n List of (rescaled preconditioned gradient, variable) pairs.\n \"\"\"\n coeff = self._update_clip_coeff(grads_and_vars, precon_grads_and_vars)\n return [(pgrad * coeff, var) for pgrad, var in precon_grads_and_vars]\n\n def _compute_prev_updates(self, variables):\n \"\"\"Computes previous updates as negative velocities scaled by learning rate.\n\n Args:\n variables: List of variables in the graph that the update will be\n applied to.\n\n Returns:\n List of previous updates applied to the `variables`.\n \"\"\"\n return list(\n -1 * self._learning_rate * self._zeros_slot(var, \"velocity\", self._name)\n for var in variables)\n\n def _compute_qmodel_hyperparams(self, precon_grads, prev_updates, grads,\n variables):\n \"\"\"Compute optimal update hyperparameters from the quadratic model.\n\n More specifically, if L is the loss we minimize a quadratic approximation\n of L(theta + d) which we denote by qmodel(d) with\n d = alpha*precon_grad + mu*prev_update with respect to alpha and mu, where\n\n qmodel(d) = (1/2) * d^T * B * d + grad^T*d + L(theta) .\n\n Unlike in the KL clipping approach we use the non-approximated quadratic\n model where the curvature matrix C is the true Fisher on the current\n mini-batch (computed without any approximations beyond mini-batch sampling),\n with the usual Tikhonov damping/regularization applied,\n\n C = F + damping * I\n\n See Section 7 of https://arxiv.org/abs/1503.05671 for a derivation of\n the formula. See Appendix C for a discussion of the trick of using\n a factorized Fisher matrix to more efficiently compute the required\n vector-matrix-vector products.\n\n Note that the elements of all 4 lists passed to this function must\n be in correspondence with each other.\n\n Args:\n precon_grads: List of preconditioned gradients.\n prev_updates: List of updates computed at the previous iteration.\n grads: List of gradients.\n variables: List of variables in the graph that the update will be\n applied to. (Note that this function doesn't actually apply the\n update.)\n\n Returns:\n (alpha, mu, qmodel_change), where alpha and mu are chosen to optimize the\n quadratic model, and\n qmodel_change = qmodel(alpha*precon_grad + mu*prev_update) - qmodel(0)\n = qmodel(alpha*precon_grad + mu*prev_update) - L(theta).\n \"\"\"\n\n cmvpc = cmvp.CurvatureMatrixVectorProductComputer(self._layers.losses,\n variables)\n\n # compute the matrix-vector products with the transposed Fisher factor\n fft_precon_grads = cmvpc.multiply_fisher_factor_transpose(precon_grads)\n fft_prev_updates = cmvpc.multiply_fisher_factor_transpose(prev_updates)\n\n batch_size = math_ops.cast(\n self._batch_size, dtype=fft_precon_grads[0].dtype)\n\n # compute the entries of the 2x2 matrix\n m_11 = (\n _inner_product_list(fft_precon_grads, fft_precon_grads) / batch_size +\n self.damping * _inner_product_list(precon_grads, precon_grads))\n\n m_21 = (\n _inner_product_list(fft_prev_updates, fft_precon_grads) / batch_size +\n self.damping * _inner_product_list(prev_updates, precon_grads))\n\n m_22 = (\n _inner_product_list(fft_prev_updates, fft_prev_updates) / batch_size +\n self.damping * _inner_product_list(prev_updates, prev_updates))\n\n def non_zero_prevupd_case():\n r\"\"\"Computes optimal (alpha, mu) given non-zero previous update.\n\n We solve the full 2x2 linear system. See Martens & Grosse (2015),\n Section 7, definition of $\\alpha^*$ and $\\mu^*$.\n\n Returns:\n (alpha, mu, qmodel_change), where alpha and mu are chosen to optimize\n the quadratic model, and\n qmodel_change = qmodel(alpha*precon_grad + mu*prev_update) - qmodel(0).\n \"\"\"\n m = ops.convert_to_tensor([[m_11, m_21], [m_21, m_22]])\n\n c = ops.convert_to_tensor([[_inner_product_list(grads, precon_grads)],\n [_inner_product_list(grads, prev_updates)]])\n\n sol = -1. * _two_by_two_solve(m, c)\n alpha = sol[0]\n mu = sol[1]\n qmodel_change = 0.5 * math_ops.reduce_sum(sol * c)\n\n return alpha, mu, qmodel_change\n\n def zero_prevupd_case():\n r\"\"\"Computes optimal (alpha, mu) given all-zero previous update.\n\n The linear system reduces to 1x1. See Martens & Grosse (2015),\n Section 6.4, definition of $\\alpha^*$.\n\n Returns:\n (alpha, 0.0, qmodel_change), where alpha is chosen to optimize the\n quadratic model, and\n qmodel_change = qmodel(alpha*precon_grad) - qmodel(0)\n \"\"\"\n m = m_11\n c = _inner_product_list(grads, precon_grads)\n\n alpha = -c / m\n mu = 0.0\n qmodel_change = 0.5 * alpha * c\n\n return alpha, mu, qmodel_change\n\n return control_flow_ops.cond(\n math_ops.equal(m_22, 0.0), zero_prevupd_case, non_zero_prevupd_case)\n\n def _assign_q_model_change(self, q_model_change):\n \"\"\"Assigns `q_model_change` to `self._q_model_change` if damping is adapted.\n\n Note only the chief worker does the assignment.\n\n Args:\n q_model_change: Scalar tensor of type `float32`.\n\n Returns:\n If `adapt_damping` is `True` then returns an assign op, Otherwise returns\n a no_op().\n \"\"\"\n if self._adapt_damping and self._is_chief:\n q_model_assign_op = state_ops.assign(self._q_model_change, q_model_change)\n else:\n q_model_assign_op = control_flow_ops.no_op()\n return q_model_assign_op\n\n def _compute_qmodel_hyperparams_wrapper(self, grads_and_vars,\n precon_grads_and_vars):\n \"\"\"Wrapper function for `self._compute_qmodel_hyperparams`.\n\n Constructs a list of preconditioned gradients and variables. Also creates a\n op to asssign the computed q model change to `self._q_model_change`.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n precon_grads_and_vars: List of (preconditioned gradients, variable)\n pairs.\n\n Returns:\n (alpha, mu, q_model_assign_op), where alpha and mu are chosen to optimize\n the quadratic model, `q_model_assign_op` assigns the computed q model\n change to `self._q_model_change`.\n \"\"\"\n precon_grads = list(\n precon_grad for (precon_grad, _) in precon_grads_and_vars)\n grads = list(grad for (grad, _) in grads_and_vars)\n variables = list(var for (_, var) in grads_and_vars)\n prev_updates = self._compute_prev_updates(variables)\n # Compute optimal velocity update parameters according to quadratic model\n alpha, mu, q_model_change = self._compute_qmodel_hyperparams(\n precon_grads, prev_updates, grads, variables)\n\n return alpha, mu, self._assign_q_model_change(q_model_change)\n\n def _compute_update_steps(self, grads_and_vars):\n \"\"\"Computes the update steps for the variables given the gradients.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs.\n\n Returns:\n A list of tuple (assign_op ,var) where `assign_op` assigns the update\n steps to `var`.\n \"\"\"\n\n if self._momentum_type == \"regular\":\n # Compute \"preconditioned\" gradient.\n precon_grads_and_vars = self._fisher_est.multiply_inverse(grads_and_vars)\n\n # Apply \"KL clipping\" if asked for.\n if self._norm_constraint is not None:\n precon_grads_and_vars = self._clip_updates(grads_and_vars,\n precon_grads_and_vars)\n\n # Update the velocity with this and return it as the step.\n if self._adapt_damping and self._is_chief:\n _, _, q_model_assign_op = self._compute_qmodel_hyperparams_wrapper(\n grads_and_vars, precon_grads_and_vars)\n with ops.control_dependencies([q_model_assign_op]):\n return self._update_velocities(precon_grads_and_vars, self._momentum)\n else:\n return self._update_velocities(precon_grads_and_vars, self._momentum)\n elif self._momentum_type == \"adam\":\n # Update velocity.\n velocities_and_vars = self._update_velocities(grads_and_vars,\n self._momentum)\n # Return \"preconditioned\" velocity vector as the step.\n return self._fisher_est.multiply_inverse(velocities_and_vars)\n\n elif self._momentum_type == \"qmodel\":\n # Compute \"preconditioned\" gradient.\n precon_grads_and_vars = self._fisher_est.multiply_inverse(grads_and_vars)\n\n # Compute optimal velocity update parameters according to quadratic model\n alpha, mu, q_model_assign_op = self._compute_qmodel_hyperparams_wrapper(\n grads_and_vars, precon_grads_and_vars)\n\n with ops.control_dependencies([q_model_assign_op]):\n return self._update_velocities(\n precon_grads_and_vars, mu, vec_coeff=-alpha)\n\n def _update_velocities(self, vecs_and_vars, decay, vec_coeff=1.0):\n \"\"\"Updates the velocities of the variables with the given vectors.\n\n Args:\n vecs_and_vars: List of (vector, variable) pairs.\n decay: How much to decay the old velocity by. This is often referred to\n as the 'momentum constant'.\n vec_coeff: Coefficient to apply to the vectors before adding them to the\n velocity.\n\n Returns:\n A list of (velocity, var) indicating the new velocity for each var.\n \"\"\"\n\n def _update_velocity(vec, var):\n velocity = self._zeros_slot(var, \"velocity\", self._name)\n with ops.colocate_with(velocity):\n # NOTE(mattjj): read/modify/write race condition not suitable for async.\n\n # Compute the new velocity for this variable.\n new_velocity = decay * velocity + vec_coeff * vec\n\n # Save the updated velocity.\n return (array_ops.identity(velocity.assign(new_velocity)), var)\n\n # Go through variable and update its associated part of the velocity vector.\n return [_update_velocity(vec, var) for vec, var in vecs_and_vars]\n\n # TODO(b/73448937): Move all update damping code to a separate class/function.\n def _update_damping(self, prev_batch, global_step):\n \"\"\"Adapts damping parameter. Check KFAC (Section 6.5) for the details.\n\n The damping parameter is updated according to the Levenberg-Marquardt rule\n every `self._damping_adaptation_interval` iterations.\n\n Args:\n prev_batch: Tensor or tuple of tensors which can be passed to\n `self._loss_fn` to evaluate loss.\n global_step: `Variable` which keeps track of number of times the training\n variables have been updated.\n Returns:\n A `tf.cond` op which updates the damping parameter.\n \"\"\"\n def compute_damping():\n \"\"\"\"Adapts damping parameter based on \"reduction ratio\".\n\n Reduction ratio captures how closely the quadratic approximation to the\n loss function approximates the actual loss within a trust region. The\n damping update tries to make the damping as small as possible while\n maintaining the property that the quadratic model remains a good local\n approximation to the loss function.\n\n Returns:\n An Op to assign newly computed damping value to `self._damping`.\n \"\"\"\n prev_batch_loss = self._loss_fn(prev_batch)\n with ops.control_dependencies([prev_batch_loss]):\n rho_assign = self._rho.assign(\n (prev_batch_loss - self._prev_loss) / self._q_model_change)\n with ops.control_dependencies([rho_assign]):\n new_damping = control_flow_ops.case(\n [(self._rho < 0.25, lambda: self.damping / self._omega),\n (self._rho > 0.75, lambda: self.damping * self._omega)],\n lambda: self.damping)\n with ops.control_dependencies([new_damping]):\n new_damping_min = math_ops.maximum(new_damping, self._min_damping)\n return control_flow_ops.group(self._damping.assign(new_damping_min))\n\n return control_flow_ops.cond(\n math_ops.equal(\n math_ops.mod(global_step + 1, self._damping_adaptation_interval),\n 0), compute_damping, control_flow_ops.no_op)\n\n\ndef _inner_product_list(list1, list2):\n return math_ops.add_n(\n [math_ops.reduce_sum(elt1 * elt2) for elt1, elt2 in zip(list1, list2)])\n\n\ndef _two_by_two_solve(m, c):\n # it might be better just to crank out the exact formula for 2x2 inverses\n return math_ops.matmul(linalg_ops.matrix_inverse(m), c)\n" ]
[ [ "tensorflow.python.data.ops.readers.TextLineDataset", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.ops.parsing_ops.decode_csv", "tensorflow.python.platform.gfile.Glob", "tensorflow.contrib.data.python.ops.shuffle_ops.shuffle_and_repeat", "tensorflow.python.data.util.nest.map_structure", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.data.util.nest.flatten", "tensorflow.python.ops.parsing_ops.parse_example", "tensorflow.python.data.ops.dataset_ops.Dataset.list_files", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.math_ops.sqrt", "tensorflow.python.ops.variables.trainable_variables", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.linalg_ops.matrix_inverse", "tensorflow.python.ops.math_ops.cast", "tensorflow.contrib.kfac.python.ops.estimator.FisherEstimator", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.contrib.kfac.python.ops.curvature_matrix_vector_products.CurvatureMatrixVectorProductComputer", "tensorflow.python.ops.control_flow_ops.case", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.ops.variable_scope.get_variable", "tensorflow.python.ops.math_ops.mod", "tensorflow.python.ops.math_ops.maximum", "tensorflow.python.ops.math_ops.reduce_sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.10", "1.4" ] } ]
yicrane/Real-SR
[ "a6e380b791129b80fe58bf282089c0cfd9159b36", "a6e380b791129b80fe58bf282089c0cfd9159b36" ]
[ "codes/preprocess/collect_noise.py", "codes/preprocess/ct_collect_noise_sp32v160m0_yic_210525.py" ]
[ "from PIL import Image\nimport numpy as np\nimport os.path as osp\nimport glob\nimport os\nimport argparse\nimport yaml\n\nparser = argparse.ArgumentParser(description='create a dataset')\nparser.add_argument('--dataset', default='df2k', type=str, help='selecting different datasets')\nparser.add_argument('--artifacts', default='', type=str, help='selecting different artifacts type')\nparser.add_argument('--cleanup_factor', default=2, type=int, help='downscaling factor for image cleanup')\nparser.add_argument('--upscale_factor', default=4, type=int, choices=[4], help='super resolution upscale factor')\nopt = parser.parse_args()\n\n# define input and target directories\nwith open('./preprocess/paths.yml', 'r') as stream:\n PATHS = yaml.load(stream)\n\n\ndef noise_patch(rgb_img, sp, max_var, min_mean):\n img = rgb_img.convert('L')\n rgb_img = np.array(rgb_img)\n img = np.array(img)\n\n w, h = img.shape\n collect_patchs = []\n\n for i in range(0, w - sp, sp):\n for j in range(0, h - sp, sp):\n patch = img[i:i + sp, j:j + sp]\n var_global = np.var(patch)\n mean_global = np.mean(patch)\n if var_global < max_var and mean_global > min_mean:\n rgb_patch = rgb_img[i:i + sp, j:j + sp, :]\n collect_patchs.append(rgb_patch)\n\n return collect_patchs\n\n\nif __name__ == '__main__':\n\n if opt.dataset == 'df2k':\n img_dir = PATHS[opt.dataset][opt.artifacts]['source']\n noise_dir = PATHS['datasets']['df2k'] + '/Corrupted_noise'\n sp = 256\n max_var = 20\n min_mean = 0\n else:\n img_dir = PATHS[opt.dataset][opt.artifacts]['hr']['train']\n noise_dir = PATHS['datasets']['dped'] + '/DPEDiphone_noise_sp32v20m50'\n sp = 256\n max_var = 20\n min_mean = 50\n\n assert not os.path.exists(noise_dir)\n os.mkdir(noise_dir)\n\n img_paths = sorted(glob.glob(osp.join(img_dir, '*.png')))\n cnt = 0\n for path in img_paths:\n img_name = osp.splitext(osp.basename(path))[0]\n print('**********', img_name, '**********')\n img = Image.open(path).convert('RGB')\n patchs = noise_patch(img, sp, max_var, min_mean)\n for idx, patch in enumerate(patchs):\n save_path = osp.join(noise_dir, '{}_{:03}.png'.format(img_name, idx))\n cnt += 1\n print('collect:', cnt, save_path)\n Image.fromarray(patch).save(save_path)\n", "from PIL import Image\nimport numpy as np\nimport os.path as osp\nimport glob\nimport os\nimport argparse\nimport yaml\n\nparser = argparse.ArgumentParser(description='create a dataset')\nparser.add_argument('--dataset', default='df2k', type=str, help='selecting different datasets')\nparser.add_argument('--artifacts', default='', type=str, help='selecting different artifacts type')\nparser.add_argument('--cleanup_factor', default=2, type=int, help='downscaling factor for image cleanup')\n#yic\n#parser.add_argument('--cleanup_factor', default=2, type=int, help='downscaling factor for image cleanup')\nparser.add_argument('--upscale_factor', default=4, type=int, choices=[4], help='super resolution upscale factor')\nopt = parser.parse_args()\n\n# define input and target directories\nwith open('./preprocess/paths_ct_210522.yml', 'r') as stream:\n PATHS = yaml.load(stream)\n\n\ndef noise_patch(rgb_img, sp, max_var, min_mean):\n img = rgb_img.convert('L')\n rgb_img = np.array(rgb_img)\n img = np.array(img)\n\n w, h = img.shape\n collect_patchs = []\n\n for i in range(0, w - sp, sp):\n for j in range(0, h - sp, sp):\n patch = img[i:i + sp, j:j + sp]\n var_global = np.var(patch)\n mean_global = np.mean(patch)\n if var_global < max_var and mean_global > min_mean:\n rgb_patch = rgb_img[i:i + sp, j:j + sp, :]\n collect_patchs.append(rgb_patch)\n\n return collect_patchs\n\n\nif __name__ == '__main__':\n\n if opt.dataset == 'df2k':\n img_dir = PATHS[opt.dataset][opt.artifacts]['source']\n noise_dir = PATHS['datasets']['df2k'] + '/Corrupted_noise'\n sp = 256\n max_var = 20\n min_mean = 0\n else:\n img_dir = PATHS[opt.dataset][opt.artifacts]['hr']['train']\n noise_dir = PATHS['datasets']['dped'] + '/DPEDiphone_noise'\n sp = 32\n max_var = 160\n min_mean = 0\n \n assert not os.path.exists(noise_dir)\n os.mkdir(noise_dir)\n\n img_paths = sorted(glob.glob(osp.join(img_dir, '*.png')))\n cnt = 0\n for path in img_paths:\n img_name = osp.splitext(osp.basename(path))[0]\n print('**********', img_name, '**********')\n img = Image.open(path).convert('RGB')\n patchs = noise_patch(img, sp, max_var, min_mean)\n for idx, patch in enumerate(patchs):\n save_path = osp.join(noise_dir, '{}_{:03}.png'.format(img_name, idx))\n cnt += 1\n print('collect:', cnt, save_path)\n Image.fromarray(patch).save(save_path)\n" ]
[ [ "numpy.var", "numpy.array", "numpy.mean" ], [ "numpy.var", "numpy.array", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jalavery/gnomeR
[ "4f165774eb3c5f442881a915ee70e18a5f33b387", "4f165774eb3c5f442881a915ee70e18a5f33b387" ]
[ "inst/CnaAnnotator.py", "inst/AnnotatorCore.py" ]
[ "import argparse\n# from AnnotatorCore import *\nimport sys\nimport csv\nimport requests\nimport os.path\nimport logging\nimport re\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom datetime import date\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger('CnaAnnotator')\n\n\ndef main(argv):\n if argv.help:\n log.info('\\n'\n 'CnaAnnotator.py -i <input CNA file> -o <output CNA file> [-p previous results] [-c <input clinical file>] [-s sample list filter] [-t <default tumor type>] [-u oncokb-base-url] [-b oncokb_api_bear_token] [-z annotate_gain_loss]\\n'\n ' Input CNA file should follow the GISTIC output (https://docs.cbioportal.org/5.1-data-loading/data-loading/file-formats#data-file-1)\\n'\n ' Essential clinical columns:\\n'\n ' SAMPLE_ID: sample ID\\n'\n ' Cancer type will be assigned based on the following priority:\\n'\n ' 1) ONCOTREE_CODE in clinical data file\\n'\n ' 2) ONCOTREE_CODE exist in MAF\\n'\n ' 3) default tumor type (-t)\\n'\n ' We do not annotate Gain and Loss by default, add -z to include the analysis. See https://github.com/oncokb/oncokb-annotator/issues/51 for more information.\\n'\n ' Default OncoKB base url is https://www.oncokb.org')\n sys.exit()\n if argv.input_file == '' or argv.output_file == '' or argv.oncokb_api_bearer_token == '':\n log.info('for help: python CnaAnnotator.py -h')\n sys.exit(2)\n if argv.sample_ids_filter:\n setsampleidsfileterfile(argv.sample_ids_filter)\n if argv.oncokb_api_url:\n setoncokbbaseurl(argv.oncokb_api_url)\n setoncokbapitoken(argv.oncokb_api_bearer_token)\n\n cancertypemap = {}\n if argv.input_clinical_file:\n readCancerTypes(argv.input_clinical_file, cancertypemap)\n\n log.info('annotating %s ...' % argv.input_file)\n processcnagisticdata(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type,\n cancertypemap, argv.annotate_gain_loss)\n\n log.info('done!')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument('-h', dest='help', action=\"store_true\", default=False)\n parser.add_argument('-i', dest='input_file', default='', type=str)\n parser.add_argument('-o', dest='output_file', default='', type=str)\n parser.add_argument('-p', dest='previous_result_file', default='', type=str)\n parser.add_argument('-c', dest='input_clinical_file', default='', type=str)\n parser.add_argument('-s', dest='sample_ids_filter', default='', type=str)\n parser.add_argument('-t', dest='default_cancer_type', default='', type=str)\n parser.add_argument('-u', dest='oncokb_api_url', default='', type=str)\n parser.add_argument('-b', dest='oncokb_api_bearer_token', default='', type=str)\n parser.add_argument('-z', dest='annotate_gain_loss', action=\"store_true\", default=False)\n parser.set_defaults(func=main)\n\n args = parser.parse_args()\n args.func(args)\n", "import json\nimport sys\nimport csv\nfrom enum import Enum\n\nimport requests\nimport os.path\nimport logging\nimport re\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom datetime import date\nimport ctypes as ct\n\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n\nlog = logging.getLogger('AnnotatorCore')\n\ncsv.field_size_limit(int(ct.c_ulong(-1).value // 2)) # Deal with overflow problem on Windows, https://stackoverflow.com/questions/15063936/csv-error-field-larger-than-field-limit-131072\nsizeLimit = csv.field_size_limit()\ncsv.field_size_limit(2**(31)-1) # for reading large files\n\noncokbapiurl = \"https://www.oncokb.org/api/v1\"\noncokbapibearertoken = \"\"\n\n\ndef setoncokbbaseurl(u):\n global oncokbapiurl\n oncokbapiurl = u.rstrip('/') + '/api/v1'\n\ndef setoncokbapitoken(t):\n global oncokbapibearertoken\n oncokbapibearertoken = t.strip()\n\ncancerhotspotsbaseurl = \"http://www.cancerhotspots.org\"\ndef setcancerhotspotsbaseurl(u):\n global cancerhotspotsbaseurl\n cancerhotspotsbaseurl = u\n\n_3dhotspotsbaseurl = \"http://www.3dhotspots.org\"\ndef set3dhotspotsbaseurl(u):\n global _3dhotspotsbaseurl\n _3dhotspotsbaseurl = u\n\nsampleidsfilter = None\ndef setsampleidsfileterfile(f):\n global sampleidsfilter\n content = [line.rstrip() for line in open(f)]\n sampleidsfilter = set(content)\n log.info(len(sampleidsfilter))\n\n\nGENE_IN_ONCOKB_HEADER = 'GENE_IN_ONCOKB'\nVARIANT_IN_ONCOKB_HEADER = 'VARIANT_IN_ONCOKB'\n\nGENE_IN_ONCOKB_DEFAULT = 'False'\nVARIANT_IN_ONCOKB_DEFAULT = 'False'\n\nlevels = [\n 'LEVEL_1',\n 'LEVEL_2',\n 'LEVEL_3A',\n 'LEVEL_3B',\n 'LEVEL_4',\n 'LEVEL_R1',\n 'LEVEL_R2',\n 'LEVEL_R3'\n]\n\ndxLevels = [\n 'LEVEL_Dx1',\n 'LEVEL_Dx2',\n 'LEVEL_Dx3'\n]\n\npxLevels = [\n 'LEVEL_Px1',\n 'LEVEL_Px2',\n 'LEVEL_Px3'\n]\n\nmutationtypeconsequencemap = {\n '3\\'Flank': ['any'],\n '5\\'Flank ': ['any'],\n 'Targeted_Region': ['inframe_deletion', 'inframe_insertion'],\n 'COMPLEX_INDEL': ['inframe_deletion', 'inframe_insertion'],\n 'ESSENTIAL_SPLICE_SITE': ['feature_truncation'],\n 'Exon skipping': ['inframe_deletion'],\n 'Frameshift deletion': ['frameshift_variant'],\n 'Frameshift insertion': ['frameshift_variant'],\n 'FRAMESHIFT_CODING': ['frameshift_variant'],\n 'Frame_Shift_Del': ['frameshift_variant'],\n 'Frame_Shift_Ins': ['frameshift_variant'],\n 'Fusion': ['fusion'],\n 'Indel': ['frameshift_variant', 'inframe_deletion', 'inframe_insertion'],\n 'In_Frame_Del': ['inframe_deletion'],\n 'In_Frame_Ins': ['inframe_insertion'],\n 'Missense': ['missense_variant'],\n 'Missense_Mutation': ['missense_variant'],\n 'Nonsense_Mutation': ['stop_gained'],\n 'Nonstop_Mutation': ['stop_lost'],\n 'Splice_Site': ['splice_region_variant'],\n 'Splice_Site_Del': ['splice_region_variant'],\n 'Splice_Site_SNP': ['splice_region_variant'],\n 'splicing': ['splice_region_variant'],\n 'Translation_Start_Site': ['start_lost'],\n 'vIII deletion': ['any']\n}\n\n\n# column headers\nHUGO_HEADERS = ['HUGO_SYMBOL', 'HUGO_GENE_SYMBOL', 'GENE']\nCONSEQUENCE_HEADERS = ['VARIANT_CLASSIFICATION', 'MUTATION_TYPE']\nALTERATION_HEADER = 'ALTERATION'\nHGVSP_SHORT_HEADER = 'HGVSP_SHORT'\nHGVSP_HEADER = 'HGVSP'\nHGVSG_HEADER = 'HGVSG'\nHGVS_HEADERS = [ALTERATION_HEADER, HGVSP_SHORT_HEADER, HGVSP_HEADER, HGVSG_HEADER, 'AMINO_ACID_CHANGE', 'FUSION']\nSAMPLE_HEADERS = ['SAMPLE_ID', 'TUMOR_SAMPLE_BARCODE']\nPROTEIN_START_HEADERS = ['PROTEIN_START']\nPROTEIN_END_HEADERS = ['PROTEIN_END']\nPROTEIN_POSITION_HEADERS = ['PROTEIN_POSITION']\nCANCER_TYPE_HEADERS = ['ONCOTREE_CODE', 'CANCER_TYPE']\nFUSION_HEADERS = ['FUSION']\nREFERENCE_GENOME_HEADERS = ['NCBI_BUILD', 'REFERENCE_GENOME']\n\n# columns for genomic change annotation\nGC_CHROMOSOME_HEADER = 'CHROMOSOME'\nGC_START_POSITION_HEADER = 'START_POSITION'\nGC_END_POSITION_HEADER = 'END_POSITION'\nGC_REF_ALLELE_HEADER = 'REFERENCE_ALLELE'\nGC_VAR_ALLELE_1_HEADER = 'TUMOR_SEQ_ALLELE1'\nGC_VAR_ALLELE_2_HEADER = 'TUMOR_SEQ_ALLELE2'\nGENOMIC_CHANGE_HEADERS = [GC_CHROMOSOME_HEADER, GC_START_POSITION_HEADER, GC_END_POSITION_HEADER, GC_REF_ALLELE_HEADER, GC_VAR_ALLELE_1_HEADER, GC_VAR_ALLELE_2_HEADER]\n\n\nclass QueryType(Enum):\n HGVSP_SHORT = 'HGVSP_SHORT'\n HGVSP = 'HGVSP'\n HGVSG = 'HGVSG'\n GENOMIC_CHANGE = 'GENOMIC_CHANGE'\n\n\nclass ReferenceGenome(Enum):\n GRCH37 = 'GRCh37'\n GRCH38 = 'GRCh38'\n\n\nREQUIRED_QUERY_TYPE_COLUMNS = {\n QueryType.HGVSP_SHORT: [HGVSP_SHORT_HEADER],\n QueryType.HGVSP: [HGVSP_HEADER],\n QueryType.HGVSG: [HGVSG_HEADER],\n QueryType.GENOMIC_CHANGE: GENOMIC_CHANGE_HEADERS\n}\n\nPOST_QUERIES_THRESHOLD = 1000\n\ndef getOncokbInfo():\n ret = ['Files annotated on ' + date.today().strftime('%m/%d/%Y') + \"\\nOncoKB API URL: \"+oncokbapiurl]\n try:\n info = requests.get(oncokbapiurl + \"/info\").json()\n ret.append('\\nOncoKB data version: ' + info['dataVersion']['version']+', released on ' + info['dataVersion']['date'])\n except:\n log.error(\"error when fetch OncoKB info\")\n return ''.join(ret)\n\n\ndef generateReadme(outfile):\n outf = open(outfile, 'w+', 1000)\n outf.write(getOncokbInfo())\n outf.close()\n\ndef gethotspots(url, type):\n hotspots = {}\n response = requests.get(url)\n if response.status_code == 200:\n hotspotsjson = response.json()\n\n for hs in hotspotsjson:\n gene = hs['hugoSymbol']\n start = hs['aminoAcidPosition']['start']\n end = hs['aminoAcidPosition']['end']\n if type is None or hs['type'] == type:\n if gene not in hotspots:\n hotspots[gene] = set()\n for i in range(start, end + 1):\n hotspots[gene].add(i)\n else:\n log.error(\"error when processing %s \\n\" % url +\n \"reason: %s\" % response.reason)\n return hotspots\n\n\ndef makeoncokbpostrequest(url, body):\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer %s' % oncokbapibearertoken\n }\n return requests.post(url, headers=headers, data=json.dumps(body, default=lambda o: o.__dict__))\n\n\ndef makeoncokbgetrequest(url):\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer %s' % oncokbapibearertoken\n }\n return requests.get(url, headers=headers)\n\n\n_3dhotspots = None\n\ndef init_3d_hotspots():\n global _3dhotspots\n _3dhotspots = gethotspots(_3dhotspotsbaseurl+\"/api/hotspots/3d\", None)\n\n\nconversiondict = {'Ala': 'A',\n 'Asx': 'B',\n 'Cys': 'C',\n 'Asp': 'D',\n 'Glu': 'E',\n 'Phe': 'F',\n 'Gly': 'G',\n 'His': 'H',\n 'Ile': 'I',\n 'Lys': 'K',\n 'Leu': 'L',\n 'Met': 'M',\n 'Asn': 'N',\n 'Pro': 'P',\n 'Gln': 'Q',\n 'Arg': 'R',\n 'Ser': 'S',\n 'Thr': 'T',\n 'Val': 'V',\n 'Trp': 'W',\n 'Tyr': 'Y',\n 'Glx': 'Z'\n }\nconversionlist = conversiondict.keys()\ndef conversion(hgvs):\n threecharactersearch = re.findall('[a-zA-Z]{3}\\d+', hgvs, flags=re.IGNORECASE)\n if threecharactersearch:\n if any(letters.lower() in hgvs.lower() for letters in conversionlist):\n return replace_all(hgvs)\n return hgvs\n\ndef replace_all(hgvs):\n # Author: Thomas Glaessle\n pattern = re.compile('|'.join(conversionlist), re.IGNORECASE)\n return pattern.sub(lambda m: conversiondict[m.group().capitalize()], hgvs)\n\n\ndef append_annotation_to_file(outf, ncols, rows, annotations):\n if len(rows) != len(annotations):\n log.error('The length of the rows and annotations do not match')\n\n for index, annotation in enumerate(annotations):\n row = rows[index]\n if annotation is not None:\n row = row + annotation\n\n row = padrow(row, ncols)\n rowstr = '\\t'.join(row)\n rowstr = rowstr.encode('ascii', 'ignore').decode('ascii')\n outf.write(rowstr + \"\\n\")\n\n\ndef get_tumor_type_from_row(row, row_index, defaultCancerType, icancertype, cancerTypeMap, sample):\n cancertype = defaultCancerType\n if icancertype >= 0:\n row_cancer_type = get_cell_content(row, icancertype)\n if row_cancer_type is not None:\n cancertype = row_cancer_type\n if sample in cancerTypeMap:\n cancertype = cancerTypeMap[sample]\n if cancertype == \"\":\n log.info(\"Cancer type for the sample should be defined for a more accurate result\\nline %s: %s\\n\" % (row_index, row))\n # continue\n return cancertype\n\ndef has_desired_headers(desired_headers, file_headers):\n has_required_headers = True\n for header in desired_headers:\n if header not in file_headers:\n has_required_headers = False\n break\n\n return has_required_headers\n\n\ndef resolve_query_type(user_input_query_type, headers):\n selected_query_type = None\n if isinstance(user_input_query_type, QueryType):\n selected_query_type = user_input_query_type\n\n if selected_query_type is None and HGVSP_SHORT_HEADER in headers:\n selected_query_type = QueryType.HGVSP_SHORT\n if selected_query_type is None and HGVSP_HEADER in headers:\n selected_query_type = QueryType.HGVSP\n if selected_query_type is None and HGVSG_HEADER in headers:\n selected_query_type = QueryType.HGVSG\n\n if selected_query_type is None and has_desired_headers(REQUIRED_QUERY_TYPE_COLUMNS[QueryType.GENOMIC_CHANGE], headers):\n selected_query_type = QueryType.GENOMIC_CHANGE\n\n # default to HGVSp_Short\n if selected_query_type is None:\n selected_query_type = QueryType.HGVSP_SHORT\n\n # check the file has required columns\n if has_desired_headers(REQUIRED_QUERY_TYPE_COLUMNS[selected_query_type], headers) == False:\n # when it is False, it will never be GENOMIC_CHANGE. For other types, we need to check whether ALTERATION column is available\n if ALTERATION_HEADER not in headers:\n raise Exception(\"The file does not have required columns \"\n + ', '.join(REQUIRED_QUERY_TYPE_COLUMNS[user_input_query_type])\n + \" for the query type: \" + user_input_query_type.value)\n\n return selected_query_type\n\n\ndef get_reference_genome_from_row(row_reference_genome, default_reference_genome):\n reference_genome = default_reference_genome\n if row_reference_genome is not None and row_reference_genome != '':\n try:\n reference_genome = ReferenceGenome[row_reference_genome.upper()]\n except KeyError:\n log.warning('Unexpected reference genome, only GRCh37 and GRCh38 are supported.' + (\n ' Use default.' if default_reference_genome is not None else ' Skipping.'))\n return reference_genome\n\n\ndef processalterationevents(eventfile, outfile, previousoutfile, defaultCancerType, cancerTypeMap,\n annotatehotspots, user_input_query_type, default_reference_genome):\n if annotatehotspots:\n init_3d_hotspots()\n if os.path.isfile(previousoutfile):\n cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)\n outf = open(outfile, 'w+', 1000)\n with open(eventfile, 'rU') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n\n headers = readheaders(reader)\n\n ncols = headers[\"length\"]\n if ncols == 0:\n return\n newncols = 0\n\n outf.write(headers['^-$'])\n\n if annotatehotspots:\n outf.write(\"\\tIS-A-HOTSPOT\")\n outf.write(\"\\tIS-A-3D-HOTSPOT\")\n newncols += 2\n\n outf.write(\"\\t\" + GENE_IN_ONCOKB_HEADER)\n outf.write(\"\\t\" + VARIANT_IN_ONCOKB_HEADER)\n\n outf.write(\"\\tMUTATION_EFFECT\")\n outf.write(\"\\tONCOGENIC\")\n\n newncols += 4\n\n for l in levels:\n outf.write('\\t' + l)\n newncols += len(levels)\n\n outf.write(\"\\tHIGHEST_LEVEL\")\n outf.write(\"\\tCITATIONS\")\n newncols += 2\n\n for l in dxLevels:\n outf.write('\\t' + l)\n newncols += len(dxLevels)\n\n outf.write(\"\\tHIGHEST_DX_LEVEL\")\n newncols += 1\n\n for l in pxLevels:\n outf.write('\\t' + l)\n newncols += len(pxLevels)\n\n outf.write(\"\\tHIGHEST_PX_LEVEL\")\n newncols += 1\n\n outf.write(\"\\n\")\n\n query_type = resolve_query_type(user_input_query_type, headers)\n if (query_type == QueryType.HGVSP_SHORT):\n process_alteration(reader, outf, headers, [HGVSP_SHORT_HEADER, ALTERATION_HEADER], ncols, newncols,\n defaultCancerType,\n cancerTypeMap, annotatehotspots, default_reference_genome)\n\n if (query_type == QueryType.HGVSP):\n process_alteration(reader, outf, headers, [HGVSP_HEADER, ALTERATION_HEADER], ncols, newncols, defaultCancerType,\n cancerTypeMap, annotatehotspots, default_reference_genome)\n\n if (query_type == QueryType.HGVSG):\n process_hvsg(reader, outf, headers, [HGVSG_HEADER, ALTERATION_HEADER], ncols, newncols, defaultCancerType,\n cancerTypeMap, annotatehotspots, default_reference_genome)\n\n if (query_type == QueryType.GENOMIC_CHANGE):\n process_genomic_change(reader, outf, headers, ncols, newncols, defaultCancerType, cancerTypeMap, annotatehotspots, default_reference_genome)\n\n outf.close()\n\n\ndef get_cell_content(row, index, return_empty_string=False):\n if index >= 0 and row[index] != 'NULL' and row[index] != '':\n return row[index]\n elif return_empty_string:\n return ''\n else:\n return None\n\ndef process_alteration(maffilereader, outf, maf_headers, alteration_column_names, ncols, nannotationcols, defaultCancerType, cancerTypeMap,\n annotatehotspots, default_reference_genome):\n ihugo = geIndexOfHeader(maf_headers, HUGO_HEADERS)\n iconsequence = geIndexOfHeader(maf_headers, CONSEQUENCE_HEADERS)\n ihgvs = geIndexOfHeader(maf_headers, alteration_column_names)\n isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)\n istart = geIndexOfHeader(maf_headers, PROTEIN_START_HEADERS)\n iend = geIndexOfHeader(maf_headers, PROTEIN_END_HEADERS)\n iproteinpos = geIndexOfHeader(maf_headers, PROTEIN_POSITION_HEADERS)\n icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)\n ireferencegenome= geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)\n\n posp = re.compile('[0-9]+')\n\n i = 0\n queries = []\n rows = []\n for row in maffilereader:\n i = i + 1\n\n if i % POST_QUERIES_THRESHOLD == 0:\n log.info(i)\n\n row = padrow(row, ncols)\n\n sample = row[isample]\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n hugo = row[ihugo]\n\n consequence = get_cell_content(row, iconsequence)\n if consequence in mutationtypeconsequencemap:\n consequence = '%2B'.join(mutationtypeconsequencemap[consequence])\n\n hgvs = row[ihgvs]\n if hgvs.startswith('p.'):\n hgvs = hgvs[2:]\n\n cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)\n reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome), default_reference_genome)\n\n hgvs = conversion(hgvs)\n\n start = get_cell_content(row, istart)\n\n end = get_cell_content(row, iend)\n\n if start is None and iproteinpos >= 0 and row[iproteinpos] != \"\" and row[iproteinpos] != \".\" and row[iproteinpos] != \"-\":\n poss = row[iproteinpos].split('/')[0].split('-')\n try:\n if len(poss) > 0:\n start = int(poss[0])\n if len(poss) == 2:\n end = int(poss[1])\n except ValueError:\n log.info(\"position wrong at line %s: %s\" % (str(i), row[iproteinpos]))\n\n if start is None and consequence == \"missense_variant\":\n m = posp.search(hgvs)\n if m:\n start = m.group()\n\n if start is not None and end is None:\n end = start\n\n query = ProteinChangeQuery(hugo, hgvs, cancertype, reference_genome, consequence, start, end)\n queries.append(query)\n rows.append(row)\n\n if len(queries) == POST_QUERIES_THRESHOLD:\n annotations = pull_protein_change_info(queries,annotatehotspots)\n append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)\n queries = []\n rows = []\n\n if len(queries) > 0:\n annotations = pull_protein_change_info(queries,annotatehotspots)\n append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)\n\n# this method is from genome-nexus annotation-tools\n# https://github.com/genome-nexus/annotation-tools/blob/53ff7f7fe673e961282f871ebc78d2ecc0831919/standardize_mutation_data.py\ndef get_var_allele(ref_allele, tumor_seq_allele1, tumor_seq_allele2):\n # set the general tumor_seq_allele as the first non-ref allele encountered\n # this will be used to resolve the variant classification and variant type\n # if there are no tumor alleles that do not match the ref allele then use empty string\n # in the event that this happens then there might be something wrong with the data itself\n try:\n tumor_seq_allele = [allele for allele in [tumor_seq_allele1, tumor_seq_allele2] if allele != ref_allele][0]\n except:\n tumor_seq_allele = \"\"\n\n return tumor_seq_allele\n\ndef process_genomic_change(maffilereader, outf, maf_headers, ncols, nannotationcols, defaultCancerType, cancerTypeMap, annotatehotspots, default_reference_genome):\n ichromosome = geIndexOfHeader(maf_headers, [GC_CHROMOSOME_HEADER])\n istart = geIndexOfHeader(maf_headers, [GC_START_POSITION_HEADER])\n iend = geIndexOfHeader(maf_headers, [GC_END_POSITION_HEADER])\n irefallele = geIndexOfHeader(maf_headers, [GC_REF_ALLELE_HEADER])\n ivarallele1 = geIndexOfHeader(maf_headers, [GC_VAR_ALLELE_1_HEADER])\n ivarallele2 = geIndexOfHeader(maf_headers, [GC_VAR_ALLELE_2_HEADER])\n\n isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)\n icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)\n ireferencegenome= geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)\n\n posp = re.compile('[0-9]+')\n\n i = 0\n queries = []\n rows = []\n for row in maffilereader:\n i = i + 1\n\n if i % POST_QUERIES_THRESHOLD == 0:\n log.info(i)\n\n row = padrow(row, ncols)\n\n sample = row[isample]\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)\n reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome), default_reference_genome)\n\n chromosome = get_cell_content(row, ichromosome, True)\n start = get_cell_content(row, istart, True)\n end = get_cell_content(row, iend, True)\n ref_allele = get_cell_content(row, irefallele, True)\n var_allele_1 = get_cell_content(row, ivarallele1, True)\n var_allele_2 = get_cell_content(row, ivarallele2, True)\n var_allele = get_var_allele(ref_allele, var_allele_1, var_allele_2)\n\n query = GenomicChangeQuery(chromosome, start, end, ref_allele, var_allele, cancertype, reference_genome)\n queries.append(query)\n rows.append(row)\n\n if len(queries) == POST_QUERIES_THRESHOLD:\n annotations = pull_genomic_change_info(queries,annotatehotspots)\n append_annotation_to_file(outf, ncols+nannotationcols, rows, annotations)\n queries = []\n rows = []\n\n if len(queries) > 0:\n annotations = pull_genomic_change_info(queries,annotatehotspots)\n append_annotation_to_file(outf, ncols+nannotationcols, rows, annotations)\n\ndef process_hvsg(maffilereader, outf, maf_headers, alteration_column_names, ncols, nannotationcols, defaultCancerType, cancerTypeMap, annotatehotspots, default_reference_genome):\n ihgvsg = geIndexOfHeader(maf_headers, alteration_column_names)\n isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)\n icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)\n ireferencegenome= geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)\n\n i = 0\n queries = []\n rows = []\n for row in maffilereader:\n i = i + 1\n\n if i % POST_QUERIES_THRESHOLD == 0:\n log.info(i)\n\n row = padrow(row, ncols)\n\n sample = row[isample]\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n hgvsg = get_cell_content(row, ihgvsg)\n\n cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)\n reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome), default_reference_genome)\n\n if hgvsg is None:\n if annotatehotspots:\n default_cols = [['', '', GENE_IN_ONCOKB_DEFAULT, VARIANT_IN_ONCOKB_DEFAULT]]\n else:\n default_cols = [[GENE_IN_ONCOKB_DEFAULT, VARIANT_IN_ONCOKB_DEFAULT]]\n append_annotation_to_file(outf, ncols + nannotationcols, [row],\n default_cols)\n else:\n query = HGVSgQuery(hgvsg, cancertype, reference_genome)\n queries.append(query)\n rows.append(row)\n\n if len(queries) == POST_QUERIES_THRESHOLD:\n annotations = pull_hgvsg_info(queries, annotatehotspots)\n append_annotation_to_file(outf, ncols+nannotationcols, rows, annotations)\n queries = []\n rows = []\n\n if len(queries) > 0:\n annotations = pull_hgvsg_info(queries,annotatehotspots)\n append_annotation_to_file(outf, ncols+nannotationcols, rows, annotations)\n\n\ndef getgenesfromfusion(fusion, nameregex=None):\n GENES_REGEX = \"([A-Za-z\\d]+-[A-Za-z\\d]+)\" if nameregex is None else nameregex\n searchresult = re.search(GENES_REGEX, fusion, flags=re.IGNORECASE)\n gene1=None\n gene2=None\n if searchresult:\n parts = searchresult.group(1).split(\"-\")\n gene1 = parts[0]\n gene2 = gene1\n if len(parts) > 1 and parts[1] != \"intragenic\":\n gene2 = parts[1]\n else:\n gene1=gene2=fusion\n return gene1, gene2\n\ndef processsv(svdata, outfile, previousoutfile, defaultCancerType, cancerTypeMap, nameregex):\n if os.path.isfile(previousoutfile):\n cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)\n outf = open(outfile, 'w+')\n with open(svdata, 'rU') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n\n headers = readheaders(reader)\n\n ncols = headers[\"length\"]\n\n if ncols == 0:\n return\n\n outf.write(headers['^-$'])\n outf.write(\"\\t\" + GENE_IN_ONCOKB_HEADER)\n outf.write(\"\\t\" + VARIANT_IN_ONCOKB_HEADER)\n outf.write(\"\\tMUTATION_EFFECT\")\n outf.write(\"\\tONCOGENIC\")\n for l in levels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_LEVEL\")\n outf.write(\"\\tCITATIONS\")\n\n for l in dxLevels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_DX_LEVEL\")\n\n for l in pxLevels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_PX_LEVEL\\n\")\n\n newcols = ncols + 8 + len(levels) + len(dxLevels) + len(pxLevels)\n\n igene1 = geIndexOfHeader(headers, ['GENE1'])\n igene2 = geIndexOfHeader(headers, ['GENE2'])\n ifusion = geIndexOfHeader(headers, FUSION_HEADERS)\n isample = geIndexOfHeader(headers, SAMPLE_HEADERS)\n icancertype = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)\n\n i = 0\n queries = []\n rows = []\n for row in reader:\n i = i + 1\n if i % POST_QUERIES_THRESHOLD == 0:\n log.info(i)\n\n row = padrow(row, ncols)\n\n sample = row[isample]\n\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n gene1 = None\n gene2 = None\n if igene1 >= 0:\n gene1 = row[igene1]\n if igene2 >= 0:\n gene2 = row[igene2]\n if igene1 < 0 and igene2 < 0 and ifusion >= 0:\n fusion = row[ifusion]\n gene1, gene2 = getgenesfromfusion(fusion, nameregex)\n\n cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)\n\n\n queries.append(StructuralVariantQuery(gene1, gene2, 'FUSION', cancertype))\n rows.append(row)\n\n if len(queries) == POST_QUERIES_THRESHOLD:\n annotations = pull_structural_variant_info(queries)\n append_annotation_to_file(outf, newcols, rows, annotations)\n queries = []\n rows = []\n\n if len(queries) > 0:\n annotations = pull_structural_variant_info(queries)\n append_annotation_to_file(outf, newcols, rows, annotations)\n outf.close()\n\n\ndef processcnagisticdata(cnafile, outfile, previousoutfile, defaultCancerType, cancerTypeMap, annotate_gain_loss=False):\n CNA_AMPLIFICATION_TXT = 'Amplification'\n CNA_DELETION_TXT = 'Deletion'\n CNA_LOSS_TXT = 'Loss'\n CNA_GAIN_TXT = 'Gain'\n\n cnaEventMap = {\n \"-2\": CNA_DELETION_TXT,\n \"-1.5\": CNA_DELETION_TXT,\n \"2\": CNA_AMPLIFICATION_TXT\n }\n\n if annotate_gain_loss:\n cnaEventMap.update({\n \"-1\": CNA_LOSS_TXT,\n \"1\": CNA_GAIN_TXT\n })\n\n if os.path.isfile(previousoutfile):\n cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)\n outf = open(outfile, 'w+', 1000)\n with open(cnafile, 'rU') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n headers = readheaders(reader)\n samples = []\n rawsamples = []\n if headers[\"length\"] != 0:\n startofsamples = getfirstcolumnofsampleingisticdata(headers['^-$'].split('\\t'))\n rawsamples = headers['^-$'].split('\\t')[startofsamples:]\n for rs in rawsamples:\n samples.append(rs)\n\n if defaultCancerType == '' and not set(cancerTypeMap.keys()).issuperset(set(samples)):\n log.info(\n \"Cancer type for all samples should be defined for a more accurate result\\nsamples in cna file: %s\\n\" % (\n samples))\n\n outf.write('SAMPLE_ID\\tCANCER_TYPE\\tHUGO_SYMBOL\\tALTERATION')\n outf.write(\"\\t\"+GENE_IN_ONCOKB_HEADER)\n outf.write(\"\\t\"+VARIANT_IN_ONCOKB_HEADER)\n outf.write(\"\\tMUTATION_EFFECT\")\n outf.write(\"\\tONCOGENIC\")\n for l in levels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_LEVEL\")\n outf.write(\"\\tCITATIONS\")\n\n for l in dxLevels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_DX_LEVEL\")\n\n for l in pxLevels:\n outf.write('\\t' + l)\n outf.write(\"\\tHIGHEST_PX_LEVEL\\n\")\n\n ncols = 12 + len(levels) + len(dxLevels) + len(pxLevels)\n\n i = 0\n rows = []\n queries = []\n for row in reader:\n i = i + 1\n if i % POST_QUERIES_THRESHOLD == 0:\n log.info(i)\n\n hugo = row[0]\n if len(row) == 1:\n log.warning(\"No CNA specified for gene \" + hugo)\n continue\n\n for rawsample in rawsamples:\n if rawsample in headers:\n if len(row) <= headers[rawsample]:\n log.warning('No CNA specified for ' + row[0] + ' ' + rawsample)\n continue\n cna = row[headers[rawsample]]\n if cna in cnaEventMap:\n cna_type = cnaEventMap[cna]\n if cna_type is not None:\n cancertype = defaultCancerType\n sample = rawsample\n\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n if sample in cancerTypeMap:\n cancertype = cancerTypeMap[sample]\n\n rows.append([sample, cancertype, hugo, cna_type])\n queries.append(CNAQuery(hugo, cna_type, cancertype))\n\n if len(queries) == POST_QUERIES_THRESHOLD:\n annotations = pull_cna_info(queries)\n append_annotation_to_file(outf, ncols, rows, annotations)\n rows = []\n queries = []\n\n if len(queries) > 0:\n annotations = pull_cna_info(queries)\n append_annotation_to_file(outf, ncols, rows, annotations)\n\n outf.close()\n\ndef getfirstcolumnofsampleingisticdata(headers):\n header0 = headers[0].lower()\n if header0 != \"hugo_symbol\" and header0 != \"gene symbol\":\n log.info(\"Gistic data should start with Hugo_Symbol\")\n quit()\n\n header1 = headers[1].lower()\n if header1 != \"entrez_gene_id\" and header1 != \"locus id\":\n return 1\n\n header2 = headers[2].lower()\n if header2 != \"cytoband\":\n return 2\n\n return 3\n\n\ndef file_len(fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\n\ndef processclinicaldata(annotatedmutfiles, clinicalfile, outfile):\n samplelevels = {}\n sampledxlevels = {}\n samplepxlevels = {}\n sampleleveltreatments = {}\n sampledrivers = {}\n samplemutationswithdiagnosis = {}\n samplemutationswithprognosis = {}\n sampleactionablecount = {}\n samplealterationcount = {}\n for annotatedmutfile in annotatedmutfiles:\n with open(annotatedmutfile, 'rU') as mutfile:\n reader = csv.reader(mutfile, delimiter='\\t')\n headers = readheaders(reader)\n\n ncols = headers[\"length\"]\n\n if ncols == 0:\n return\n\n igene1 = geIndexOfHeader(headers, ['GENE1'] + HUGO_HEADERS) # fusion\n igene2 = geIndexOfHeader(headers, ['GENE2'] + HUGO_HEADERS) # fusion\n ifusion = geIndexOfHeader(headers, ['FUSION'])\n\n ihugo = geIndexOfHeader(headers, HUGO_HEADERS)\n iconsequence = geIndexOfHeader(headers, CONSEQUENCE_HEADERS)\n ihgvs = geIndexOfHeader(headers, HGVS_HEADERS)\n isample = geIndexOfHeader(headers, SAMPLE_HEADERS)\n istart = geIndexOfHeader(headers, PROTEIN_START_HEADERS)\n iend = geIndexOfHeader(headers, PROTEIN_END_HEADERS)\n icancertype = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)\n # imutationeffect = headers['MUTATION_EFFECT']\n ioncogenic = headers['ONCOGENIC']\n\n isfusion = (igene1 != -1 & igene2 != -1) or ifusion != -1\n ismutorcna = ihugo != -1 & ihgvs != -1\n\n if not isfusion and not ismutorcna:\n log.error(\"missing proper header\")\n exit()\n\n for row in reader:\n\n row = padrow(row, ncols)\n\n sample = row[isample]\n\n oncogenic = \"\"\n if ioncogenic < len(row):\n oncogenic = row[ioncogenic].lower()\n if sample not in samplelevels:\n samplelevels[sample] = {}\n sampledxlevels[sample] = []\n samplepxlevels[sample] = []\n sampleleveltreatments[sample] = {}\n sampledrivers[sample] = []\n sampleactionablecount[sample] = {}\n\n if sample not in samplemutationswithdiagnosis:\n samplemutationswithdiagnosis[sample] = []\n\n if sample not in samplemutationswithprognosis:\n samplemutationswithprognosis[sample] = []\n\n if sample not in samplealterationcount:\n samplealterationcount[sample] = 1\n else:\n samplealterationcount[sample] += 1\n\n hugo = row[ihugo]\n alteration = row[ihgvs]\n gene1 = row[igene1]\n gene2 = row[igene2]\n\n variant = \"NA\"\n if ismutorcna:\n variant = hugo + \" \" + alteration\n elif isfusion:\n if ifusion != -1:\n variant = row[ifusion]\n else:\n if gene1 == gene2:\n variant = gene1 + \" intragenic deletion\"\n else:\n variant = gene1 + \"-\" + gene2 + \" fusion\"\n\n if oncogenic == \"oncogenic\" or oncogenic == \"likely oncogenic\" or oncogenic == \"predicted oncogenic\":\n sampledrivers[sample].append(variant)\n\n for l in levels:\n il = headers[l]\n if il < len(row) and row[il] != '':\n if l not in samplelevels[sample]:\n samplelevels[sample][l] = []\n sampleleveltreatments[sample][l] = []\n samplelevels[sample][l].append(row[il] + \"(\" + variant + \")\")\n sampleleveltreatments[sample][l].extend(row[il].split(\",\"))\n\n if not l.startswith('LEVEL_R'):\n sampleactionablecount[sample][variant] = True\n\n for l in dxLevels:\n il = headers[l]\n if il < len(row) and row[il] != '':\n if l not in samplelevels[sample]:\n samplelevels[sample][l] = []\n samplelevels[sample][l].append(row[il] + \"(\" + variant + \")\")\n\n for l in pxLevels:\n il = headers[l]\n if il < len(row) and row[il] != '':\n if l not in samplelevels[sample]:\n samplelevels[sample][l] = []\n samplelevels[sample][l].append(row[il] + \"(\" + variant + \")\")\n\n ihighestdxlevel = geIndexOfHeader(headers, ['HIGHEST_DX_LEVEL'])\n if ihighestdxlevel != -1:\n if row[ihighestdxlevel] != '':\n samplemutationswithdiagnosis[sample].append(variant)\n sampledxlevels[sample].append(row[ihighestdxlevel])\n\n ihighestpxlevel = geIndexOfHeader(headers, ['HIGHEST_PX_LEVEL'])\n if ihighestpxlevel != -1:\n if row[ihighestpxlevel] != '':\n samplemutationswithprognosis[sample].append(variant)\n samplepxlevels[sample].append(row[ihighestpxlevel])\n\n outf = open(outfile, 'w+')\n\n # export to anntoated file\n with open(clinicalfile, 'rU') as clinfile:\n reader = csv.reader(clinfile, delimiter='\\t')\n headers = readheaders(reader)\n outf.write(headers['^-$'])\n for l in levels:\n outf.write('\\t' + l)\n outf.write('\\tHIGHEST_LEVEL')\n for l in dxLevels:\n outf.write('\\t' + l)\n outf.write('\\tHIGHEST_DX_LEVEL')\n for l in pxLevels:\n outf.write('\\t' + l)\n outf.write('\\tHIGHEST_PX_LEVEL')\n outf.write('\\tONCOGENIC_MUTATIONS\\t#ONCOGENIC_MUTATIONS\\t#MUTATIONS_WITH_THERAPEUTIC_IMPLICATIONS\\t#MUTATIONS_WITH_DIAGNOSTIC_IMPLICATIONS\\t#MUTATIONS_WITH_PROGNOSTIC_IMPLICATIONS\\t#MUTATIONS\\n')\n isample = headers['SAMPLE_ID']\n\n for row in reader:\n sample = row[isample]\n\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n outf.write('\\t'.join(row))\n\n for l in levels:\n outf.write('\\t')\n if sample in samplelevels and l in samplelevels[sample]:\n outf.write(\";\".join(samplelevels[sample][l]))\n\n highestlevel = ''\n highestdxlevel = ''\n highestpxlevel = ''\n if sample in sampleleveltreatments:\n highestlevel = gethighestsensitivitylevel(sampleleveltreatments[sample])\n if sample in sampledxlevels:\n highestdxlevel = gethighestDxPxlevel(dxLevels, sampledxlevels[sample])\n if sample in samplepxlevels:\n highestpxlevel = gethighestDxPxlevel(pxLevels, samplepxlevels[sample])\n # if highestlevel == '':\n # if sample in sampledrivers and len(sampledrivers[sample])>0:\n # highestlevel = 'Oncogenic, no level'\n # else:\n # highestlevel = \"VUS\"\n outf.write('\\t' + highestlevel)\n\n for l in dxLevels:\n outf.write('\\t')\n if sample in samplelevels and l in samplelevels[sample]:\n outf.write(\";\".join(samplelevels[sample][l]))\n\n outf.write('\\t' + highestdxlevel)\n\n for l in pxLevels:\n outf.write('\\t')\n if sample in samplelevels and l in samplelevels[sample]:\n outf.write(\";\".join(samplelevels[sample][l]))\n outf.write('\\t' + highestpxlevel)\n\n\n actionablecount = 0\n if sample in sampleactionablecount:\n actionablecount = len(sampleactionablecount[sample].keys())\n\n alterationcount = 0\n if sample in samplealterationcount:\n alterationcount = samplealterationcount[sample]\n\n drivercount = 0\n diagnosiscount = 0\n prognosiscount = 0\n drivermutations = \"\"\n if sample in sampledrivers:\n drivercount = len(sampledrivers[sample])\n drivermutations = \";\".join(sampledrivers[sample])\n if sample in samplemutationswithdiagnosis:\n diagnosiscount = len(samplemutationswithdiagnosis[sample])\n if sample in samplemutationswithprognosis:\n prognosiscount = len(samplemutationswithprognosis[sample])\n\n outf.write('\\t' + drivermutations)\n outf.write('\\t' + str(drivercount))\n outf.write('\\t' + str(actionablecount))\n outf.write('\\t' + str(diagnosiscount))\n outf.write('\\t' + str(prognosiscount))\n outf.write('\\t' + str(alterationcount))\n\n outf.write('\\n')\n\n outf.close()\n\ndef plotclinicalactionability(ax, annotatedclinicalfile, outfile, parameters):\n if os.path.isfile(outfile):\n os.remove(outfile)\n\n extlevels = levels + [\"ONCOGENIC\", \"VUS\"]\n if \"levels\" in parameters:\n extlevels = parameters[\"levels\"]\n\n with open(annotatedclinicalfile, 'rU') as clinfile:\n reader = csv.reader(clinfile, delimiter='\\t')\n headers = readheaders(reader)\n isample = geIndexOfHeader(headers, SAMPLE_HEADERS)\n ilevel = headers['HIGHEST_LEVEL']\n ioncogenic = headers['ONCOGENIC_MUTATIONS']\n icat = headers[parameters[\"catogerycolumn\"].upper()] #e.g. \"CANCER_TYPE\"\n\n catsamplecount = {}\n catactionablesamplecount = {}\n oncogenicsamplecount = {}\n levelcatsamplecount = {}\n\n for row in reader:\n sample = row[isample]\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n cat = row[icat]\n if cat not in catsamplecount:\n catsamplecount[cat] = 0\n catsamplecount[cat] += 1\n\n if cat not in catactionablesamplecount:\n catactionablesamplecount[cat] = 0\n oncogenicsamplecount[cat] = 0\n\n level = row[ilevel]\n oncogenic = row[ioncogenic]\n\n exlevel = level\n\n if level in extlevels:\n catactionablesamplecount[cat] += 1\n oncogenicsamplecount[cat] += 1\n elif len(oncogenic.strip()) > 0:\n oncogenicsamplecount[cat] += 1\n exlevel = \"ONCOGENIC\"\n else:\n exlevel = \"VUS\"\n\n if exlevel not in levelcatsamplecount:\n levelcatsamplecount[exlevel] = {}\n if cat not in levelcatsamplecount[exlevel]:\n levelcatsamplecount[exlevel][cat] = 0\n levelcatsamplecount[exlevel][cat] += 1\n\n\n # plot\n catarray = [] # cancer types\n catactionabilityarray = [] # actionabiligy percentages per cancer type\n catoncogenicarray = [] # actionabiligy percentages per cancer type\n for cat in catsamplecount:\n if catsamplecount[cat] >= parameters[\"thresholdcat\"]:\n catarray.append(cat)\n catactionabilityarray.append(catactionablesamplecount[cat] * 100.0 / catsamplecount[cat])\n catoncogenicarray.append(oncogenicsamplecount[cat] * 100.0 / catsamplecount[cat])\n\n ncat = len(catarray)\n order = reversed(sorted(range(ncat),key=lambda x:(catactionabilityarray[x],catoncogenicarray[x])))\n drawplot(ax, 'OncoKB Actionability', extlevels, levelcatsamplecount, catarray, catsamplecount, order, parameters[\"thresholdcat\"])\n\ndef plotimplications(ax, header, title, levels, annotatedclinicalfile, outfile, parameters):\n if os.path.isfile(outfile):\n os.remove(outfile)\n\n extlevels = levels\n if \"levels\" in parameters:\n extlevels = parameters[\"levels\"]\n\n with open(annotatedclinicalfile, 'rU') as clinfile:\n reader = csv.reader(clinfile, delimiter='\\t')\n headers = readheaders(reader)\n isample = headers['SAMPLE_ID']\n ilevel = headers[header]\n icat = headers[parameters[\"catogerycolumn\"].upper()]\n\n catsamplecount = {}\n catactionablesamplecount = {}\n levelcatsamplecount = {}\n\n for row in reader:\n sample = row[isample]\n if sampleidsfilter and sample not in sampleidsfilter:\n continue\n\n cat = row[icat]\n if cat not in catsamplecount:\n catsamplecount[cat] = 0\n catsamplecount[cat] += 1\n\n if cat not in catactionablesamplecount:\n catactionablesamplecount[cat] = 0\n\n level = row[ilevel]\n\n exlevel = level\n\n if level in extlevels:\n catactionablesamplecount[cat] += 1\n else:\n exlevel = \"Other\"\n\n if exlevel not in levelcatsamplecount:\n levelcatsamplecount[exlevel] = {}\n if cat not in levelcatsamplecount[exlevel]:\n levelcatsamplecount[exlevel][cat] = 0\n levelcatsamplecount[exlevel][cat] += 1\n\n\n # plot\n catarray = [] # cancer types\n catactionabilityarray = [] # actionabiligy percentages per cancer type\n for cat in catsamplecount:\n if catsamplecount[cat] >= parameters[\"thresholdcat\"]:\n catarray.append(cat)\n catactionabilityarray.append(catactionablesamplecount[cat] * 100.0 / catsamplecount[cat])\n\n ncat = len(catarray)\n order = reversed(sorted(range(ncat),key=lambda x:(catactionabilityarray[x])))\n drawplot(ax, title, extlevels, levelcatsamplecount, catarray, catsamplecount, order, parameters[\"thresholdcat\"])\n\ndef drawplot(ax, title, extlevels, levelcatsamplecount, catarray, catsamplecount, order, thresholdcat):\n\n # level colors\n levelcolors = {\n 'LEVEL_1': '#33A02C',\n 'LEVEL_2': '#1F78B4',\n 'LEVEL_3A': '#984EA3',\n 'LEVEL_3B': '#BE98CE',\n 'LEVEL_4': '#a8a8a8',\n 'LEVEL_R1': '#EE3424',\n 'LEVEL_R2': '#F79A92',\n 'LEVEL_R3': '#FCD6D3',\n\n 'LEVEL_Dx1': '#33A02C',\n 'LEVEL_Dx2': '#1F78B4',\n 'LEVEL_Dx3': '#984EA3',\n\n 'LEVEL_Px1': '#33A02C',\n 'LEVEL_Px2': '#1F78B4',\n 'LEVEL_Px3': '#984EA3',\n\n 'ONCOGENIC': '#ffdab9',\n 'VUS': '#d1d1d1',\n 'Other': 'grey'\n }\n\n # level legend\n levellegend = {\n 'LEVEL_1': 'Level 1',\n 'LEVEL_2': 'Level 2',\n 'LEVEL_3A': 'Level 3A',\n 'LEVEL_3B': 'Level 3B',\n 'LEVEL_4': 'Level 4',\n 'LEVEL_R1': 'Level R1',\n 'LEVEL_R2': 'Level R2',\n 'LEVEL_R3': 'Level R3',\n\n 'LEVEL_Dx1': 'Level Dx1',\n 'LEVEL_Dx2': 'Level Dx2',\n 'LEVEL_Dx3': 'Level Dx3',\n\n 'LEVEL_Px1': 'Level Px1',\n 'LEVEL_Px2': 'Level Px2',\n 'LEVEL_Px3': 'Level Px3',\n\n 'ONCOGENIC': 'Oncogenic, no level',\n 'VUS': 'VUS',\n 'Other': 'Other'\n }\n\n ncat = len(catarray)\n if ncat > 0:\n catarray = [catarray[i] for i in order]\n\n ind = range(ncat)\n\n legends = []\n plts = []\n accumlevelcancerperc = [0] * ncat\n for level in extlevels:\n if level not in levelcatsamplecount:\n continue\n\n levelcancerperc = [0] * ncat\n for k in ind:\n cat = catarray[k]\n if catsamplecount[cat] < thresholdcat:\n continue\n if cat in levelcatsamplecount[level]:\n levelcancerperc[k] = levelcatsamplecount[level][cat] * 100.0 / catsamplecount[cat]\n\n width = 0.75\n plts = [ax.bar(ind, levelcancerperc, width, color=levelcolors[level], bottom=accumlevelcancerperc)] + plts\n legends = [levellegend[level]] + legends\n accumlevelcancerperc = list(map(sum, zip(accumlevelcancerperc,levelcancerperc)))\n\n ax = plt.gca()\n ax.set_axisbelow(True)\n ax.set_aspect(0.1)\n\n ax.tick_params(axis='y', which='major', labelsize=6)\n ax.set_ylabel('% of samples', fontsize=6)\n ax.set_title(title, fontsize=8)\n ax.set_xticks([i+0.5 for i in ind])\n ax.set_xticklabels(catarray, rotation=60, ha=\"right\", fontsize=4)\n # plt.yticks(np.arange(0, 81, 10))\n ax.legend(plts, legends, fontsize=6, bbox_to_anchor=(1.01, 1), loc=\"upper left\")\n\n\noncokbcache = {}\n\n\ndef cacheannotated(annotatedfile, defaultCancerType, cancerTypeMap):\n with open(annotatedfile, 'rU') as infile:\n try:\n reader = csv.reader(infile, delimiter='\\t')\n headers = readheaders(reader)\n\n ihugo = geIndexOfHeader(headers, HUGO_HEADERS)\n iconsequence = geIndexOfHeader(headers, CONSEQUENCE_HEADERS)\n ihgvs = geIndexOfHeader(headers, HGVS_HEADERS)\n isample = geIndexOfHeader(headers, SAMPLE_HEADERS)\n istart = geIndexOfHeader(headers, PROTEIN_START_HEADERS)\n iend = geIndexOfHeader(headers, PROTEIN_END_HEADERS)\n icancertype = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)\n imutationeffect = headers['MUTATION_EFFECT']\n icitations = headers['CITATIONS']\n ioncogenic = headers['ONCOGENIC']\n igeneannotated = headers[GENE_IN_ONCOKB_HEADER]\n ivariantannotated = headers[VARIANT_IN_ONCOKB_HEADER]\n\n for row in reader:\n try:\n hugo = row[ihugo]\n\n hgvs = row[ihgvs]\n if hgvs.startswith('p.'):\n hgvs = hgvs[2:]\n\n sample = row[isample]\n cancertype = defaultCancerType\n if icancertype >= 0:\n cancertype = row[icancertype]\n if sample in cancerTypeMap:\n cancertype = cancerTypeMap[sample]\n key = '-'.join([hugo, hgvs, cancertype])\n # oncokb = row[ioncokb]\n\n oncokbcache[key] = {}\n oncokbcache[key][GENE_IN_ONCOKB_HEADER] = row[igeneannotated]\n oncokbcache[key][VARIANT_IN_ONCOKB_HEADER] = row[ivariantannotated]\n oncokbcache[key]['mutation_effect'] = row[imutationeffect]\n oncokbcache[key]['citations'] = row[icitations]\n oncokbcache[key]['oncogenic'] = row[ioncogenic]\n for l in levels:\n il = headers[l]\n if il < len(row):\n oncokbcache[key][l] = row[il].split(',')\n else:\n oncokbcache[key][l] = []\n except Exception:\n pass\n except Exception:\n pass\n\ndef geIndexOfHeader(headers, keywords):\n for k in keywords:\n if k in headers:\n return headers[k]\n return -1\n\n\ndef pull3dhotspots(hugo, consequence, start, end):\n try:\n if hugo in _3dhotspots and consequence == \"missense_variant\":\n for i in range(int(start), int(end) + 1):\n if i in _3dhotspots[hugo]:\n return \"Y\"\n except TypeError:\n log.error(\"%s: %s-%s\" % (hugo, str(start), str(end)))\n return \"\"\n\ndef appendoncokbcitations(citations, pmids, abstracts):\n if citations is None:\n citations = []\n\n if pmids is not None:\n for pmid in pmids:\n if pmid not in citations:\n citations.append(pmid)\n\n if abstracts is not None:\n for abstract in abstracts:\n abstractStr = abstract['abstract'] + '(' + abstract['link'] + ')'\n if abstractStr not in citations:\n citations.append(abstractStr)\n\n return citations\n\n\nclass Gene:\n def __init__(self, hugo):\n self.hugoSymbol = hugo\n\n\nclass ProteinChangeQuery:\n def __init__(self, hugo, hgvs, cancertype, reference_genome=None, consequence=None, start=None, end=None):\n self.gene = Gene(hugo)\n self.alteration = hgvs\n if consequence is not None:\n self.consequence = consequence\n if start is not None:\n self.proteinStart = start\n if end is not None:\n self.proteinEnd = end\n self.tumorType = cancertype\n if reference_genome is not None:\n self.referenceGenome = reference_genome.value\n\n\nclass HGVSgQuery:\n def __init__(self, hgvsg, cancertype, reference_genome=None):\n self.hgvsg = hgvsg\n self.tumorType = cancertype\n if reference_genome is not None:\n self.referenceGenome = reference_genome.value\n\n\ndef gettumortypename(tumortype):\n if 'code' in tumortype and tumortype['code'] is not None and tumortype['code'] != '':\n return tumortype['code']\n elif 'name' in tumortype and tumortype['name'] is not None and tumortype['name'] != '':\n return tumortype['name']\n else:\n return tumortype['mainType']['name']\n\n\ndef getimplications(oncokbdata, levels, implications):\n for implication in implications:\n level = implication['levelOfEvidence']\n\n if level is not None:\n if level not in levels:\n log.info(level + \" is ignored\")\n else:\n if 'tumorType' in implication:\n oncokbdata[level].append(gettumortypename(implication['tumorType']))\n\n\nclass GenomicChangeQuery:\n def __init__(self, chromosome, start, end, ref_allele, var_allele, cancertype, reference_genome=None):\n self.genomicLocation = ','.join([chromosome, start, end, ref_allele, var_allele])\n self.tumorType = cancertype\n if reference_genome is not None:\n self.referenceGenome = reference_genome.value\n\nclass CNAQuery:\n def __init__(self, hugo, cnatype, cancertype):\n self.gene = Gene(hugo)\n self.copyNameAlterationType = cnatype.upper()\n self.tumorType = cancertype\n\nclass StructuralVariantQuery:\n def __init__(self, hugoA, hugoB, structural_variant_type, cancertype):\n\n # Assume all structural variants in the file are functional fusions\n is_functional_fusion = True\n if hugoA == hugoB:\n is_functional_fusion = False\n structural_variant_type = 'DELETION'\n\n self.geneA = Gene(hugoA)\n self.geneB = Gene(hugoB)\n self.functionalFusion = is_functional_fusion\n self.structuralVariantType = structural_variant_type.upper()\n self.tumorType = cancertype\n\n\ndef pull_protein_change_info(queries, annotate_hotspot):\n url = oncokbapiurl + '/annotate/mutations/byProteinChange'\n response = makeoncokbpostrequest(url, queries)\n annotation = []\n if response.status_code == 200:\n annotation = response.json()\n else:\n for query in queries:\n geturl = url + '?'\n geturl += 'hugoSymbol=' + query.gene.hugoSymbol\n geturl += '&alteration=' + query.alteration\n geturl += '&tumorType=' + query.tumorType\n if query.consequence:\n geturl += '&consequence=' + query.consequence\n if query.proteinStart and query.proteinStart != '\\\\N' and query.proteinStart != 'NULL' and query.proteinStart != '':\n geturl += '&proteinStart=' + str(query.proteinStart)\n if query.proteinEnd and query.proteinEnd != '\\\\N' and query.proteinEnd != 'NULL' and query.proteinEnd != '':\n geturl += '&proteinEnd=' + str(query.proteinEnd)\n getresponse = makeoncokbgetrequest(geturl)\n if getresponse.status_code == 200:\n annotation.append(getresponse.json())\n else:\n # if the api call fails, we should still push a None into the list\n # to keep the same length of the queries\n annotation.append(None)\n\n processed_annotation = []\n for query_annotation in annotation:\n processed_annotation.append(process_oncokb_annotation(query_annotation, annotate_hotspot))\n return processed_annotation\n\n\ndef pull_hgvsg_info(queries, annotate_hotspot):\n url = oncokbapiurl + '/annotate/mutations/byHGVSg'\n response = makeoncokbpostrequest(url, queries)\n annotation = []\n if response.status_code == 200:\n annotation = response.json()\n else:\n for query in queries:\n geturl = url + '?'\n geturl += 'hgvsg=' + query.hgvsg\n geturl += '&tumorType=' + query.tumorType\n getresponse = makeoncokbgetrequest(geturl)\n if getresponse.status_code == 200:\n annotation.append(getresponse.json())\n else:\n # if the api call fails, we should still push a None into the list\n # to keep the same length of the queries\n annotation.append(None)\n\n processed_annotation = []\n for query_annotation in annotation:\n processed_annotation.append(process_oncokb_annotation(query_annotation, annotate_hotspot))\n return processed_annotation\n\ndef pull_genomic_change_info(queries, annotate_hotspot):\n url = oncokbapiurl + '/annotate/mutations/byGenomicChange'\n response = makeoncokbpostrequest(url, queries)\n annotation = []\n if response.status_code == 200:\n annotation = response.json()\n else:\n for query in queries:\n geturl = url + '?'\n geturl += 'genomicLocation=' + query.genomicLocation\n geturl += '&tumorType=' + query.tumorType\n getresponse = makeoncokbgetrequest(geturl)\n if getresponse.status_code == 200:\n annotation.append(getresponse.json())\n else:\n # if the api call fails, we should still push a None into the list\n # to keep the same length of the queries\n annotation.append(None)\n\n processed_annotation = []\n for query_annotation in annotation:\n processed_annotation.append(process_oncokb_annotation(query_annotation, annotate_hotspot))\n return processed_annotation\n\n\ndef pull_cna_info(queries):\n url = oncokbapiurl + '/annotate/copyNumberAlterations?'\n\n response = makeoncokbpostrequest(url, queries)\n annotation = []\n if response.status_code == 200:\n annotation = response.json()\n else:\n for query in queries:\n geturl = url + '?'\n geturl += 'hugoSymbol=' + query.gene.hugoSymbol\n geturl += '&copyNameAlterationType=' + query.copyNameAlterationType\n geturl += '&tumorType=' + query.tumorType\n getresponse = makeoncokbgetrequest(geturl)\n if getresponse.status_code == 200:\n annotation.append(getresponse.json())\n else:\n # if the api call fails, we should still push a None into the list\n # to keep the same length of the queries\n annotation.append(None)\n\n processed_annotation = []\n for query_annotation in annotation:\n processed_annotation.append(process_oncokb_annotation(query_annotation, annotate_hotspot=False))\n return processed_annotation\n\n\n\ndef pull_structural_variant_info(queries):\n url = oncokbapiurl + '/annotate/structuralVariants'\n\n response = makeoncokbpostrequest(url, queries)\n annotation = []\n if response.status_code == 200:\n annotation = response.json()\n else:\n for query in queries:\n geturl = url + '?'\n geturl += 'hugoSymbolA=' + query.geneA.hugoSymbol\n geturl += '&hugoSymbolB=' + query.geneB.hugoSymbol\n geturl += '&structuralVariantType=' + query.structuralVariantType\n geturl += '&isFunctionalFusion=' + str(query.functionalFusion).upper() if type(query.functionalFusion) is bool else query.functionalFusion\n geturl += '&tumorType=' + query.tumorType\n\n getresponse = makeoncokbgetrequest(geturl)\n if getresponse.status_code == 200:\n annotation.append(getresponse.json())\n else:\n # if the api call fails, we should still push a None into the list\n # to keep the same length of the queries\n annotation.append(None)\n\n processed_annotation = []\n for query_annotation in annotation:\n processed_annotation.append(process_oncokb_annotation(query_annotation, annotate_hotspot=False))\n return processed_annotation\n\n\n\ndef process_oncokb_annotation(annotation, annotate_hotspot):\n if annotation is None:\n return None\n\n oncokbdata = {}\n for l in levels:\n oncokbdata[l] = []\n for l in dxLevels:\n oncokbdata[l] = []\n for l in pxLevels:\n oncokbdata[l] = []\n\n oncokbdata[GENE_IN_ONCOKB_HEADER] = GENE_IN_ONCOKB_DEFAULT\n oncokbdata[VARIANT_IN_ONCOKB_HEADER] = VARIANT_IN_ONCOKB_DEFAULT\n oncokbdata['mutation_effect'] = \"\"\n oncokbdata['citations'] = []\n oncokbdata['oncogenic'] = \"\"\n\n try:\n # oncogenic\n oncokbdata[GENE_IN_ONCOKB_HEADER] = GENE_IN_ONCOKB_DEFAULT if annotation['geneExist'] is None else str(annotation['geneExist'])\n oncokbdata[VARIANT_IN_ONCOKB_HEADER] = VARIANT_IN_ONCOKB_DEFAULT if annotation['variantExist'] is None else str(annotation['variantExist'])\n\n # oncogenic\n oncokbdata['oncogenic'] = annotation['oncogenic']\n\n # if not evidences['geneExist'] or (not evidences['variantExist'] and not evidences['alleleExist']):\n # return ''\n\n # mutation effect\n if (annotation['mutationEffect'] is not None):\n oncokbdata['mutation_effect'] = annotation['mutationEffect']['knownEffect']\n oncokbdata['citations'] = appendoncokbcitations(oncokbdata['citations'],\n annotation['mutationEffect']['citations']['pmids'],\n annotation['mutationEffect']['citations']['abstracts'])\n\n # oncogenic\n oncokbdata['oncogenic'] = annotation['oncogenic']\n\n # get treatment\n for treatment in annotation['treatments']:\n level = treatment['level']\n\n if level not in levels:\n log.info(\"%s is ignored\" % level)\n # oncokbdata[level].append('')\n else:\n drugs = treatment['drugs']\n\n oncokbdata['citations'] = appendoncokbcitations(oncokbdata['citations'], treatment['pmids'],\n treatment['abstracts'])\n\n if len(drugs) == 0:\n oncokbdata[level].append('[NOT SPECIFIED]')\n else:\n drugnames = []\n for drug in drugs:\n drugnames.append(drug['drugName'])\n oncokbdata[level].append('+'.join(drugnames))\n if annotation['diagnosticImplications'] is not None:\n getimplications(oncokbdata, dxLevels, annotation['diagnosticImplications'])\n\n if annotation['prognosticImplications'] is not None:\n getimplications(oncokbdata, pxLevels, annotation['prognosticImplications'])\n\n oncokbdata['highestDiagnosticImplicationLevel'] = annotation['highestDiagnosticImplicationLevel']\n oncokbdata['highestPrognosticImplicationLevel'] = annotation['highestPrognosticImplicationLevel']\n except:\n log.error(\"error when processing %s \" % annotation)\n # sys.exit()\n\n\n ret = []\n if annotate_hotspot:\n if annotation['hotspot']:\n ret.append('Y')\n else:\n ret.append('')\n\n _3dhotspot = pull3dhotspots(annotation['query']['hugoSymbol'], annotation['query']['consequence'], annotation['query']['proteinStart'], annotation['query']['proteinEnd'])\n ret.append(_3dhotspot)\n\n ret.append(oncokbdata[GENE_IN_ONCOKB_HEADER])\n ret.append(oncokbdata[VARIANT_IN_ONCOKB_HEADER])\n ret.append(oncokbdata['mutation_effect'])\n ret.append(oncokbdata['oncogenic'])\n for l in levels:\n ret.append(','.join(oncokbdata[l]))\n ret.append(gethighestsensitivitylevel(oncokbdata))\n ret.append(';'.join(oncokbdata['citations']))\n for l in dxLevels:\n ret.append(','.join(oncokbdata[l]))\n ret.append(gethighestDxPxlevel(dxLevels, [oncokbdata['highestDiagnosticImplicationLevel']]))\n\n for l in pxLevels:\n ret.append(','.join(oncokbdata[l]))\n ret.append(gethighestDxPxlevel(pxLevels, [oncokbdata['highestPrognosticImplicationLevel']]))\n\n return ret\n\n\ndef gethighestsensitivitylevel(oncokbdata):\n r1 = set()\n if \"LEVEL_R1\" in oncokbdata:\n r1 = set(oncokbdata[\"LEVEL_R1\"])\n for l in levels:\n if l.startswith(\"LEVEL_R\") or l not in oncokbdata or oncokbdata[l] == '':\n continue\n if not r1.issuperset(set(oncokbdata[l])):\n return l\n return \"\"\n\ndef gethighestDxPxlevel(levels, oncokbdata):\n for l in levels:\n if l not in oncokbdata:\n continue\n return l\n return \"\"\n\ndef gettreatments(evidence):\n treatments = []\n for t in evidence['treatments']:\n drugs = []\n for d in t['drugs']:\n drugs.append(d['drugName'])\n treatments.append('+'.join(drugs))\n return treatments\n\n\ndef readCancerTypes(clinicalFile, data):\n with open(clinicalFile, 'rU') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n headers = readheaders(reader)\n\n iSample = geIndexOfHeader(headers, ['SAMPLE_ID'])\n iCancerType = geIndexOfHeader(headers, ['ONCOTREE_CODE', 'CANCER_TYPE'])\n\n for row in reader:\n data[row[iSample]] = row[iCancerType]\n\n return data\n\n\ndef readheaders(reader):\n headers = {}\n headers[\"length\"] = 0\n for row in reader:\n if not row[0].startswith(\"#\"):\n headers[\"^-$\"] = '\\t'.join(row) # the whole line\n headers[\"length\"] = len(row)\n i = 0\n for h in row:\n headers[h.upper()] = i\n headers[h] = i\n i = i + 1\n break\n return headers\n\ndef padrow(row, n):\n nr = len(row)\n if nr == n:\n return row\n\n if nr < n:\n return row + [\"\"] * (n - len(row))\n\n else: # nr<n\n return row[0:n]\n" ]
[ [ "matplotlib.use" ], [ "matplotlib.use", "matplotlib.pyplot.gca" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JunweiLiang/Object_Detection_Tracking
[ "f86caaec97669a6da56f1b402cca4e179a85d2f0" ]
[ "tmot/matching.py" ]
[ "import numpy as np\r\nimport scipy\r\nfrom scipy.spatial.distance import cdist\r\nimport lap # 0.4.0\r\n\r\nfrom cython_bbox import bbox_overlaps as bbox_ious\r\nfrom . import kalman_filter\r\n\r\ndef merge_matches(m1, m2, shape):\r\n O,P,Q = shape\r\n m1 = np.asarray(m1)\r\n m2 = np.asarray(m2)\r\n\r\n M1 = scipy.sparse.coo_matrix((np.ones(len(m1)), (m1[:, 0], m1[:, 1])), shape=(O, P))\r\n M2 = scipy.sparse.coo_matrix((np.ones(len(m2)), (m2[:, 0], m2[:, 1])), shape=(P, Q))\r\n\r\n mask = M1*M2\r\n match = mask.nonzero()\r\n match = list(zip(match[0], match[1]))\r\n unmatched_O = tuple(set(range(O)) - set([i for i, j in match]))\r\n unmatched_Q = tuple(set(range(Q)) - set([j for i, j in match]))\r\n\r\n return match, unmatched_O, unmatched_Q\r\n\r\n\r\ndef linear_assignment(cost_matrix, thresh):\r\n if cost_matrix.size == 0:\r\n return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))\r\n matches, unmatched_a, unmatched_b = [], [], []\r\n cost, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)\r\n for ix, mx in enumerate(x):\r\n if mx >= 0:\r\n matches.append([ix, mx])\r\n unmatched_a = np.where(x < 0)[0]\r\n unmatched_b = np.where(y < 0)[0]\r\n matches = np.asarray(matches)\r\n return matches, unmatched_a, unmatched_b\r\n\r\n\r\ndef ious(atlbrs, btlbrs):\r\n \"\"\"\r\n Compute cost based on IoU\r\n :type atlbrs: list[tlbr] | np.ndarray\r\n :type atlbrs: list[tlbr] | np.ndarray\r\n\r\n :rtype ious np.ndarray\r\n \"\"\"\r\n ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float)\r\n if ious.size == 0:\r\n return ious\r\n\r\n ious = bbox_ious(\r\n np.ascontiguousarray(atlbrs, dtype=np.float),\r\n np.ascontiguousarray(btlbrs, dtype=np.float)\r\n )\r\n\r\n return ious\r\n\r\n\r\ndef iou_distance(atracks, btracks):\r\n \"\"\"\r\n Compute cost based on IoU\r\n :type atracks: list[STrack]\r\n :type btracks: list[STrack]\r\n\r\n :rtype cost_matrix np.ndarray\r\n \"\"\"\r\n\r\n if (len(atracks)>0 and isinstance(atracks[0], np.ndarray)) or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):\r\n atlbrs = atracks\r\n btlbrs = btracks\r\n else:\r\n atlbrs = [track.tlbr for track in atracks]\r\n btlbrs = [track.tlbr for track in btracks]\r\n _ious = ious(atlbrs, btlbrs)\r\n cost_matrix = 1 - _ious\r\n\r\n return cost_matrix\r\n\r\ndef embedding_distance(tracks, detections, metric='cosine'):\r\n \"\"\"\r\n :param tracks: list[STrack]\r\n :param detections: list[BaseTrack]\r\n :param metric:\r\n :return: cost_matrix np.ndarray\r\n \"\"\"\r\n\r\n cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float)\r\n if cost_matrix.size == 0:\r\n return cost_matrix\r\n det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float)\r\n track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float)\r\n cost_matrix = np.maximum(0.0, cdist(track_features, det_features)) # Nomalized features\r\n\r\n return cost_matrix\r\n\r\n\r\ndef fuse_motion(kf, cost_matrix, tracks, detections, only_position=False, lambda_=0.98):\r\n if cost_matrix.size == 0:\r\n return cost_matrix\r\n gating_dim = 2 if only_position else 4\r\n gating_threshold = kalman_filter.chi2inv95[gating_dim]\r\n measurements = np.asarray([det.to_xyah() for det in detections])\r\n for row, track in enumerate(tracks):\r\n gating_distance = kf.gating_distance(\r\n track.mean, track.covariance, measurements, only_position, metric='maha')\r\n cost_matrix[row, gating_distance > gating_threshold] = np.inf\r\n cost_matrix[row] = lambda_ * cost_matrix[row] + (1-lambda_)* gating_distance\r\n return cost_matrix\r\n" ]
[ [ "numpy.asarray", "numpy.ascontiguousarray", "scipy.spatial.distance.cdist", "numpy.where", "numpy.empty" ] ]
[ { "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": [] } ]
cailab-tamu/scTenifoldXct
[ "d25ded8dfb7f2951217a30ab71eccd6b060178f6", "d25ded8dfb7f2951217a30ab71eccd6b060178f6" ]
[ "tests/test_stat.py", "scTenifoldXct/pcNet.py" ]
[ "import pytest\n\nimport itertools\n\nimport pandas as pd\nimport numpy as np\n\nfrom scTenifoldXct.core import null_test\n\n\ndef generate_fake_df_nn(n_ligand=3000, n_receptors=3000, n_cands=200):\n gene_names = [f\"GENE{i}\" for i in range(max(n_ligand, n_receptors))]\n iteration = itertools.product(gene_names, gene_names)\n inds, ligands, receptors = [], [], []\n for i, j in iteration:\n inds.append(f\"{i}_{j}\")\n ligands.append(i)\n receptors.append(j)\n df = pd.DataFrame({\"ligand\": ligands,\n \"receptor\": receptors,\n \"dist\": np.random.chisquare(1, (n_ligand * n_receptors,)),\n \"correspondence\": np.random.lognormal(0, 4, size=(n_ligand * n_receptors,))},\n index=inds)\n return df, np.random.choice(df.index, size=(n_cands,), replace=False)\n\n\[email protected](\"df_nn,candidates\", [\n generate_fake_df_nn(3000, 3000, 200),\n generate_fake_df_nn(1000, 1000, 200),\n])\[email protected](\"filter_zeros\", [True])\ndef test_null_test(df_nn, candidates, filter_zeros):\n null_test(df_nn=df_nn, candidates=candidates, filter_zeros=filter_zeros)\n\n\ndef test_chi2_test(xct_skin):\n xct_skin.train_nn(n_steps= 1000, lr = 0.001)\n xct_skin.chi2_test(dof=3, pval=0.05, cal_FDR=True, plot_result=True)", "import numpy as np\nfrom numpy.linalg import svd\nfrom scipy import sparse\nimport os\nimport time\nimport ray\n\n\ndef pcCoefficients(X, K, nComp):\n y = X[:, K] \n Xi = np.delete(X, K, 1)\n U, s, VT = svd(Xi, full_matrices=False) \n #print ('U:', U.shape, 's:', s.shape, 'VT:', VT.shape)\n V = VT[:nComp, :].T\n #print('V:', V.shape)\n score = Xi@V\n t = np.sqrt(np.sum(score**2, axis=0))\n score_lsq = ((score.T / (t**2)[:, None])).T\n beta = np.sum(y[:, None]*score_lsq, axis=0)\n beta = V@beta\n return list(beta) \n\ndef pcNet(X, # X: cell * gene\n nComp: int = 3, \n scale: bool = True, \n symmetric: bool = True, \n q: float = 0., # q: 0-100\n as_sparse: bool = True,\n random_state: int = 0): \n X = X.toarray() if sparse.issparse(X) else X\n if nComp < 2 or nComp >= X.shape[1]:\n raise ValueError('nComp should be greater or equal than 2 and lower than the total number of genes') \n else:\n np.random.seed(random_state)\n n = X.shape[1] # genes \n B = np.array([pcCoefficients(X, k, nComp) for k in range(n)]) \n A = np.ones((n, n), dtype=float)\n np.fill_diagonal(A, 0)\n for i in range(n):\n A[i, A[i, :]==1] = B[i, :] \n if scale:\n absA = abs(A)\n A = A / np.max(absA)\n if q > 0:\n A[absA < np.percentile(absA, q)] = 0\n if symmetric: # place in the end\n A = (A + A.T)/2\n #diag(A) <- 0\n if as_sparse:\n A = sparse.csc_matrix(A) \n return A\n\[email protected]\ndef pc_net_parallel(X, # X: cell * gene\n nComp: int = 3,\n scale: bool = True,\n symmetric: bool = True,\n q: float = 0.,\n as_sparse: bool = True,\n random_state: int = 0):\n return pcNet(X, nComp = nComp, scale = scale, symmetric = symmetric, q = q, \n as_sparse = as_sparse, random_state = random_state)\n\ndef pc_net_single(X, # X: cell * gene\n nComp: int = 3,\n scale: bool = True,\n symmetric: bool = True,\n q: float = 0.,\n as_sparse: bool = True,\n random_state: int = 0):\n return pcNet(X, nComp = nComp, scale = scale, symmetric = symmetric, q = q, \n as_sparse = as_sparse, random_state = random_state)\n\ndef make_pcNet(X, \n nComp: int = 3, \n scale: bool = True, \n symmetric: bool = True, \n q: float = 0., \n as_sparse: bool = True, \n random_state: int = 0,\n n_cpus: int = 1, # -1: use all CPUs\n timeit: bool = True):\n start_time = time.time()\n if n_cpus != 1:\n if ray.is_initialized():\n ray.shutdown()\n if n_cpus == -1:\n n_cpus = os.cpu_count()\n ray.init(num_cpus = n_cpus)\n print(f'ray init, using {n_cpus} CPUs')\n\n X_ray = ray.put(X) # put X to distributed object store and return object ref (ID)\n # print(X_ray)\n net = pc_net_parallel.remote(X_ray, nComp = nComp, scale = scale, symmetric = symmetric, q = q, \n as_sparse = as_sparse, random_state = random_state)\n net = ray.get(net)\n else:\n net = pc_net_single(X, nComp = nComp, scale = scale, symmetric = symmetric, q = q, \n as_sparse = as_sparse, random_state = random_state)\n if ray.is_initialized():\n ray.shutdown()\n if timeit:\n duration = time.time() - start_time\n print('execution time of making pcNet: {:.2f} s'.format(duration))\n return net\n\ndef main():\n counts = np.random.randint(0, 10, (5, 100))\n net = make_pcNet(counts, as_sparse = True, timeit = True, n_cpus = -1)\n print(f'input counts shape: {counts.shape},\\nmake pcNet completed, shape: {net.shape}')\n\nif __name__ == '__main__':\n main() \n \n \n" ]
[ [ "numpy.random.lognormal", "numpy.random.chisquare", "numpy.random.choice" ], [ "scipy.sparse.csc_matrix", "numpy.linalg.svd", "scipy.sparse.issparse", "numpy.random.seed", "numpy.percentile", "numpy.ones", "numpy.max", "numpy.delete", "numpy.fill_diagonal", "numpy.sum", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] } ]
andreyyec/Texas_Tech_AI
[ "e4e8e41c65b41a1a684f1f65d21cf5427abdb046" ]
[ "practices/week6/assignment_exercise_3.py" ]
[ "import numpy as np\nimport pandas as pd\nimport pickle\nimport tensorflow as tf\nimport sklearn.metrics\nimport matplotlib.pyplot as plt\n\n# Load the training and test data from the Pickle file\nwith open(\"../datasets/credit_card_default_dataset.pickle\", \"rb\") as f:\n train_data, train_labels, test_data, test_labels = pickle.load(f)\n\n# Get some lengths\nn_inputs = train_data.shape[1]\nnsamples = train_data.shape[0]\n\n# Training constants\nn_nodes_l1 = 5\nbatch_size = 32\nlearning_rate = .001 # Initial rate for Adam\nn_epochs = 1000\neval_step = 5\n\nn_batches = int(np.ceil(nsamples / batch_size))\n\n# Print the configuration\nprint(\"Batch size: {} Num batches: {} Num epochs: {} Learning rate: {}\".format(batch_size, n_batches, n_epochs, learning_rate))\nprint(\"Num nodes in L1: {} Activation function: ELU\".format(n_nodes_l1))\n\n# TensorFlow constants\n\n# Input vector placeholders. Length is unspecified.\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\nY = tf.placeholder(tf.float32, shape=(None, 1), name=\"Y\")\n\n# Hidden layer 1:\n# Inputs: n_inputs\n# Outputs: n_nodes_l1\n# Activation: ELU\nW_L1 = tf.Variable(tf.truncated_normal([n_inputs, n_nodes_l1], stddev=2/np.sqrt(n_inputs)))\nb_L1 = tf.Variable(tf.zeros(n_nodes_l1))\nY_L1 = tf.nn.elu(tf.add(tf.matmul(X, W_L1), b_L1))\n#Y_L1 = tf.nn.relu(tf.add(tf.matmul(X, W_L1), b_L1))\n\n# Output layer:\n# Inputs: n_nodes_l1\n# Outputs: 1\n# Activation: logistic\nW_L2 = tf.Variable(tf.truncated_normal([n_nodes_l1, 1], stddev=1/np.sqrt(n_nodes_l1)))\nb_L2 = tf.Variable(tf.zeros(1))\nY_L2_linear = tf.add(tf.matmul(Y_L1, W_L2), b_L2)\n\n# Cost function, plus the sigmoid part of the prediction\ncost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits = Y_L2_linear, labels = Y))\n\n# Optimize cost through gradient descent\n#optimizer = tf.train.GradientDescentOptimizer(learning_rate)\noptimizer = tf.train.AdamOptimizer(learning_rate)\nupdate_op = optimizer.minimize(cost)\n\n# Prediction probability values\nY_pred_proba_calc = tf.nn.sigmoid(Y_L2_linear)\n\n# Create TensorFlow session and initialize it\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# Initialize lists to hold the history of metrics per epoch\ntrn_cost_hist = []\ntest_cost_hist = []\ntrn_auroc_hist = []\ntest_auroc_hist = []\n\nepoch = 0\nwhile epoch < n_epochs:\n batch = 0\n\n # Save a vector of cost values per batch\n cost_vals = np.zeros(n_batches)\n\n while batch < n_batches:\n\n # Select the data for the next batch\n dataidx = batch * batch_size\n X_batch = train_data[dataidx:(dataidx+batch_size)]\n Y_batch = train_labels[dataidx:(dataidx+batch_size)].values.reshape(-1,1)\n feed_dict = {X: X_batch, Y: Y_batch}\n\n # Run one iteration of the computation session to update coefficients\n _, cost_vals[batch] = sess.run([update_op, cost], feed_dict=feed_dict)\n batch += 1\n\n # Evaluate and print the results so far\n if (epoch % eval_step == 0):\n\n # Compute the average cost for all mini-batches in this epoch\n trn_cost_avg = np.mean(cost_vals)\n\n # Compute the ROC AUC against the full training data\n feed_dict = {X: train_data, Y: train_labels.values.reshape(-1,1)}\n Y_pred_proba_train = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n train_auroc = sklearn.metrics.roc_auc_score(train_labels, Y_pred_proba_train)\n\n # Compute the cost and ROC AUC against the test data\n feed_dict = {X: test_data, Y: test_labels.values.reshape(-1,1)}\n Y_pred_proba_test = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n test_cost = sess.run(cost, feed_dict=feed_dict)\n test_auroc = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba_test)\n\n print(\"Epoch: {:4d} trn_cost: {:.5f} test_cost: {:.5f} trn_auroc: {:.4f} test_auroc: {:.4f}\".\\\n format(epoch, trn_cost_avg, test_cost, train_auroc, test_auroc))\n\n # Save the metrics to the history\n trn_cost_hist.append(trn_cost_avg)\n test_cost_hist.append(test_cost)\n trn_auroc_hist.append(train_auroc)\n test_auroc_hist.append(test_auroc)\n\n epoch += 1\n\n# Print the best results (as if we had done early stopping)\nepoch_hist = [i for i in range(0, n_epochs, eval_step)]\n\nbest_idx = test_auroc_hist.index(max(test_auroc_hist))\nprint(\"Max test ROC AUC: {:.4f} at epoch: {}\".format(test_auroc_hist[best_idx], epoch_hist[best_idx]))\n\nbest_idx = trn_auroc_hist.index(max(trn_auroc_hist))\nprint(\"Max train ROC AUC: {:.4f} at epoch: {}\".format(trn_auroc_hist[best_idx], epoch_hist[best_idx]))\n\nbest_idx = test_cost_hist.index(min(test_cost_hist))\nprint(\"Min test cost: {:.5f} at epoch: {}\".format(test_cost_hist[best_idx], epoch_hist[best_idx]))\n\nbest_idx = trn_cost_hist.index(min(trn_cost_hist))\nprint(\"Min train cost: {:.5f} at epoch: {}\".format(trn_cost_hist[best_idx], epoch_hist[best_idx]))\n\n# Plot the metrics history\nplt.plot(epoch_hist, trn_cost_hist, \"b\")\nplt.plot(epoch_hist, test_cost_hist, \"r\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"cost\")\nplt.title(\"Cost vs. epoch\")\nplt.figure()\nplt.plot(epoch_hist, trn_auroc_hist, \"b\")\nplt.plot(epoch_hist, test_auroc_hist, \"r\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"ROC AUC\")\nplt.title(\"ROC AUC vs. epoch\")\nplt.show()\n" ]
[ [ "tensorflow.matmul", "tensorflow.nn.sigmoid", "numpy.sqrt", "matplotlib.pyplot.title", "tensorflow.zeros", "matplotlib.pyplot.figure", "tensorflow.placeholder", "matplotlib.pyplot.plot", "tensorflow.global_variables_initializer", "numpy.ceil", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "numpy.mean", "tensorflow.Session", "tensorflow.train.AdamOptimizer", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
pengfei99/openfood
[ "2b65af02ce34bf8193d357ef3661da749d2d9671" ]
[ "siamesenetwork/siamesePreTrainedEmbeddings.py" ]
[ "# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nDefine the siamese network for one-shot learning,\nfor french short labels\n02/06/2021\n@author: milena-git, from jeremylhour courtesy\n\"\"\"\nimport torch\nimport torch.nn as nn\n\n\ndef _createEmbeddingLayer(weights_matrix, non_trainable=False):\n \"\"\"\n _createEmbeddingLayer:\n create a layer from pre-trained embeddings\n\n @param weights_matrix (np.array):\n @param non_trainable (bool):\n \"\"\"\n weights_matrix = torch.tensor(weights_matrix)\n num_embeddings, embedding_dim = weights_matrix.size()\n emb_layer = nn.Embedding(num_embeddings, embedding_dim)\n emb_layer.load_state_dict({'weight': weights_matrix})\n if non_trainable:\n emb_layer.weight.requires_grad = False\n return emb_layer, num_embeddings, embedding_dim\n\n\nclass SiamesePreTrainedQuadruplet(nn.Module):\n\n def __init__(self, weights_matrix, length, dim=100):\n \"\"\"\n Initialize the siamese network with pre-trained embeddings\n\n @param weights_matrix (torch.tensor):\n @param length (int): longueur des inputs\n @param dim (int): dimension of the output embedding space\n \"\"\"\n super(SiamesePreTrainedQuadruplet, self).__init__()\n self.dim = dim\n self.length = length\n self.embedding = nn.Embedding.from_pretrained(weights_matrix, padding_idx=0)\n self.fc1 = nn.Sequential(\n nn.Linear(self.length * weights_matrix.size()[1], 1000),\n nn.ReLU(inplace=True),\n nn.Linear(1000, 800),\n nn.Dropout(0.2),\n nn.Linear(800, 500),\n nn.Dropout(0.2),\n nn.Linear(500, self.dim)\n )\n\n def forward_once(self, x):\n \"\"\"\n Run one of the network on a single image\n\n @param x (): img output from SiameseNetworkDataset\n \"\"\"\n embedded = self.embedding(x)\n embedded = torch.reshape(embedded, (embedded.size()[0], embedded.size()[1] * embedded.size()[2]))\n output = self.fc1(embedded)\n return output\n\n def forward(self, anchor, positive, negative1, negative2):\n \"\"\"\n Run the model forward, by applying forward_once to each inputs\n Main forward that is used during train, wraps forward_once().\n\n @param anchor, positive, negative1, negative2 (): output from SiameseNetworkDataset\n \"\"\"\n anchor_o, positive_o, negative1_o, negative2_o = self.forward_once(anchor), self.forward_once(\n positive), self.forward_once(negative1), self.forward_once(negative2)\n return anchor_o, positive_o, negative1_o, negative2_o\n\n\nif __name__ == '__main__':\n pass\n" ]
[ [ "torch.nn.Dropout", "torch.nn.Embedding", "torch.tensor", "torch.nn.Linear", "torch.nn.Embedding.from_pretrained", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DwijayDS/fastestimator
[ "6061a4fbbeb62a2194ef82ba8017f651710d0c65", "9b288cb2bd870f971ec4cee09d0b3205e1316a94", "9b288cb2bd870f971ec4cee09d0b3205e1316a94", "9b288cb2bd870f971ec4cee09d0b3205e1316a94", "6061a4fbbeb62a2194ef82ba8017f651710d0c65", "9b288cb2bd870f971ec4cee09d0b3205e1316a94", "6061a4fbbeb62a2194ef82ba8017f651710d0c65", "6061a4fbbeb62a2194ef82ba8017f651710d0c65" ]
[ "test/PR_test/unit_test/op/numpyop/univariate/test_autocontrast.py", "fastestimator/trace/metric/mcc.py", "fastestimator/backend/_iwd.py", "fastestimator/trace/metric/bleu_score.py", "fastestimator/backend/_lambertw.py", "fastestimator/trace/io/traceability.py", "test/PR_test/integration_test/trace/metric/test_calibration_error.py", "test/PR_test/unit_test/op/numpyop/multivariate/test_flip.py" ]
[ "# Copyright 2021 The FastEstimator 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 unittest\n\nimport numpy as np\n\nfrom fastestimator.op.numpyop.univariate import AutoContrast\n\n\nclass TestAutoContrast(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.single_input = [np.random.randint(0, 256, size=(28, 28, 3)).astype(np.uint8)]\n cls.single_output_shape = (28, 28, 3)\n cls.multi_input = [\n np.random.randint(0, 256, size=(28, 28, 3)).astype(np.uint8),\n np.random.randint(0, 256, size=(28, 28, 3)).astype(np.uint8)\n ]\n cls.multi_output_shape = (28, 28, 3)\n\n def test_single_input(self):\n autocontrast = AutoContrast(inputs='x', outputs='x')\n output = autocontrast.forward(data=self.single_input, state={})\n with self.subTest('Check output type'):\n self.assertEqual(type(output), list)\n with self.subTest('Check output image shape'):\n self.assertEqual(output[0].shape, self.single_output_shape)\n\n def test_multi_input(self):\n autocontrast = AutoContrast(inputs='x', outputs='x')\n output = autocontrast.forward(data=self.multi_input, state={})\n with self.subTest('Check output type'):\n self.assertEqual(type(output), list)\n with self.subTest('Check output list length'):\n self.assertEqual(len(output), 2)\n for img_output in output:\n with self.subTest('Check output image shape'):\n self.assertEqual(img_output.shape, self.multi_output_shape)\n", "# Copyright 2019 The FastEstimator Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom typing import Union, Iterable\n\nimport numpy as np\nfrom sklearn.metrics import matthews_corrcoef\n\nfrom fastestimator.trace.meta._per_ds import per_ds\nfrom fastestimator.trace.trace import Trace\nfrom fastestimator.util.data import Any, Data, Dict\nfrom fastestimator.util.traceability_util import traceable\nfrom fastestimator.util.util import to_number\n\n\n@per_ds\n@traceable()\nclass MCC(Trace):\n \"\"\"A trace which computes the Matthews Correlation Coefficient for a given set of predictions.\n\n This is a preferable metric to accuracy or F1 score since it automatically corrects for class imbalances and does\n not depend on the choice of target class (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6941312/). Ideal value is 1,\n a value of 0 means your predictions are completely uncorrelated with the true data. A value less than zero implies\n anti-correlation (you should invert your classifier predictions in order to do better).\n\n Args:\n true_key: Name of the key that corresponds to ground truth in the batch dictionary.\n pred_key: Name of the key that corresponds to predicted score in the batch dictionary.\n mode: What mode(s) to execute this Trace in. For example, \"train\", \"eval\", \"test\", or \"infer\". To execute\n regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument\n like \"!infer\" or \"!train\".\n ds_id: What dataset id(s) to execute this Trace in. To execute regardless of ds_id, pass None. To execute in all\n ds_ids except for a particular one, you can pass an argument like \"!ds1\".\n output_name: What to call the output from this trace (for example in the logger output).\n per_ds: Whether to automatically compute this metric individually for every ds_id it runs on, in addition to\n computing an aggregate across all ds_ids on which it runs. This is automatically False if `output_name`\n contains a \"|\" character.\n **kwargs: Additional keyword arguments that pass to sklearn.metrics.matthews_corrcoef()\n\n Raises:\n ValueError: One of [\"y_true\", \"y_pred\"] argument exists in `kwargs`.\n \"\"\"\n def __init__(self,\n true_key: str,\n pred_key: str,\n mode: Union[None, str, Iterable[str]] = (\"eval\", \"test\"),\n ds_id: Union[None, str, Iterable[str]] = None,\n output_name: str = \"mcc\",\n per_ds: bool = True,\n **kwargs) -> None:\n MCC.check_kwargs(kwargs)\n super().__init__(inputs=(true_key, pred_key), mode=mode, outputs=output_name, ds_id=ds_id)\n self.kwargs = kwargs\n self.y_true = []\n self.y_pred = []\n self.per_ds = per_ds\n\n @property\n def true_key(self) -> str:\n return self.inputs[0]\n\n @property\n def pred_key(self) -> str:\n return self.inputs[1]\n\n def on_epoch_begin(self, data: Data) -> None:\n self.y_true = []\n self.y_pred = []\n\n def on_batch_end(self, data: Data) -> None:\n y_true, y_pred = to_number(data[self.true_key]), to_number(data[self.pred_key])\n if y_true.shape[-1] > 1 and y_true.ndim > 1:\n y_true = np.argmax(y_true, axis=-1)\n if y_pred.shape[-1] > 1 and y_pred.ndim > 1:\n y_pred = np.argmax(y_pred, axis=-1)\n else:\n y_pred = np.round(y_pred)\n assert y_pred.size == y_true.size\n self.y_true.extend(y_true)\n self.y_pred.extend(y_pred)\n\n def on_epoch_end(self, data: Data) -> None:\n data.write_with_log(self.outputs[0], matthews_corrcoef(y_true=self.y_true, y_pred=self.y_pred, **self.kwargs))\n\n @staticmethod\n def check_kwargs(kwargs: Dict[str, Any]) -> None:\n \"\"\"Check if `kwargs` has any blacklist argument and raise an error if it does.\n\n Args:\n kwargs: Keywork arguments to be examined.\n\n Raises:\n ValueError: One of [\"y_true\", \"y_pred\"] argument exists in `kwargs`.\n \"\"\"\n blacklist = [\"y_true\", \"y_pred\"]\n illegal_kwarg = [x for x in blacklist if x in kwargs]\n if illegal_kwarg:\n raise ValueError(\n f\"Arguments {illegal_kwarg} cannot exist in kwargs, since FastEstimator will later directly use them in\"\n \" sklearn.metrics.matthews_corrcoef()\")\n", "# Copyright 2019 The FastEstimator 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 math\nfrom typing import Optional, TypeVar\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\n\nfrom fastestimator.backend._maximum import maximum\nfrom fastestimator.backend._reduce_sum import reduce_sum\nfrom fastestimator.backend._reshape import reshape\nfrom fastestimator.backend._tensor_pow import tensor_pow\nfrom fastestimator.backend._to_tensor import to_tensor\nfrom fastestimator.util.util import TENSOR_TO_NP_DTYPE\n\nTensor = TypeVar('Tensor', tf.Tensor, torch.Tensor, np.ndarray)\n\n\ndef iwd(tensor: Tensor,\n power: float = 1.0,\n max_prob: float = 0.95,\n pairwise_distance: float = 1.0,\n eps: Optional[Tensor] = None) -> Tensor:\n \"\"\"Compute the Inverse Weighted Distance from the given input.\n\n This can be used as an activation function for the final layer of a neural network instead of softmax. For example,\n instead of: model.add(layers.Dense(classes, activation='softmax')), you could use:\n model.add(layers.Dense(classes, activation=lambda x: iwd(tf.nn.sigmoid(x))))\n\n This method can be used with Numpy data:\n ```python\n n = np.array([[0.5]*5, [0]+[1]*4])\n b = fe.backend.iwd(n) # [[0.2, 0.2, 0.2, 0.2, 0.2], [0.95, 0.0125, 0.0125, 0.0125, 0.0125]]\n ```\n\n This method can be used with TensorFlow tensors:\n ```python\n t = tf.constant([[0.5]*5, [0]+[1]*4])\n b = fe.backend.iwd(n) # [[0.2, 0.2, 0.2, 0.2, 0.2], [0.95, 0.0125, 0.0125, 0.0125, 0.0125]]\n ```\n\n This method can be used with PyTorch tensors:\n ```python\n p = torch.tensor([[0.5]*5, [0]+[1]*4])\n b = fe.backend.iwd(n) # [[0.2, 0.2, 0.2, 0.2, 0.2], [0.95, 0.0125, 0.0125, 0.0125, 0.0125]]\n ```\n\n Args:\n tensor: The input value. Should be of shape (Batch, C) where every element in C corresponds to a (non-negative)\n distance to a target class.\n power: The power to raise the inverse distances to. 1.0 results in a fairly intuitive probability output. Larger\n powers can widen regions of certainty, whereas values between 0 and 1 can widen regions of uncertainty.\n max_prob: The maximum probability to assign to a class estimate when it is distance zero away from the target.\n For numerical stability this must be less than 1.0. We have found that using smaller values like 0.95 can\n lead to natural adversarial robustness.\n pairwise_distance: The distance to any other class when the distance to a target class is zero. For example, if\n you have a perfect match for class 'a', what distance should be reported to class 'b'. If you have a metric\n where this isn't constant, just use an approximate expected distance. In that case `max_prob` will only give\n you approximate control over the true maximum probability.\n eps: The numeric stability constant to be used when d approaches zero. If None then it will be computed using\n `max_prob` and `pairwise_distance`. If not None, then `max_prob` and `pairwise_distance` will be ignored.\n\n Returns:\n A probability distribution of shape (Batch, C) where smaller distances from `tensor` correspond to larger\n probabilities.\n \"\"\"\n if eps is None:\n eps = np.array(pairwise_distance * math.pow((1.0 - max_prob) / (max_prob * (tensor.shape[-1] - 1)), 1 / power),\n dtype=TENSOR_TO_NP_DTYPE[tensor.dtype])\n eps = to_tensor(\n eps, target_type='torch' if isinstance(tensor, torch.Tensor) else 'tf' if tf.is_tensor(tensor) else 'np')\n if isinstance(eps, torch.Tensor):\n eps = eps.to(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n tensor = maximum(tensor, eps)\n tensor = tensor_pow(1.0 / tensor, power)\n tensor = tensor / reshape(reduce_sum(tensor, axis=-1), shape=[-1, 1])\n return tensor\n", "# Copyright 2022 The FastEstimator 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 math\nfrom collections import Counter\nfrom fractions import Fraction\nfrom typing import Iterable, List, Tuple, Union\n\nimport numpy as np\nfrom nltk.translate.bleu_score import SmoothingFunction, brevity_penalty, modified_precision, sentence_bleu\n\nfrom fastestimator.trace.meta._per_ds import per_ds\nfrom fastestimator.trace.trace import Trace\nfrom fastestimator.util.data import Data\nfrom fastestimator.util.traceability_util import traceable\nfrom fastestimator.util.util import to_number\n\n\ndef get_formated_list(input_data: np.ndarray) -> List[str]:\n \"\"\"\n Filter the padding(elements with 0 value) and typecast the elements of list to str.\n\n Returns:\n Formated list.\n \"\"\"\n return [str(i) for i in input_data if i != 0]\n\n\ndef get_formated_reference(input_data: np.ndarray) -> List[List[str]]:\n \"\"\"\n Encapsulate formated list in another list.\n\n Returns:\n List encapsulated formated list.\n \"\"\"\n return [get_formated_list(input_data)]\n\n\n@per_ds\n@traceable()\nclass BleuScore(Trace):\n \"\"\"Calculate the Bleu score for a nlp task and report it back to the logger.\n\n Calculate BLEU score (Bilingual Evaluation Understudy) from Papineni, Kishore, Salim Roukos, Todd Ward, and\n Wei-Jing Zhu. 2002.\"BLEU: a method for automatic evaluation of machine translation.\"In Proceedings of ACL.\n https://www.aclweb.org/anthology/P02-1040.pdf\n\n The BLEU metric scores a translation on a scale of 0 to 1, in an attempt to measure the adequacy and fluency of\n the Machine Translation output. The closer to 1 the test sentences score, the more overlap there is with their\n human reference translations and thus, the better the system is deemed to be. The MT output would score 1 only\n if it is identical to the reference human translation. But even two competent human translations of the exact\n same material may only score in the 0.6 or 0.7 range as they are likely to use different vocabulary and phrasing.\n We should be wary of very high BLEU scores (in excess of 0.7) as it is probably measuring improperly or overfitting.\n\n The default BLEU calculates a score for up to 4-grams using uniform weights (this is called BLEU-4). To evaluate\n your translations with lower order ngrams, use customized \"n_gram\". E.g. when accounting for up to 2-grams\n with uniform weights (this is called BLEU-2) use n_gram=2.\n\n If there is no ngrams overlap for any order of n-grams, BLEU returns the value 0. This is because the precision\n for the order of n-grams withoutoverlap is 0, and the geometric mean in the final BLEU score computation multiplies\n the 0 with the precision of other n-grams. This results in 0. Shorter translations may have inflated precision values due to having\n smaller denominators; therefore, we give them proportionally smaller smoothed counts. Instead of scaling to 1/(2^k),\n Chen and Cherry suggests dividing by 1/ln(len(T)), where T is the length of the translation.\n\n\n Args:\n true_key: Name of the key that corresponds to ground truth in the batch dictionary.\n pred_key: Name of the key that corresponds to predicted score in the batch dictionary.\n mode: What mode(s) to execute this Trace in. For example, \"train\", \"eval\", \"test\", or \"infer\". To execute\n regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument\n like \"!infer\" or \"!train\".\n ds_id: What dataset id(s) to execute this Trace in. To execute regardless of ds_id, pass None. To execute in all\n ds_ids except for a particular one, you can pass an argument like \"!ds1\".\n output_name: Name of the key to store back to the state.\n n_gram: Number of grams used to calculate bleu score.\n per_ds: Whether to automatically compute this metric individually for every ds_id it runs on, in addition to\n computing an aggregate across all ds_ids on which it runs. This is automatically False if `output_name`\n contains a \"|\" character.\n\n \"\"\"\n def __init__(self,\n true_key: str,\n pred_key: str,\n mode: Union[None, str, Iterable[str]] = (\"eval\", \"test\"),\n ds_id: Union[None, str, Iterable[str]] = None,\n output_name: str = 'bleu_score',\n n_gram: int = 4,\n per_ds: bool = True) -> None:\n super().__init__(inputs=(true_key, pred_key), outputs=output_name, mode=mode, ds_id=ds_id)\n self.n_gram = n_gram\n self.weights = self.get_output_weights()\n self.per_ds = per_ds\n self.smoothing_function = SmoothingFunction().method4\n self.no_of_correct_predicted = Counter()\n self.no_of_total_predicted = Counter()\n self.total_hypotheses_length = 0\n self.total_references_length = 0\n\n @property\n def true_key(self) -> str:\n return self.inputs[0]\n\n @property\n def pred_key(self) -> str:\n return self.inputs[1]\n\n def get_output_weights(self) -> Tuple[float, ...]:\n \"\"\"\n Generate weights tuple based on n_gram.\n\n Returns:\n Tuple of n_gram weights\n\n Raises:\n ValueError: When n_gram provided is less than or equal to 0..\n \"\"\"\n if self.n_gram > 0:\n return (1 / self.n_gram, ) * self.n_gram\n else:\n raise ValueError(\"N Gram should be a positive integer.\")\n\n def on_epoch_begin(self, data: Data) -> None:\n self.no_of_correct_predicted = Counter()\n self.no_of_total_predicted = Counter()\n self.total_hypotheses_length = 0\n self.total_references_length = 0\n\n def get_brevity_penalty(self) -> float:\n \"\"\"\n Calculate the brevity penalty of the corpus.\n\n Returns:\n Brevity penalty for corpus.\n \"\"\"\n return brevity_penalty(self.total_references_length, self.total_hypotheses_length)\n\n def get_smoothened_modified_precision(self) -> List[float]:\n \"\"\"\n Calculate the smoothened modified precision.\n\n Returns:\n List of smoothened modified precision of n_grams.\n \"\"\"\n # Collects the various precision values for the different ngram orders.\n p_n = [\n Fraction(self.no_of_correct_predicted[i], self.no_of_total_predicted[i], _normalize=False)\n for i in range(1, self.n_gram + 1)\n ]\n # Smoothen the modified precision.\n return self.smoothing_function(p_n, [], [], hyp_len=self.total_hypotheses_length)\n\n def get_corpus_bleu_score(self) -> float:\n \"\"\"\n Calculate the bleu score using corpus level brevity penalty and geometric average precision.\n\n Returns:\n Corpus level bleu score.\n \"\"\"\n # Calculate corpus-level brevity penalty.\n bp = self.get_brevity_penalty()\n\n # Returns 0 if there's no matching 1-gram\n if self.no_of_correct_predicted[1] == 0:\n return 0\n\n n_gram_precision = self.get_smoothened_modified_precision()\n\n geometric_average_precision = math.exp(\n math.fsum((w_i * math.log(p_i) for w_i, p_i in zip(self.weights, n_gram_precision) if p_i > 0)))\n bleu_score = bp * geometric_average_precision\n\n return bleu_score\n\n def batch_precision_parameters(self, references: List[np.ndarray], hypotheses: List[np.ndarray]) -> List[float]:\n \"\"\"\n Calculate modified precision per n_gram for input references and hypotheses combinations.\n\n Args:\n references: Ground truth sentences.\n hypotheses: Predicted sentences.\n\n Returns:\n List of sentence level bleu scores\n \"\"\"\n\n assert len(references) == len(hypotheses), (\n \"The number of hypotheses and their reference(s) should be the same \")\n\n sentence_level_scores = []\n # Iterate through each hypothesis and their corresponding references.\n for reference, hypothesis in zip(references, hypotheses):\n\n # For each order of ngram, calculate the correct predicted words and\n # total predicted words for the corpus-level modified precision.\n reference = get_formated_reference(reference)\n hypothesis = get_formated_list(hypothesis)\n for i in range(1, self.n_gram + 1):\n p_i = modified_precision(reference, hypothesis, i)\n self.no_of_correct_predicted[i] += p_i.numerator\n self.no_of_total_predicted[i] += p_i.denominator\n\n sentence_level_scores.append(sentence_bleu(reference, hypothesis, self.weights, self.smoothing_function))\n\n # Calculate the hypothesis length and the closest reference length.\n # Adds them to the corpus-level hypothesis and reference counts.\n hyp_len = len(hypothesis)\n self.total_hypotheses_length += hyp_len\n ref_lens = (len(ref) for ref in reference)\n self.total_references_length += min(ref_lens, key=lambda ref_len: (abs(ref_len - hyp_len), ref_len))\n\n return sentence_level_scores\n\n def on_batch_end(self, data: Data) -> None:\n y_pred, y_true = to_number(data['pred']), to_number(data['target_real'])\n if y_true.shape[-1] > 1 and y_true.ndim > 2:\n y_true = np.argmax(y_true, axis=-1)\n if y_pred.shape[-1] > 1 and y_pred.ndim > 2:\n y_pred = np.argmax(y_pred, axis=-1)\n sentence_level_scores = self.batch_precision_parameters(y_true, y_pred)\n data.write_per_instance_log(self.outputs[0], sentence_level_scores)\n\n def on_epoch_end(self, data: Data) -> None:\n data.write_with_log(self.outputs[0], round(self.get_corpus_bleu_score(), 5))\n", "# Copyright 2020 The FastEstimator 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 math\nfrom typing import TypeVar\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport torch\nfrom scipy.special import lambertw as lamw\n\nTensor = TypeVar('Tensor', tf.Tensor, torch.Tensor, np.ndarray)\n\n\ndef lambertw(tensor: Tensor) -> Tensor:\n \"\"\"Compute the k=0 branch of the Lambert W function.\n\n See https://en.wikipedia.org/wiki/Lambert_W_function for details. Only valid for inputs >= -1/e (approx -0.368). We\n do not check this for the sake of speed, but if an input is out of domain the return value may be random /\n inconsistent or even NaN.\n\n This method can be used with Numpy data:\n ```python\n n = np.array([-1.0/math.e, -0.34, -0.32, -0.2, 0, 0.12, 0.15, math.e, 5, math.exp(1 + math.e), 100])\n b = fe.backend.lambertw(n) # [-1, -0.654, -0.560, -0.259, 0, 0.108, 0.132, 1, 1.327, 2.718, 3.386]\n ```\n\n This method can be used with TensorFlow tensors:\n ```python\n t = tf.constant([-1.0/math.e, -0.34, -0.32, -0.2, 0, 0.12, 0.15, math.e, 5, math.exp(1 + math.e), 100])\n b = fe.backend.lambertw(t) # [-1, -0.654, -0.560, -0.259, 0, 0.108, 0.132, 1, 1.327, 2.718, 3.386]\n ```\n\n This method can be used with PyTorch tensors:\n ```python\n p = torch.tensor([-1.0/math.e, -0.34, -0.32, -0.2, 0, 0.12, 0.15, math.e, 5, math.exp(1 + math.e), 100])\n b = fe.backend.lambertw(p) # [-1, -0.654, -0.560, -0.259, 0, 0.108, 0.132, 1, 1.327, 2.718, 3.386]\n ```\n\n Args:\n tensor: The input value.\n\n Returns:\n The lambertw function evaluated at `tensor`.\n\n Raises:\n ValueError: If `tensor` is an unacceptable data type.\n \"\"\"\n if tf.is_tensor(tensor):\n return tfp.math.lambertw(tensor)\n if isinstance(tensor, torch.Tensor):\n return _torch_lambertw(tensor)\n elif isinstance(tensor, np.ndarray):\n # scipy implementation is numerically unstable at exactly -1/e, but the result should be -1.0\n return np.nan_to_num(lamw(tensor, k=0, tol=1e-6).real.astype(tensor.dtype), nan=-1.0)\n else:\n raise ValueError(\"Unrecognized tensor type {}\".format(type(tensor)))\n\n\ndef _torch_lambertw(z: torch.Tensor) -> torch.Tensor:\n \"\"\"Approximate the LambertW function value using Halley iteration.\n\n Args:\n z: The inputs to the LambertW function.\n\n Returns:\n An approximation of W(z).\n \"\"\"\n # Make some starting guesses in order to converge faster.\n z0 = torch.where(z < -0.2649, _taylor_approx(z), _lambertw_winitzki_approx(z))\n tolerance = 1e-6\n # Perform at most 20 halley iteration refinements of the value (usually finishes in 2)\n for _ in range(20):\n f = z0 - z * torch.exp(-z0)\n z01 = z0 + 1.0000001 # Numerical stability when z0 == -1\n delta = f / (z01 - (z0 + 2.) * f / (2. * z01))\n z0 = z0 - delta\n converged = torch.abs(delta) <= tolerance * torch.abs(z0)\n if torch.all(converged):\n break\n return z0\n\n\ndef _taylor_approx(z: torch.Tensor) -> torch.Tensor:\n \"\"\"Compute an approximation of the lambertw function at z.\n\n Based on the polynomial expansion in https://arxiv.org/pdf/1003.1628.pdf. An empirical comparison of this polynomial\n expansion against the winitzki approximation found that this one is better when z < -0.2649.\n\n Args:\n z: The input to the lambertw function.\n\n Returns:\n An estimated value of lambertw(z).\n \"\"\"\n p2 = 2 * (1. + math.e * z)\n p = torch.sqrt(p2)\n return -1. + p - p2 / 3. + 0.1527777777 * p2 * p\n\n\ndef _lambertw_winitzki_approx(z: torch.Tensor) -> torch.Tensor:\n \"\"\"Compute an approximation of the lambertw function at z.\n\n Args:\n z: The input to the lambertw function.\n\n Returns:\n An estimated value of lambertw(z).\n \"\"\"\n log1pz = torch.log1p(z)\n return log1pz * (1. - torch.log1p(log1pz) / (2. + log1pz))\n", "# Copyright 2019 The FastEstimator 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 contextlib\nimport functools\nimport locale\nimport os\nimport platform\nimport re\nimport shutil\nimport sys\nimport types\nfrom collections import defaultdict\nfrom typing import Any, Dict, List, Set, Tuple, Union, Optional\nfrom unittest.mock import Base, MagicMock\n\nimport dot2tex as d2t\nimport jsonpickle\nimport matplotlib\nimport numpy as np\nimport pydot\nimport pytorch_model_summary as pms\nimport tensorflow as tf\nimport torch\nfrom natsort import humansorted\nfrom pylatex import Command, Document, Figure, Hyperref, Itemize, Label, LongTable, Marker, MultiColumn, NoEscape, \\\n Package, Section, Subsection, Subsubsection, Tabularx, escape_latex\nfrom pylatex.base_classes import Arguments\nfrom pylatex.section import Paragraph\nfrom pylatex.utils import bold\nfrom torch.utils.data import Dataset\n\nimport fastestimator as fe\nfrom fastestimator.dataset.dataset import FEDataset\nfrom fastestimator.network import BaseNetwork\nfrom fastestimator.op.numpyop.numpyop import Batch\nfrom fastestimator.op.numpyop.meta.fuse import Fuse\nfrom fastestimator.op.numpyop.meta.one_of import OneOf\nfrom fastestimator.op.numpyop.meta.repeat import Repeat\nfrom fastestimator.op.numpyop.meta.sometimes import Sometimes\nfrom fastestimator.op.op import Op\nfrom fastestimator.op.tensorop.meta.fuse import Fuse as FuseT\nfrom fastestimator.op.tensorop.meta.one_of import OneOf as OneOfT\nfrom fastestimator.op.tensorop.meta.repeat import Repeat as RepeatT\nfrom fastestimator.op.tensorop.meta.sometimes import Sometimes as SometimesT\nfrom fastestimator.op.tensorop.model import ModelOp\nfrom fastestimator.pipeline import Pipeline\nfrom fastestimator.schedule.schedule import Scheduler, get_current_items, get_signature_epochs\nfrom fastestimator.summary.logs.log_plot import visualize_logs\nfrom fastestimator.trace.io.restore_wizard import RestoreWizard\nfrom fastestimator.trace.trace import Trace, sort_traces\nfrom fastestimator.util.data import Data\nfrom fastestimator.util.latex_util import AdjustBox, Center, ContainerList, HrefFEID, Verbatim\nfrom fastestimator.util.traceability_util import FeSummaryTable, traceable\nfrom fastestimator.util.base_util import to_list, NonContext, Suppressor, LogSplicer, prettify_metric_name, \\\n DefaultKeyDict, FEID\n\n\n@traceable()\nclass Traceability(Trace):\n \"\"\"Automatically generate summary reports of the training.\n\n Args:\n save_path: Where to save the output files. Note that this will generate a new folder with the given name, into\n which the report and corresponding graphics assets will be written.\n extra_objects: Any extra objects which are not part of the Estimator, but which you want to capture in the\n summary report. One example could be an extra pipeline which performs pre-processing.\n\n Raises:\n OSError: If graphviz is not installed.\n \"\"\"\n def __init__(self, save_path: str, extra_objects: Any = None):\n # Verify that graphviz is available on this machine\n try:\n pydot.Dot.create(pydot.Dot())\n except OSError:\n raise OSError(\n \"Traceability requires that graphviz be installed. See www.graphviz.org/download for more information.\")\n # Verify that the system locale is functioning correctly\n try:\n locale.getlocale()\n except ValueError:\n raise OSError(\"Your system locale is not configured correctly. On mac this can be resolved by adding \\\n 'export LC_ALL=en_US.UTF-8' and 'export LANG=en_US.UTF-8' to your ~/.bash_profile\")\n super().__init__(inputs=\"*\", mode=\"!infer\") # Claim wildcard inputs to get this trace sorted last\n # Report assets will get saved into a folder for portability\n path = os.path.normpath(save_path)\n path = os.path.abspath(path)\n root_dir = os.path.dirname(path)\n report = os.path.basename(path) or 'report'\n report = report.split('.')[0]\n self.save_dir = os.path.join(root_dir, report)\n self.resource_dir = os.path.join(self.save_dir, 'resources')\n self.report_name = None # This will be set later by the experiment name\n os.makedirs(self.save_dir, exist_ok=True)\n os.makedirs(self.resource_dir, exist_ok=True)\n # Other member variables\n self.config_tables = []\n # Extra objects will automatically get included in the report since this Trace is @traceable, so we don't need\n # to do anything with them. Referencing here to stop IDEs from flagging the argument as unused and removing it.\n to_list(extra_objects)\n self.doc = Document()\n self.log_splicer = None\n\n def on_begin(self, data: Data) -> None:\n exp_name = self.system.summary.name\n if not exp_name:\n raise RuntimeError(\"Traceability reports require an experiment name to be provided in estimator.fit()\")\n # Convert the experiment name to a report name (useful for saving multiple experiments into same directory)\n report_name = \"\".join('_' if c == ' ' else c for c in exp_name\n if c.isalnum() or c in (' ', '_')).rstrip().lower()\n report_name = re.sub('_{2,}', '_', report_name)\n self.report_name = report_name or 'report'\n # Send experiment logs into a file\n log_path = os.path.join(self.resource_dir, f\"{report_name}.txt\")\n if self.system.mode != 'test':\n # See if there's a RestoreWizard\n restore = False\n for trace in self.system.traces:\n if isinstance(trace, RestoreWizard):\n restore = trace.should_restore()\n if not restore:\n # If not running in test mode, we need to remove any old log file since it would get appended to\n with contextlib.suppress(FileNotFoundError):\n os.remove(log_path)\n self.log_splicer = LogSplicer(log_path)\n self.log_splicer.__enter__()\n # Get the initialization summary information for the experiment\n self.config_tables = self.system.summary.system_config\n models = self.system.network.models\n n_floats = len(self.config_tables) + len(models)\n\n self.doc = self._init_document_geometry()\n # Keep tables/figures in their sections\n self.doc.packages.append(Package(name='placeins', options=['section']))\n self.doc.preamble.append(NoEscape(r'\\usetikzlibrary{positioning}'))\n\n # Fix an issue with too many tables for LaTeX to render\n self.doc.preamble.append(NoEscape(r'\\maxdeadcycles=' + str(2 * n_floats + 10) + ''))\n self.doc.preamble.append(NoEscape(r'\\extrafloats{' + str(n_floats + 10) + '}'))\n\n # Manipulate booktab tables so that their horizontal lines don't break\n self.doc.preamble.append(NoEscape(r'\\aboverulesep=0ex'))\n self.doc.preamble.append(NoEscape(r'\\belowrulesep=0ex'))\n self.doc.preamble.append(NoEscape(r'\\renewcommand{\\arraystretch}{1.2}'))\n\n self._write_title()\n self._write_toc()\n\n def on_end(self, data: Data) -> None:\n self._write_body_content()\n\n # Need to move the tikz dependency after the xcolor package\n self.doc.dumps_packages()\n packages = self.doc.packages\n tikz = Package(name='tikz')\n packages.discard(tikz)\n packages.add(tikz)\n\n if shutil.which(\"latexmk\") is None and shutil.which(\"pdflatex\") is None:\n # No LaTeX Compiler is available\n self.doc.generate_tex(os.path.join(self.save_dir, self.report_name))\n suffix = '.tex'\n else:\n # Force a double-compile since some compilers will struggle with TOC generation\n self.doc.generate_pdf(os.path.join(self.save_dir, self.report_name), clean_tex=False, clean=False)\n self.doc.generate_pdf(os.path.join(self.save_dir, self.report_name), clean_tex=False)\n suffix = '.pdf'\n print(\"FastEstimator-Traceability: Report written to {}{}\".format(os.path.join(self.save_dir, self.report_name),\n suffix))\n self.log_splicer.__exit__()\n\n def _write_title(self) -> None:\n \"\"\"Write the title content of the file. Override if you want to build on top of base traceability report.\n \"\"\"\n self.doc.preamble.append(Command('title', self.system.summary.name))\n self.doc.preamble.append(Command('author', f\"FastEstimator {fe.__version__}\"))\n self.doc.preamble.append(Command('date', NoEscape(r'\\today')))\n self.doc.append(NoEscape(r'\\maketitle'))\n\n def _write_toc(self) -> None:\n \"\"\"Write the table of contents. Override if you want to build on top of base traceability report.\n \"\"\"\n self.doc.append(NoEscape(r'\\tableofcontents'))\n self.doc.append(NoEscape(r'\\newpage'))\n\n def _write_body_content(self) -> None:\n \"\"\"Write the main content of the file. Override if you want to build on top of base traceability report.\n \"\"\"\n self._document_training_graphs()\n self.doc.append(NoEscape(r'\\newpage'))\n self._document_fe_graph()\n self.doc.append(NoEscape(r'\\newpage'))\n self._document_init_params()\n self._document_models()\n self._document_sys_config()\n self.doc.append(NoEscape(r'\\newpage'))\n\n def _document_training_graphs(self) -> None:\n \"\"\"Add training graphs to the traceability document.\n \"\"\"\n with self.doc.create(Section(\"Training Graphs\")):\n log_path = os.path.join(self.resource_dir, f'{self.report_name}_logs.png')\n visualize_logs(experiments=[self.system.summary],\n save_path=log_path,\n verbose=False,\n ignore_metrics={'num_device', 'logging_interval'})\n with self.doc.create(Figure(position='h!')) as plot:\n plot.add_image(os.path.relpath(log_path, start=self.save_dir),\n width=NoEscape(r'1.0\\textwidth,height=0.95\\textheight,keepaspectratio'))\n for idx, graph in enumerate(self.system.custom_graphs.values()):\n graph_path = os.path.join(self.resource_dir, f'{self.report_name}_custom_graph_{idx}.png')\n visualize_logs(experiments=graph, save_path=graph_path, verbose=False)\n with self.doc.create(Figure(position='h!')) as plot:\n plot.add_image(os.path.relpath(graph_path, start=self.save_dir),\n width=NoEscape(r'1.0\\textwidth,height=0.95\\textheight,keepaspectratio'))\n\n def _document_fe_graph(self) -> None:\n \"\"\"Add FE execution graphs into the traceability document.\n \"\"\"\n with self.doc.create(Section(\"FastEstimator Architecture\")):\n for mode in self.system.pipeline.data.keys():\n scheduled_items = self.system.pipeline.get_scheduled_items(\n mode) + self.system.network.get_scheduled_items(mode) + self.system.traces\n signature_epochs = get_signature_epochs(scheduled_items, total_epochs=self.system.epoch_idx, mode=mode)\n epochs_with_data = self.system.pipeline.get_epochs_with_data(total_epochs=self.system.epoch_idx,\n mode=mode)\n if set(signature_epochs) & epochs_with_data:\n self.doc.append(NoEscape(r'\\FloatBarrier'))\n with self.doc.create(Subsection(mode.capitalize())):\n for epoch in signature_epochs:\n if epoch not in epochs_with_data:\n continue\n self.doc.append(NoEscape(r'\\FloatBarrier'))\n with self.doc.create(\n Subsubsection(f\"Epoch {epoch}\",\n label=Label(Marker(name=f\"{mode}{epoch}\", prefix=\"ssubsec\")))):\n ds_ids = self.system.pipeline.get_ds_ids(epoch=epoch, mode=mode)\n for ds_id in ds_ids:\n with NonContext() if ds_id == '' else self.doc.create(\n Paragraph(f\"Dataset {ds_id}\",\n label=Label(Marker(name=f\"{mode}{epoch}{ds_id}\",\n prefix=\"para\")))):\n diagram = self._draw_diagram(mode, epoch, ds_id)\n ltx = d2t.dot2tex(diagram.to_string(), figonly=True)\n args = Arguments(**{'max width': r'\\textwidth, max height=0.9\\textheight'})\n args.escape = False\n with self.doc.create(Center()):\n with self.doc.create(AdjustBox(arguments=args)) as box:\n box.append(NoEscape(ltx))\n\n def _document_init_params(self) -> None:\n \"\"\"Add initialization parameters to the traceability document.\n \"\"\"\n from fastestimator.estimator import Estimator # Avoid circular import\n with self.doc.create(Section(\"Parameters\")):\n model_ids = {\n FEID(id(model))\n for model in self.system.network.models if isinstance(model, (tf.keras.Model, torch.nn.Module))\n }\n # Locate the datasets in order to provide extra details about them later in the summary\n datasets = {}\n for mode in ['train', 'eval', 'test']:\n objs = to_list(self.system.pipeline.data.get(mode, None))\n idx = 0\n while idx < len(objs):\n obj = objs[idx]\n if obj:\n feid = FEID(id(obj))\n if feid not in datasets:\n datasets[feid] = ({mode}, obj)\n else:\n datasets[feid][0].add(mode)\n if isinstance(obj, Scheduler):\n objs.extend(obj.get_all_values())\n idx += 1\n # Parse the config tables\n start = 0\n start = self._loop_tables(start,\n classes=(Estimator, BaseNetwork, Pipeline),\n name=\"Base Classes\",\n model_ids=model_ids,\n datasets=datasets)\n start = self._loop_tables(start,\n classes=Scheduler,\n name=\"Schedulers\",\n model_ids=model_ids,\n datasets=datasets)\n start = self._loop_tables(start, classes=Trace, name=\"Traces\", model_ids=model_ids, datasets=datasets)\n start = self._loop_tables(start, classes=Op, name=\"Operators\", model_ids=model_ids, datasets=datasets)\n start = self._loop_tables(start,\n classes=(Dataset, tf.data.Dataset),\n name=\"Datasets\",\n model_ids=model_ids,\n datasets=datasets)\n start = self._loop_tables(start,\n classes=(tf.keras.Model, torch.nn.Module),\n name=\"Models\",\n model_ids=model_ids,\n datasets=datasets)\n start = self._loop_tables(start,\n classes=types.FunctionType,\n name=\"Functions\",\n model_ids=model_ids,\n datasets=datasets)\n start = self._loop_tables(start,\n classes=(np.ndarray, tf.Tensor, tf.Variable, torch.Tensor),\n name=\"Tensors\",\n model_ids=model_ids,\n datasets=datasets)\n self._loop_tables(start, classes=Any, name=\"Miscellaneous\", model_ids=model_ids, datasets=datasets)\n\n def _loop_tables(self,\n start: int,\n classes: Union[type, Tuple[type, ...]],\n name: str,\n model_ids: Set[FEID],\n datasets: Dict[FEID, Tuple[Set[str], Any]]) -> int:\n \"\"\"Iterate through tables grouping them into subsections.\n\n Args:\n start: What index to start searching from.\n classes: What classes are acceptable for this subsection.\n name: What to call this subsection.\n model_ids: The ids of any known models.\n datasets: A mapping like {ID: ({modes}, dataset)}. Useful for augmenting the displayed information.\n\n Returns:\n The new start index after traversing as many spaces as possible along the list of tables.\n \"\"\"\n stop = start\n while stop < len(self.config_tables):\n if classes == Any or issubclass(self.config_tables[stop].type, classes):\n stop += 1\n else:\n break\n if stop > start:\n self.doc.append(NoEscape(r'\\FloatBarrier'))\n with self.doc.create(Subsection(name)):\n self._write_tables(self.config_tables[start:stop], model_ids, datasets)\n return stop\n\n def _write_tables(self,\n tables: List[FeSummaryTable],\n model_ids: Set[FEID],\n datasets: Dict[FEID, Tuple[Set[str], Any]]) -> None:\n \"\"\"Insert a LaTeX representation of a list of tables into the current doc.\n\n Args:\n tables: The tables to write into the doc.\n model_ids: The ids of any known models.\n datasets: A mapping like {ID: ({modes}, dataset)}. Useful for augmenting the displayed information.\n \"\"\"\n for tbl in tables:\n name_override = None\n toc_ref = None\n extra_rows = None\n if tbl.fe_id in model_ids:\n # Link to a later detailed model description\n name_override = Hyperref(Marker(name=str(tbl.name), prefix=\"subsec\"),\n text=NoEscape(r'\\textcolor{blue}{') + bold(tbl.name) + NoEscape('}'))\n if tbl.fe_id in datasets:\n modes, dataset = datasets[tbl.fe_id]\n title = \", \".join([s.capitalize() for s in modes])\n name_override = bold(f'{tbl.name} ({title})')\n # Enhance the dataset summary\n if isinstance(dataset, FEDataset):\n extra_rows = list(dataset.summary().__getstate__().items())\n for idx, (key, val) in enumerate(extra_rows):\n key = f\"{prettify_metric_name(key)}:\"\n if isinstance(val, dict) and val:\n if isinstance(list(val.values())[0], (int, float, str, bool, type(None))):\n val = jsonpickle.dumps(val, unpicklable=False)\n else:\n subtable = Tabularx('l|X', width_argument=NoEscape(r'\\linewidth'))\n for k, v in val.items():\n if hasattr(v, '__getstate__'):\n v = jsonpickle.dumps(v, unpicklable=False)\n subtable.add_row((k, v))\n # To nest TabularX, have to wrap it in brackets\n subtable = ContainerList(data=[NoEscape(\"{\"), subtable, NoEscape(\"}\")])\n val = subtable\n extra_rows[idx] = (key, val)\n tbl.render_table(self.doc, name_override=name_override, toc_ref=toc_ref, extra_rows=extra_rows)\n\n def _document_models(self) -> None:\n \"\"\"Add model summaries to the traceability document.\n \"\"\"\n with self.doc.create(Section(\"Models\")):\n for model in humansorted(self.system.network.models, key=lambda m: m.model_name):\n if not isinstance(model, (tf.keras.Model, torch.nn.Module)):\n continue\n self.doc.append(NoEscape(r'\\FloatBarrier'))\n with self.doc.create(Subsection(f\"{model.model_name.capitalize()}\")):\n if isinstance(model, tf.keras.Model):\n # Text Summary\n summary = []\n model.summary(line_length=92, print_fn=lambda x: summary.append(x))\n summary = \"\\n\".join(summary)\n self.doc.append(Verbatim(summary))\n with self.doc.create(Center()):\n self.doc.append(HrefFEID(FEID(id(model)), model.model_name))\n\n # Visual Summary\n # noinspection PyBroadException\n try:\n file_path = os.path.join(self.resource_dir,\n \"{}_{}.pdf\".format(self.report_name, model.model_name))\n dot = tf.keras.utils.model_to_dot(model, show_shapes=True, expand_nested=True)\n # LaTeX \\maxdim is around 575cm (226 inches), so the image must have max dimension less than\n # 226 inches. However, the 'size' parameter doesn't account for the whole node height, so\n # set the limit lower (100 inches) to leave some wiggle room.\n dot.set('size', '100')\n dot.write(file_path, format='pdf')\n except Exception:\n file_path = None\n print(\n f\"FastEstimator-Warn: Model {model.model_name} could not be visualized by Traceability\")\n elif isinstance(model, torch.nn.Module):\n if hasattr(model, 'fe_input_spec'):\n # Text Summary\n # noinspection PyUnresolvedReferences\n inputs = model.fe_input_spec.get_dummy_input()\n self.doc.append(\n Verbatim(\n pms.summary(model.module if self.system.num_devices > 1 else model,\n inputs,\n print_summary=False)))\n with self.doc.create(Center()):\n self.doc.append(HrefFEID(FEID(id(model)), model.model_name))\n # Visual Summary\n # Import has to be done while matplotlib is using the Agg backend\n old_backend = matplotlib.get_backend() or 'Agg'\n matplotlib.use('Agg')\n # noinspection PyBroadException\n try:\n # Fake the IPython import when user isn't running from Jupyter\n sys.modules.setdefault('IPython', MagicMock())\n sys.modules.setdefault('IPython.display', MagicMock())\n import hiddenlayer as hl\n with Suppressor():\n graph = hl.build_graph(model.module if self.system.num_devices > 1 else model,\n inputs)\n graph = graph.build_dot()\n graph.attr(rankdir='TB') # Switch it to Top-to-Bottom instead of Left-to-Right\n # LaTeX \\maxdim is around 575cm (226 inches), so the image must have max dimension less\n # than 226 inches. However, the 'size' parameter doesn't account for the whole node\n # height, so set the limit lower (100 inches) to leave some wiggle room.\n graph.attr(size=\"100,100\")\n graph.attr(margin='0')\n file_path = graph.render(filename=\"{}_{}\".format(self.report_name, model.model_name),\n directory=self.resource_dir,\n format='pdf',\n cleanup=True)\n except Exception:\n file_path = None\n print(\"FastEstimator-Warn: Model {} could not be visualized by Traceability\".format(\n model.model_name))\n finally:\n matplotlib.use(old_backend)\n else:\n file_path = None\n self.doc.append(\"This model was not used by the Network during training.\")\n if file_path:\n with self.doc.create(Figure(position='ht!')) as fig:\n fig.append(Label(Marker(name=str(FEID(id(model))), prefix=\"model\")))\n fig.add_image(os.path.relpath(file_path, start=self.save_dir),\n width=NoEscape(r'1.0\\textwidth,height=0.95\\textheight,keepaspectratio'))\n fig.add_caption(NoEscape(HrefFEID(FEID(id(model)), model.model_name).dumps()))\n\n def _document_sys_config(self) -> None:\n \"\"\"Add a system config summary to the traceability document.\n \"\"\"\n with self.doc.create(Section(\"System Configuration\")):\n with self.doc.create(Itemize()) as itemize:\n itemize.add_item(escape_latex(f\"FastEstimator {fe.__version__}\"))\n itemize.add_item(escape_latex(f\"Python {platform.python_version()}\"))\n itemize.add_item(escape_latex(f\"OS: {sys.platform}\"))\n itemize.add_item(f\"Number of GPUs: {torch.cuda.device_count()}\")\n if fe.fe_deterministic_seed is not None:\n itemize.add_item(escape_latex(f\"Deterministic Seed: {fe.fe_deterministic_seed}\"))\n with self.doc.create(LongTable('|lr|', pos=['h!'], booktabs=True)) as tabular:\n tabular.add_row((bold(\"Module\"), bold(\"Version\")))\n tabular.add_hline()\n tabular.end_table_header()\n tabular.add_hline()\n tabular.add_row((MultiColumn(2, align='r', data='Continued on Next Page'), ))\n tabular.add_hline()\n tabular.end_table_footer()\n tabular.end_table_last_footer()\n color = True\n for name, module in humansorted(sys.modules.items(), key=lambda x: x[0]):\n if \".\" in name:\n continue # Skip sub-packages\n if name.startswith(\"_\"):\n continue # Skip private packages\n if isinstance(module, Base):\n continue # Skip fake packages we mocked\n if hasattr(module, '__version__'):\n tabular.add_row((escape_latex(name), escape_latex(str(module.__version__))),\n color='black!5' if color else 'white')\n color = not color\n elif hasattr(module, 'VERSION'):\n tabular.add_row((escape_latex(name), escape_latex(str(module.VERSION))),\n color='black!5' if color else 'white')\n color = not color\n\n def _draw_diagram(self, mode: str, epoch: int, ds_id: str) -> pydot.Dot:\n \"\"\"Draw a summary diagram of the FastEstimator Ops / Traces.\n\n Args:\n mode: The execution mode to summarize ('train', 'eval', 'test', or 'infer').\n epoch: The epoch to summarize.\n ds_id: The ds_id to summarize.\n\n Returns:\n A pydot digraph representing the execution flow.\n \"\"\"\n ds = self.system.pipeline.data[mode][ds_id]\n if isinstance(ds, Scheduler):\n ds = ds.get_current_value(epoch)\n pipe_ops = get_current_items(self.system.pipeline.ops, run_modes=mode, epoch=epoch, ds_id=ds_id) if isinstance(\n ds, Dataset) else []\n net_ops = get_current_items(self.system.network.ops, run_modes=mode, epoch=epoch, ds_id=ds_id)\n net_post = get_current_items(self.system.network.postprocessing, run_modes=mode, epoch=epoch, ds_id=ds_id)\n traces = sort_traces(get_current_items(self.system.traces, run_modes=mode, epoch=epoch, ds_id=ds_id),\n ds_ids=self.system.pipeline.get_ds_ids(epoch=epoch, mode=mode))\n diagram = pydot.Dot(compound='true') # Compound lets you draw edges which terminate at sub-graphs\n diagram.set('rankdir', 'TB')\n diagram.set('dpi', 300)\n diagram.set_node_defaults(shape='box')\n\n # Make the dataset the first of the pipeline ops\n pipe_ops.insert(0, ds)\n label_last_seen = DefaultKeyDict(lambda k: str(id(ds))) # Where was this key last generated\n\n batch_size = \"\"\n if isinstance(ds, Dataset):\n if hasattr(ds, \"fe_batch\") and ds.fe_batch:\n batch_size = ds.fe_batch\n else:\n batch_size = self.system.pipeline.batch_size\n if isinstance(batch_size, Scheduler):\n batch_size = batch_size.get_current_value(epoch)\n if isinstance(batch_size, dict):\n batch_size = batch_size[mode]\n if batch_size is not None:\n batch_size = f\" (Batch Size: {batch_size})\"\n self._draw_subgraph(diagram, diagram, label_last_seen, f'Pipeline{batch_size}', pipe_ops, ds_id)\n self._draw_subgraph(diagram, diagram, label_last_seen, 'Network', net_ops + net_post, ds_id)\n self._draw_subgraph(diagram, diagram, label_last_seen, 'Traces', traces, ds_id)\n return diagram\n\n def _draw_subgraph(self,\n progenitor: pydot.Dot,\n diagram: Union[pydot.Dot, pydot.Cluster],\n label_last_seen: DefaultKeyDict[str, str],\n subgraph_name: str,\n subgraph_ops: List[Union[Op, Trace, Any]],\n ds_id: Optional[str]) -> None:\n \"\"\"Draw a subgraph of ops into an existing `diagram`.\n\n Args:\n progenitor: The very top level diagram onto which Edges should be written.\n diagram: The diagram into which to add new Nodes.\n label_last_seen: A mapping of {data_dict_key: node_id} indicating the last node which generated the key.\n subgraph_name: The name to be associated with this subgraph.\n subgraph_ops: The ops to be wrapped in this subgraph.\n ds_id: The ds_id to be associated with this subgraph.\n \"\"\"\n subgraph = pydot.Cluster(style='dashed', graph_name=subgraph_name, color='black')\n subgraph.set('label', subgraph_name)\n subgraph.set('labeljust', 'l')\n for idx, op in enumerate(subgraph_ops):\n node_id = str(id(op))\n self._add_node(progenitor, subgraph, op, label_last_seen, ds_id)\n if isinstance(op, Trace) and idx > 0:\n # Invisibly connect traces in order so that they aren't all just squashed horizontally into the image\n progenitor.add_edge(pydot.Edge(src=str(id(subgraph_ops[idx - 1])), dst=node_id, style='invis'))\n diagram.add_subgraph(subgraph)\n\n def _add_node(self,\n progenitor: pydot.Dot,\n diagram: Union[pydot.Dot, pydot.Cluster],\n op: Union[Op, Trace, Any],\n label_last_seen: DefaultKeyDict[str, str],\n ds_id: Optional[str],\n edges: bool = True) -> None:\n \"\"\"Draw a node onto a diagram based on a given op.\n\n Args:\n progenitor: The very top level diagram onto which Edges should be written.\n diagram: The diagram to be appended to.\n op: The op (or trace) to be visualized.\n label_last_seen: A mapping of {data_dict_key: node_id} indicating the last node which generated the key.\n ds_id: The ds_id under which the node is currently running.\n edges: Whether to write Edges to/from this Node.\n \"\"\"\n node_id = str(id(op))\n if isinstance(op, (Sometimes, SometimesT)) and op.op:\n wrapper = pydot.Cluster(style='dotted', color='red', graph_name=str(id(op)))\n wrapper.set('label', f'Sometimes ({op.prob}):')\n wrapper.set('labeljust', 'l')\n edge_srcs = defaultdict(lambda: [])\n if op.extra_inputs:\n for inp in op.extra_inputs:\n if inp == '*':\n continue\n edge_srcs[label_last_seen[inp]].append(inp)\n self._add_node(progenitor, wrapper, op.op, label_last_seen, ds_id)\n diagram.add_subgraph(wrapper)\n dst_id = self._get_all_nodes(wrapper)[0].get_name()\n for src, labels in edge_srcs.items():\n progenitor.add_edge(\n pydot.Edge(src=src, dst=dst_id, lhead=wrapper.get_name(), label=f\" {', '.join(labels)} \"))\n elif isinstance(op, (OneOf, OneOfT)) and op.ops:\n wrapper = pydot.Cluster(style='dotted', color='darkorchid4', graph_name=str(id(op)))\n wrapper.set('label', 'One Of:')\n wrapper.set('labeljust', 'l')\n self._add_node(progenitor, wrapper, op.ops[0], label_last_seen, ds_id, edges=True)\n for sub_op in op.ops[1:]:\n self._add_node(progenitor, wrapper, sub_op, label_last_seen, ds_id, edges=False)\n diagram.add_subgraph(wrapper)\n elif isinstance(op, (Fuse, FuseT)) and op.ops:\n self._draw_subgraph(progenitor, diagram, label_last_seen, 'Fuse:', op.ops, ds_id)\n elif isinstance(op, (Repeat, RepeatT)) and op.op:\n wrapper = pydot.Cluster(style='dotted', color='darkgreen', graph_name=str(id(op)))\n wrapper.set('label', f'Repeat:')\n wrapper.set('labeljust', 'l')\n wrapper.add_node(\n pydot.Node(node_id,\n label=f'{op.repeat if isinstance(op.repeat, int) else \"?\"}',\n shape='doublecircle',\n width=0.1))\n # dot2tex doesn't seem to handle edge color conversion correctly, so have to set hex color\n progenitor.add_edge(pydot.Edge(src=node_id + \":ne\", dst=node_id + \":w\", color='#006300'))\n self._add_node(progenitor, wrapper, op.op, label_last_seen, ds_id)\n # Add repeat edges\n edge_srcs = defaultdict(lambda: [])\n for out in op.outputs:\n if out in op.inputs and out not in op.repeat_inputs:\n edge_srcs[label_last_seen[out]].append(out)\n for inp in op.repeat_inputs:\n edge_srcs[label_last_seen[inp]].append(inp)\n for src, labels in edge_srcs.items():\n progenitor.add_edge(pydot.Edge(src=src, dst=node_id, constraint=False, label=f\" {', '.join(labels)} \"))\n diagram.add_subgraph(wrapper)\n else:\n if isinstance(op, ModelOp):\n label = f\"{op.__class__.__name__} ({FEID(id(op))}): {op.model.model_name}\"\n model_ref = Hyperref(Marker(name=str(op.model.model_name), prefix='subsec'),\n text=NoEscape(r'\\textcolor{blue}{') + bold(op.model.model_name) +\n NoEscape('}')).dumps()\n texlbl = f\"{HrefFEID(FEID(id(op)), name=op.__class__.__name__).dumps()}: {model_ref}\"\n elif isinstance(op, Batch):\n label = f\"{op.__class__.__name__} ({FEID(id(op))})\"\n texlbl = HrefFEID(FEID(id(op)), name=op.__class__.__name__, color='purple').dumps()\n if op.batch_size is not None:\n diagram.set_label(f\"Pipeline (Batch Size: {op.batch_size})\")\n label_last_seen.factory = functools.partial(self._delayed_edge,\n progenitor=progenitor,\n old_source=label_last_seen.factory(''),\n new_source=str(id(op)))\n else:\n label = f\"{op.__class__.__name__} ({FEID(id(op))})\"\n texlbl = HrefFEID(FEID(id(op)), name=op.__class__.__name__).dumps()\n diagram.add_node(pydot.Node(node_id, label=label, texlbl=texlbl))\n if isinstance(op, (Op, Trace)) and edges:\n # Need the instance check since subgraph_ops might contain a tf dataset or torch data loader\n self._add_edge(progenitor, op, label_last_seen, ds_id)\n\n @staticmethod\n def _delayed_edge(key: str, progenitor: pydot.Dot, old_source: str, new_source: str) -> str:\n \"\"\"Draw a specific edge between two nodes, modifying the old label if applicable.\n\n Args:\n key: The key associated with the edge.\n progenitor: The parent cluster.\n old_source: The edge source.\n new_source: The edge sync.\n\n Returns:\n The `new_source`.\n \"\"\"\n edge = progenitor.get_edge(old_source, new_source)\n if edge:\n edge = edge[0]\n label = f\"{edge.get_label()}, {key}\"\n edge.set_label(label)\n else:\n progenitor.add_edge(pydot.Edge(src=old_source, dst=new_source, label=f\" {key}\"))\n return new_source\n\n def _add_edge(self,\n progenitor: pydot.Dot,\n op: Union[Trace, Op],\n label_last_seen: Dict[str, str],\n ds_id: Optional[str]):\n \"\"\"Draw edges into a given Node.\n\n Args:\n progenitor: The very top level diagram onto which Edges should be written.\n op: The op (or trace) to be visualized.\n label_last_seen: A mapping of {data_dict_key: node_id} indicating the last node which generated the key.\n ds_id: The ds_id under which the node is currently running.\n \"\"\"\n node_id = str(id(op))\n edge_srcs = defaultdict(lambda: [])\n global_ds_ids = {key for vals in self.system.pipeline.data.values() for key in vals.keys() if key is not None}\n for inp in label_last_seen.keys() if isinstance(op, Batch) else op.inputs:\n if inp == '*':\n continue\n _, candidate_id, *_ = f\"{inp}|\".split('|')\n if candidate_id in global_ds_ids and candidate_id != ds_id:\n continue # Skip inputs which will be provided in other ds_id plots\n edge_srcs[label_last_seen[inp]].append(inp)\n for src, labels in edge_srcs.items():\n progenitor.add_edge(pydot.Edge(src=src, dst=node_id, label=f\" {', '.join(labels)} \"))\n outputs = op.get_outputs(ds_ids=ds_id) if isinstance(op, Trace) else op.outputs\n for out in label_last_seen.keys() if isinstance(op, Batch) else outputs:\n label_last_seen[out] = node_id\n\n @staticmethod\n def _get_all_nodes(diagram: Union[pydot.Dot, pydot.Cluster]) -> List[pydot.Node]:\n \"\"\"Recursively search through a `diagram` looking for Nodes.\n\n Args:\n diagram: The diagram to be inspected.\n\n Returns:\n All of the Nodes available within this diagram and its child diagrams.\n \"\"\"\n nodes = diagram.get_nodes()\n for subgraph in diagram.get_subgraphs():\n nodes.extend(Traceability._get_all_nodes(subgraph))\n return nodes\n\n @staticmethod\n def _init_document_geometry() -> Document:\n \"\"\"Init geometry setting of the document.\n\n Return:\n Initialized Document object.\n \"\"\"\n return Document(geometry_options=['lmargin=2cm', 'rmargin=2cm', 'bmargin=2cm'])\n", "# Copyright 2020 The FastEstimator 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 unittest\n\nimport numpy as np\n\nfrom fastestimator.test.unittest_util import is_equal, sample_system_object\nfrom fastestimator.trace.metric import CalibrationError\nfrom fastestimator.util import Data\n\n\nclass TestCalibrationError(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.calibration_error = CalibrationError(true_key='y', pred_key='y_pred')\n cls.calibration_error.system = sample_system_object()\n\n def test_on_epoch_begin(self):\n self.calibration_error.on_epoch_begin(data=Data())\n with self.subTest('Check initial value of y_true'):\n self.assertEqual(self.calibration_error.y_true, [])\n with self.subTest('Check initial value of y_pred'):\n self.assertEqual(self.calibration_error.y_pred, [])\n\n def test_on_batch_end(self):\n self.calibration_error.y_true = []\n self.calibration_error.y_pred = []\n batch1 = {'y': np.array([0, 0, 1, 1]), 'y_pred': np.array([[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 1.0]])}\n self.calibration_error.on_batch_end(data=Data(batch1))\n with self.subTest('Check true values'):\n self.assertTrue(is_equal(self.calibration_error.y_true, list(batch1['y'])))\n with self.subTest('Check pred values'):\n self.assertTrue(is_equal(self.calibration_error.y_pred, list(batch1['y_pred'])))\n batch2 = {'y': np.array([1, 1, 0, 0]), 'y_pred': np.array([[0.0, 1.0], [0.0, 1.0], [1.0, 0.0], [1.0, 0.0]])}\n self.calibration_error.on_batch_end(data=Data(batch2))\n with self.subTest('Check true values (2 batches)'):\n self.assertTrue(is_equal(self.calibration_error.y_true, list(batch1['y']) + list(batch2['y'])))\n with self.subTest('Check pred values (2 batches)'):\n self.assertTrue(is_equal(self.calibration_error.y_pred, list(batch1['y_pred']) + list(batch2['y_pred'])))\n\n def test_on_epoch_end(self):\n self.calibration_error.y_true = [0] * 50 + [1] * 50\n self.calibration_error.y_pred = list(np.array([1.0, 0.0] * 50 + [0.0, 1.0] * 50).reshape(100, 2))\n data = Data()\n self.calibration_error.on_epoch_end(data=data)\n with self.subTest('Check if calibration error exists'):\n self.assertIn('calibration_error', data)\n with self.subTest('Check the value of calibration error'):\n self.assertEqual(0.0, data['calibration_error'])\n\n def test_perfect_calibration(self):\n self.calibration_error.y_true = [0] * 50 + [1] * 50\n self.calibration_error.y_pred = list(\n np.array([1.0, 0.0] * 25 + [0.5, 0.5] * 50 + [0.0, 1.0] * 25).reshape(100, 2))\n data = Data()\n self.calibration_error.on_epoch_end(data=data)\n self.assertEqual(0.0, data['calibration_error'])\n\n def test_imperfect_calibration(self):\n self.calibration_error.y_true = [0] * 50 + [1] * 50\n self.calibration_error.y_pred = list(np.array([1.0, 0.0] * 50 + [0.5, 0.5] * 50).reshape(100, 2))\n data = Data()\n self.calibration_error.on_epoch_end(data=data)\n self.assertEqual(0.3536, data['calibration_error'])\n", "# Copyright 2020 The FastEstimator 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 unittest\n\nimport numpy as np\n\nfrom fastestimator.op.numpyop.multivariate import Flip\n\n\nclass TestFlip(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.single_input = [np.random.rand(28, 28, 3)]\n cls.single_output_shape = (28, 28, 3)\n cls.input_image_and_mask = [np.random.rand(28, 28, 3), np.random.rand(28, 28, 3)]\n cls.image_and_mask_output_shape = (28, 28, 3)\n\n def test_input(self):\n flip = Flip(image_in='x')\n output = flip.forward(data=self.single_input, state={})\n with self.subTest('Check output type'):\n self.assertEqual(type(output), list)\n with self.subTest('Check output image shape'):\n self.assertEqual(output[0].shape, self.single_output_shape)\n\n def test_input_image_and_mask(self):\n flip = Flip(image_in='x', mask_in='x_mask')\n output = flip.forward(data=self.input_image_and_mask, state={})\n with self.subTest('Check output type'):\n self.assertEqual(type(output), list)\n with self.subTest('Check output image shape'):\n self.assertEqual(output[0].shape, self.image_and_mask_output_shape)\n with self.subTest('Check output mask shape'):\n self.assertEqual(output[1].shape, self.image_and_mask_output_shape)\n" ]
[ [ "numpy.random.randint" ], [ "numpy.round", "numpy.argmax", "sklearn.metrics.matthews_corrcoef" ], [ "tensorflow.is_tensor", "torch.cuda.is_available" ], [ "numpy.argmax" ], [ "torch.all", "torch.abs", "tensorflow.is_tensor", "scipy.special.lambertw", "torch.sqrt", "torch.exp", "torch.log1p" ], [ "tensorflow.keras.utils.model_to_dot", "matplotlib.use", "torch.cuda.device_count", "matplotlib.get_backend" ], [ "numpy.array" ], [ "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.3", "2.4", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "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": [ "2.3", "2.4", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yockgen/movidius
[ "cc32f1951a4d00d2250bb0d2b9000c5f2435b41a", "cc32f1951a4d00d2250bb0d2b9000c5f2435b41a", "cc32f1951a4d00d2250bb0d2b9000c5f2435b41a" ]
[ "ncappzoo/tensorflow/topcoder_andresduque/supporting/inferences.py", "ncappzoo/apps/security-cam/security-picam.py", "ncappzoo/apps/object-detector/object-detector.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n#~ The MIT License (MIT)\n#~ Copyright 2018 ©klo86min\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#~ The above copyright notice and this permission notice shall be included in \n#~ all copies or substantial portions of the Software.\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\nimport argparse\nimport csv\nimport cv2\nimport mvnc.mvncapi as mvnc\nimport numpy as np\nimport os.path\n\n# image settings\nIMAGE_DIM = 299\n\n###############################################################################\n#\n# Modified code from https://github.com/ashwinvijayakumar/ncappzoo/apps/\n# rapid-image-classifier/rapid-image-classifier.py\n# also under the MIT License\n#\n###############################################################################\n\n# ---- Step 1: Open the enumerated device and get a handle to it -------------\n\ndef open_ncs_device(verbose=False):\n if verbose:\n mvnc.SetGlobalOption(mvnc.GlobalOption.LOG_LEVEL, 2)\n # Look for enumerated NCS device(s); quit program if none found.\n devices = mvnc.EnumerateDevices()\n if len( devices ) == 0:\n print( 'No devices found' )\n quit()\n\n # Get a handle to the first enumerated device and open it\n device = mvnc.Device( devices[0] )\n device.OpenDevice()\n\n return device\n\n# ---- Step 2: Load a graph file onto the NCS device -------------------------\n\ndef load_graph( device, graph_file):\n\n # Read the graph file into a buffer\n with open( graph_file, mode='rb' ) as f:\n blob = f.read()\n\n # Load the graph buffer into the NCS\n graph = device.AllocateGraph( blob )\n\n return graph\n\n# ---- Step 5: Unload the graph and close the device -------------------------\n\ndef close_ncs_device( device, graph ):\n graph.DeallocateGraph()\n device.CloseDevice()\n\n##################### End of ncappzoo code ################################\n\nclass MovidiusImage(object):\n \"\"\"Image metadata and loader for Movidius NCS\n \n Args:\n name (str): image reference name as used in CSV files\n path (str): image path\n class_index (int): 1-based class label index\n \n Attributes:\n top_k (list): list of predicted (class_index, proba)\n inference_time (float): computation time in ms \n \"\"\"\n \n def __init__(self, name, path, class_index = None):\n self.name = name\n self.path = path\n self.class_index = class_index\n self.top_k = None\n self.inference_time = None\n \n def load_BGR(self, dim, dtype=np.float16):\n \"\"\"Return image data in BGR order\n \n Args:\n dim (tuple): image dimensions\n dtype (numpy.dtype): new type for the BGR blob\n \n Returns:\n numpy.ndarray: the transformed BGR blob\n \"\"\"\n mean = 128\n std = 1/128\n\n img = cv2.imread(self.path).astype(np.float32)\n dx,dy,dz= img.shape\n delta=float(abs(dy-dx))\n if dx > dy: #crop the x dimension\n img=img[int(0.5*delta):dx-int(0.5*delta),0:dy]\n else:\n img=img[0:dx,int(0.5*delta):dy-int(0.5*delta)]\n img = cv2.resize(img, (dim, dim))\n\n img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n\n for i in range(3):\n img[:,:,i] = (img[:,:,i] - mean) * std\n \n img = img.astype(dtype)\n return img\n \n def save_top_k(self, predictions, labels, k=5):\n \"\"\"Save the top_k predicted probabilities\n \n Args:\n predictions (numpy.ndarray): the probabilities for each class\n k (int): Number of top_k probas\n \"\"\"\n \n order_k = predictions.argsort()[::-1][:k]\n # class_index is 1-based\n self.top_k = [(labels[pos], np.float(predictions[pos])) \n for pos in order_k]\n\n \n def result_string(self):\n \"\"\" Return image results with the following fields:\n [name, top1, proba1, ... top5, proba5, time]\n \n Returns:\n str: formatted CSV string\n \"\"\"\n res = [ self.name, ]\n for k, prob in self.top_k:\n res += [k, prob]\n res += [self.inference_time]\n pattern = \"%s,\" + \"%d,%.9f,\" * len(self.top_k) + \"%.9f\"\n return pattern % tuple(res)\n \ndef init_images(data_dir, images_file):\n \"\"\"Parse image_file CSV and create one MovidiusImage per row.\n \n Args:\n data_dir (str): path of the folder containing images\n image_file (str): CSV file (one image path per row)\n \n Returns:\n list: list of MovidiusImage instances\n \"\"\"\n images_dir = {}\n images = []\n for file in sorted(os.listdir(data_dir)):\n if file.endswith(\".jpg\"):\n image = MovidiusImage(file, os.path.realpath(data_dir) + \"/\" + \"/\" + file, -1)\n images_dir[file] = image\n images.append(image)\n \n if os.path.isfile(images_file):\n images = []\n with open(images_file, 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n # skip header\n next(reader)\n for row_pos, row in enumerate(reader):\n name = row[0]\n truth = int(row[1])\n img = images_dir[name]\n img.class_index = truth\n images.append(img)\n return images\n \ndef write_inferences_csv(output_path, images):\n \"\"\" For each image, retrieve and write results.\n \n Args:\n output_path (str): path for the CSV output\n images (list): list of processed MovidiusImage instances\n \"\"\"\n with open(output_path, 'w') as output_file:\n for image in images:\n output_file.write(image.result_string() + '\\n')\n\ndef score_inferences(images, min_proba = 1e-15, mult = 100, n_classes=200, \n log_loss_max=15.0, time_limit=1000.0):\n \"\"\" Compute the logLoss and reference computation time\n \n Args:\n images (list): list of processed MovidiusImage instances\n min_proba (float): minimum probability to be used in logLoss\n mult (int): number of images used for the reference time\n n_classes (int): total number of classes\n log_loss_limit (float): minimum log_loss requirement\n time_limit (float): maximum time per image (in ms)\n \n Returns:\n tuple: LogLoss and reference_time float values\n \"\"\"\n min_proba = np.float(min_proba)\n max_proba = 1.0 - min_proba\n n_images = len(images)\n probas = np.zeros(n_images, dtype=np.float)\n image_time = 0.0\n top_1_accuracy = 0.0\n top_k_accuracy = 0.0\n for i, image in enumerate(images):\n class_probas = dict(image.top_k)\n if image.class_index == image.top_k[0][0]:\n top_1_accuracy += 1.0\n if image.class_index in class_probas:\n top_k_accuracy += 1.0\n probas[i] = class_probas[image.class_index]\n if probas[i] > 0:\n sum_probas = sum(class_probas.values())\n probas[i] /= sum_probas\n probas[i] = max(min_proba, min(max_proba, probas[i]))\n image_time += image.inference_time\n \n log_loss = np.mean(-np.log(probas))\n top_1_accuracy /= n_images\n top_k_accuracy /= n_images\n image_time /= n_images\n t = mult * image_time\n print(\"top_1_accuracy = %.9f\" % top_1_accuracy)\n print(\"top_k_accuracy = %.9f\" % top_k_accuracy )\n print(\"log_loss = %.9f\" % log_loss)\n print(\"image_time = %.9f\" % image_time)\n if image_time > time_limit or log_loss > log_loss_max:\n score = 0.0\n else:\n t_max = mult * time_limit\n score = 1e6 * (1.0 - log_loss * np.log(t) / (log_loss_max * np.log(t_max)))\n print(\"score = %.2f\" % score)\n return score\n \n\ndef main(args):\n parser = argparse.ArgumentParser(description='TopCoder Movidius MM')\n parser.add_argument(\n \"-images-dir\",\n dest=\"images_dir\",\n help=\"\"\"Folder containing images to classify\"\"\"\n )\n parser.add_argument(\n \"-output-file\",\n dest=\"output_file\",\n default=\"\",\n help=\"\"\"Output CSV file to save inference results\"\"\"\n )\n parser.add_argument(\n \"-graph-file\",\n dest=\"graph_file\",\n default=\"\",\n help=\"\"\"Movidius graph file path\"\"\"\n )\n parser.add_argument(\n \"-labels-map-file\",\n dest=\"labels_map_file\",\n default=\"\",\n help=\"\"\"Labels map file\"\"\"\n )\n parser.add_argument(\n \"-images-file\",\n dest=\"images_file\",\n default=\"\",\n help=\"\"\"CSV file containing list of images filenames to classify in images-dir folder, only filenames listed here will be processed\"\"\"\n )\n args = parser.parse_args()\n if not os.path.isdir(args.images_dir):\n print(\"data is not a directory: %s\" % args.images_dir)\n print(\"Please use the right path as argument, and/or change the Makefile MOVIDIUSDIR variable\")\n return 0\n \n print(\"IMAGE_DIM\", IMAGE_DIM)\n # start NCS\n device = open_ncs_device()\n graph = load_graph(device, args.graph_file)\n # prepare images\n images = init_images(args.images_dir, args.images_file)\n n_images = len(images)\n info_frequency = 100\n print(\"n_images = %d\" % n_images)\n \n # load labels map file\n labelsLines = [line.rstrip('\\n') for line in open(args.labels_map_file)]\n labels = {}\n for label in labelsLines:\n split = label.split(\":\")\n labels[int(split[0])] = int(split[1])\n \n # process images\n for i, image in enumerate(images):\n if (i+1) % info_frequency == 0:\n print(\"progess %d/%d ...\" % (i+1, n_images), flush=True)\n bgr_blob = image.load_BGR(IMAGE_DIM)\n graph.LoadTensor(bgr_blob, 'user object')\n output, userobj = graph.GetResult()\n #print(output)\n image.inference_time = np.sum(\n graph.GetGraphOption( mvnc.GraphOption.TIME_TAKEN ) )\n image.save_top_k(output, labels, 5)\n # stop NCS\n close_ncs_device(device, graph)\n # process results\n write_inferences_csv(args.output_file, images)\n if os.path.isfile(args.images_file):\n score_inferences(images)\n return 0\n\nif __name__ == '__main__':\n import sys\n sys.exit(main(sys.argv))\n", "#!/usr/bin/python3\n\n# ****************************************************************************\n# Copyright(c) 2017 Intel Corporation. \n# License: MIT See LICENSE file in root directory.\n# ****************************************************************************\n\n# DIY smart security camera PoC using Raspberry Pi Camera and \n# Intel® Movidius™ Neural Compute Stick (NCS)\n\nimport os\nimport sys\nimport numpy\nimport select\nimport ntpath\nimport argparse\nimport picamera\nimport picamera.array\n\nimport mvnc.mvncapi as mvnc\n\nfrom PIL import Image\nfrom time import localtime, strftime\nfrom utils import visualize_output\nfrom utils import deserialize_output\n\n# \"Class of interest\" - Display detections only if they match this class ID\nCLASS_PERSON = 15\n\n# Detection threshold: Minimum confidance to tag as valid detection\nCONFIDANCE_THRESHOLD = 0.60 # 60% confidant\n\n# Variable to store commandline arguments\nARGS = None\n\n# ---- Step 1: Open the enumerated device and get a handle to it -------------\n\ndef open_ncs_device():\n\n # Look for enumerated NCS device(s); quit program if none found.\n devices = mvnc.EnumerateDevices()\n if len( devices ) == 0:\n print( \"No devices found\" )\n quit()\n\n # Get a handle to the first enumerated device and open it\n device = mvnc.Device( devices[0] )\n device.OpenDevice()\n\n return device\n\n# ---- Step 2: Load a graph file onto the NCS device -------------------------\n\ndef load_graph( device ):\n\n # Read the graph file into a buffer\n with open( ARGS.graph, mode='rb' ) as f:\n blob = f.read()\n\n # Load the graph buffer into the NCS\n graph = device.AllocateGraph( blob )\n\n return graph\n\n# ---- Step 3: Pre-process the images ----------------------------------------\n\ndef pre_process_image( frame ):\n\n # Read & resize image\n # [Image size is defined by choosen network, during training]\n img = Image.fromarray( frame )\n img = img.resize( ARGS.dim )\n img = numpy.array( img )\n\n # Mean subtraction & scaling [A common technique used to center the data]\n img = img.astype( numpy.float16 )\n img = ( img - numpy.float16( ARGS.mean ) ) * ARGS.scale\n\n return img\n\n# ---- Step 4: Read & print inference results from the NCS -------------------\n\ndef infer_image( graph, img, frame ):\n\n # Load the image as a half-precision floating point array\n graph.LoadTensor( img, 'user object' )\n\n # Get the results from NCS\n output, userobj = graph.GetResult()\n\n # Get execution time\n inference_time = graph.GetGraphOption( mvnc.GraphOption.TIME_TAKEN )\n\n # Deserialize the output into a python dictionary\n output_dict = deserialize_output.ssd( \n output, \n CONFIDANCE_THRESHOLD, \n frame.shape )\n\n # Print the results (each image/frame may have multiple objects)\n for i in range( 0, output_dict['num_detections'] ):\n\n # Filter a specific class/category\n if( output_dict.get( 'detection_classes_' + str(i) ) == CLASS_PERSON ):\n\n cur_time = strftime( \"%Y_%m_%d_%H_%M_%S\", localtime() )\n print( \"Person detected on \" + cur_time )\n\n # Extract top-left & bottom-right coordinates of detected objects \n (y1, x1) = output_dict.get('detection_boxes_' + str(i))[0]\n (y2, x2) = output_dict.get('detection_boxes_' + str(i))[1]\n\n # Prep string to overlay on the image\n display_str = ( \n labels[output_dict.get('detection_classes_' + str(i))]\n + \": \"\n + str( output_dict.get('detection_scores_' + str(i) ) )\n + \"%\" )\n\n # Overlay bounding boxes, detection class and scores\n frame = visualize_output.draw_bounding_box( \n y1, x1, y2, x2, \n frame,\n thickness=4,\n color=(255, 255, 0),\n display_str=display_str )\n\n # Capture snapshots\n img = Image.fromarray( frame )\n photo = ( os.path.dirname(os.path.realpath(__file__))\n + \"/captures/photo_\"\n + cur_time + \".jpg\" )\n img.save( photo )\n\n # If a display is available, show the image on which inference was performed\n if 'DISPLAY' in os.environ:\n img.show()\n\n# ---- Step 5: Unload the graph and close the device -------------------------\n\ndef close_ncs_device( device, graph ):\n graph.DeallocateGraph()\n device.CloseDevice()\n\n# ---- Main function (entry point for this script ) --------------------------\n\ndef main():\n\n device = open_ncs_device()\n graph = load_graph( device )\n\n # Main loop: Capture live stream & send frames to NCS\n with picamera.PiCamera() as camera:\n with picamera.array.PiRGBArray( camera ) as frame:\n while( True ):\n camera.resolution = ( 640, 480 )\n camera.capture( frame, ARGS.colormode, use_video_port=True )\n img = pre_process_image( frame.array )\n infer_image( graph, img, frame.array )\n\n # Clear PiRGBArray, so you can re-use it for next capture\n frame.seek( 0 )\n frame.truncate()\n\n # Run the program until <ENTER> is pressed\n i, o, e = select.select( [sys.stdin], [], [], 0.1 )\n if( i ):\n break\n\n close_ncs_device( device, graph )\n\n# ---- Define 'main' function as the entry point for this script -------------\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(\n description=\"DIY smart security camera using \\\n Rapberry Pi Camera and Intel® Movidius™ Neural Compute Stick. \\\n \\n Hit <ENTER> to terminate program.\" )\n\n parser.add_argument( '-g', '--graph', type=str,\n default='../../caffe/SSD_MobileNet/graph',\n help=\"Absolute path to the neural network graph file.\" )\n\n parser.add_argument( '-l', '--labels', type=str,\n default='../../caffe/SSD_MobileNet/labels.txt',\n help=\"Absolute path to labels file.\" )\n\n parser.add_argument( '-M', '--mean', type=float,\n nargs='+',\n default=[127.5, 127.5, 127.5],\n help=\"',' delimited floating point values for image mean.\" )\n\n parser.add_argument( '-S', '--scale', type=float,\n default=0.00789,\n help=\"Absolute path to labels file.\" )\n\n parser.add_argument( '-D', '--dim', type=int,\n nargs='+',\n default=[300, 300],\n help=\"Image dimensions. ex. -D 224 224\" )\n\n parser.add_argument( '-c', '--colormode', type=str,\n default=\"bgr\",\n help=\"RGB vs BGR color sequence. This is network dependent.\" )\n\n ARGS = parser.parse_args()\n\n # Load the labels file \n labels =[ line.rstrip('\\n') for line in \n open( ARGS.labels ) if line != 'classes\\n'] \n\n main()\n\n# ==== End of file ===========================================================\n", "#!/usr/bin/python3\n\n# ****************************************************************************\n# Copyright(c) 2017 Intel Corporation. \n# License: MIT See LICENSE file in root directory.\n# ****************************************************************************\n\n# How to run Single Shot Multibox Detectors (SSD)\n# on Intel® Movidius™ Neural Compute Stick (NCS)\n\nimport os\nimport sys\nimport numpy as np\nimport ntpath\nimport argparse\nimport skimage.io\nimport skimage.transform\n\nimport mvnc.mvncapi as mvnc\n\nfrom utils import visualize_output\nfrom utils import deserialize_output\n\n# Detection threshold: Minimum confidance to tag as valid detection\nCONFIDANCE_THRESHOLD = 0.60 # 60% confidant\n\n# Variable to store commandline arguments\nARGS = None\n\n# ---- Step 1: Open the enumerated device and get a handle to it -------------\n\ndef open_ncs_device():\n\n # Look for enumerated NCS device(s); quit program if none found.\n devices = mvnc.EnumerateDevices()\n if len( devices ) == 0:\n print( \"No devices found\" )\n quit()\n\n # Get a handle to the first enumerated device and open it\n device = mvnc.Device( devices[0] )\n device.OpenDevice()\n\n return device\n\n# ---- Step 2: Load a graph file onto the NCS device -------------------------\n\ndef load_graph( device ):\n\n # Read the graph file into a buffer\n with open( ARGS.graph, mode='rb' ) as f:\n blob = f.read()\n\n # Load the graph buffer into the NCS\n graph = device.AllocateGraph( blob )\n\n return graph\n\n# ---- Step 3: Pre-process the images ----------------------------------------\n\ndef pre_process_image( img_draw ):\n\n # Resize image [Image size is defined during training]\n img = skimage.transform.resize( img_draw, ARGS.dim, preserve_range=True )\n\n # Convert RGB to BGR [skimage reads image in RGB, some networks may need BGR]\n if( ARGS.colormode == \"bgr\" ):\n img = img[:, :, ::-1]\n\n # Mean subtraction & scaling [A common technique used to center the data]\n img = img.astype( np.float16 )\n img = ( img - np.float16( ARGS.mean ) ) * ARGS.scale\n\n return img\n\n# ---- Step 4: Read & print inference results from the NCS -------------------\n\ndef infer_image( graph, img ):\n\n # Read original image, so we can perform visualization ops on it\n img_draw = skimage.io.imread( ARGS.image )\n\n # The first inference takes an additional ~20ms due to memory \n # initializations, so we make a 'dummy forward pass'.\n graph.LoadTensor( img, 'user object' )\n output, userobj = graph.GetResult()\n\n # Load the image as a half-precision floating point array\n graph.LoadTensor( img, 'user object' )\n\n # Get the results from NCS\n output, userobj = graph.GetResult()\n\n # Get execution time\n inference_time = graph.GetGraphOption( mvnc.GraphOption.TIME_TAKEN )\n\n # Deserialize the output into a python dictionary\n if ARGS.network == 'SSD':\n output_dict = deserialize_output.ssd( output, CONFIDANCE_THRESHOLD, img_draw.shape )\n elif ARGS.network == 'TinyYolo':\n output_dict = deserialize_output.tinyyolo( output, CONFIDANCE_THRESHOLD, img_draw.shape )\n\n # Print the results\n print( \"\\n==============================================================\" )\n print( \"I found these objects in\", ntpath.basename( ARGS.image ) )\n print( \"Execution time: \" + str( np.sum( inference_time ) ) + \"ms\" )\n print( \"--------------------------------------------------------------\" )\n for i in range( 0, output_dict['num_detections'] ):\n print( \"%3.1f%%\\t\" % output_dict['detection_scores_' + str(i)]\n + labels[ int(output_dict['detection_classes_' + str(i)]) ]\n + \": Top Left: \" + str( output_dict['detection_boxes_' + str(i)][0] )\n + \" Bottom Right: \" + str( output_dict['detection_boxes_' + str(i)][1] ) )\n\n # Draw bounding boxes around valid detections \n (y1, x1) = output_dict.get('detection_boxes_' + str(i))[0]\n (y2, x2) = output_dict.get('detection_boxes_' + str(i))[1]\n\n # Prep string to overlay on the image\n display_str = ( \n labels[output_dict.get('detection_classes_' + str(i))]\n + \": \"\n + str( output_dict.get('detection_scores_' + str(i) ) )\n + \"%\" )\n\n img_draw = visualize_output.draw_bounding_box( \n y1, x1, y2, x2, \n img_draw,\n thickness=4,\n color=(255, 255, 0),\n display_str=display_str )\n\n print( \"==============================================================\\n\" )\n\n # If a display is available, show the image on which inference was performed\n if 'DISPLAY' in os.environ:\n skimage.io.imshow( img_draw )\n skimage.io.show()\n\n# ---- Step 5: Unload the graph and close the device -------------------------\n\ndef close_ncs_device( device, graph ):\n graph.DeallocateGraph()\n device.CloseDevice()\n\n# ---- Main function (entry point for this script ) --------------------------\n\ndef main():\n\n device = open_ncs_device()\n graph = load_graph( device )\n\n img_draw = skimage.io.imread( ARGS.image )\n img = pre_process_image( img_draw )\n infer_image( graph, img )\n\n close_ncs_device( device, graph )\n\n# ---- Define 'main' function as the entry point for this script -------------\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(\n description=\"Object detection using SSD on \\\n Intel® Movidius™ Neural Compute Stick.\" )\n\n parser.add_argument( '-n', '--network', type=str,\n default='SSD',\n help=\"network name: SSD or TinyYolo.\" )\n\n parser.add_argument( '-g', '--graph', type=str,\n default='/home/pi/movidius/ncappzoo/caffe/SSD_MobileNet/graph',\n help=\"Absolute path to the neural network graph file.\" )\n\n parser.add_argument( '-i', '--image', type=str,\n default='../../data/images/nps_chair.png',\n help=\"Absolute path to the image that needs to be inferred.\" )\n\n parser.add_argument( '-l', '--labels', type=str,\n default='/home/pi/movidius/ncappzoo/caffe/SSD_MobileNet/labels.txt',\n help=\"Absolute path to labels file.\" )\n\n parser.add_argument( '-M', '--mean', type=float,\n nargs='+',\n default=[127.5, 127.5, 127.5],\n help=\"',' delimited floating point values for image mean.\" )\n\n parser.add_argument( '-S', '--scale', type=float,\n default=0.00789,\n help=\"Absolute path to labels file.\" )\n\n parser.add_argument( '-D', '--dim', type=int,\n nargs='+',\n default=[300, 300],\n help=\"Image dimensions. ex. -D 224 224\" )\n\n parser.add_argument( '-c', '--colormode', type=str,\n default=\"bgr\",\n help=\"RGB vs BGR color sequence. This is network dependent.\" )\n\n ARGS = parser.parse_args()\n\n # Load the labels file\n labels =[ line.rstrip('\\n') for line in\n open( ARGS.labels ) if line != 'classes\\n']\n\n main()\n\n# ==== End of file ===========================================================\n" ]
[ [ "numpy.log", "numpy.zeros", "numpy.float" ], [ "numpy.float16", "numpy.array" ], [ "numpy.float16", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
agarwalrounak/qmt
[ "5e8a7001cc020979636e492448abcfd894396038" ]
[ "tests/py3/test_property_map.py" ]
[ "import numpy as np\n\nfrom qmt.geometry import PropertyMap, MaterialPropertyMap\nfrom qmt.materials import Materials\n\n\nclass DummyPartMap:\n def __init__(self, part_ids):\n assert len(part_ids) == 2\n self.partIds = part_ids\n\n def __call__(self, x):\n assert np.ndim(x) >= 1\n x = np.asanyarray(x)\n if np.ndim(x) == 1:\n return self.partIds[x[0] > 0]\n else:\n return np.where(x[..., 0] > 0, self.partIds[1], self.partIds[0])\n\n\ndef test_property_map():\n int_map = DummyPartMap([0, 1])\n str_map = DummyPartMap(['part1', 'part2'])\n\n prop_map1 = PropertyMap(int_map, np.vectorize(lambda p: 'yes' if p > 0 else 'no'))\n assert prop_map1.get_part((1., 2.)) == 1\n assert np.all(prop_map1.get_part(-np.ones((2, 3))) == 0)\n assert prop_map1((1., 2.)) == 'yes'\n assert np.all(prop_map1(-np.ones((2, 3))) == 'no')\n\n props = {'part1': 'yes', 'part2': 'no'}\n prop_map2 = PropertyMap(str_map, np.vectorize(lambda p: props[p]))\n assert prop_map2.get_part((1., 2.)) == 'part2'\n assert np.all(prop_map2.get_part(-np.ones((2, 3))) == 'part1')\n assert prop_map1((1., 2.)) == 'yes'\n assert np.all(prop_map1(-np.ones((2, 3))) == 'no')\n\n\ndef test_materials_property_map():\n int_map = DummyPartMap([0, 1])\n str_map = DummyPartMap(['part1', 'part2'])\n part_materials1 = {0: 'InAs', 1: 'GaSb'}\n part_materials2 = {'part1': 'InAs', 'part2': 'Al'}\n mat_lib = Materials(matDict={})\n mat_lib.add_material('InAs', 'semi', electronMass=0.026, directBandGap=417.,\n valenceBandOffset=-590.)\n mat_lib.add_material('GaSb', 'semi', electronMass=.039, directBandGap=812.,\n valenceBandOffset=-30.)\n mat_lib.add_material('Al', 'metal', workFunction=4280.)\n\n prop_map1 = MaterialPropertyMap(int_map, part_materials1, mat_lib, 'electronMass')\n assert prop_map1.get_part((1., 2.)) == 1\n assert np.all(prop_map1.get_part(-np.ones((2, 3))) == 0)\n assert prop_map1((1., 2.)) == mat_lib['GaSb']['electronMass']\n assert np.all(prop_map1(-np.ones((2, 3))) == mat_lib['InAs']['electronMass'])\n\n prop_map2 = MaterialPropertyMap(str_map, part_materials2, mat_lib, 'directBandGap', eunit='eV',\n fill_value=0.)\n assert prop_map2.get_part((1., 2.)) == 'part2'\n assert np.all(prop_map2.get_part(-np.ones((2, 3))) == 'part1')\n assert prop_map2((1., 2.)) == 0.\n assert np.all(prop_map2(-np.ones((2, 3))) == mat_lib.find('InAs', 'eV')['directBandGap'])\n" ]
[ [ "numpy.ones", "numpy.ndim", "numpy.asanyarray", "numpy.vectorize", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
abhaikollara/tensorflow
[ "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "4f96df3659696990cb34d0ad07dc67843c4225a9", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "4f96df3659696990cb34d0ad07dc67843c4225a9", "7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae" ]
[ "tensorflow/python/kernel_tests/batch_scatter_ops_test.py", "tensorflow/python/keras/datasets/cifar10.py", "tensorflow/python/framework/kernels.py", "tensorflow/python/kernel_tests/batch_matmul_op_test.py", "tensorflow/python/keras/engine/input_spec_test.py", "tensorflow/python/ops/resource_variable_ops.py", "tensorflow/python/debug/lib/profiling_test.py", "tensorflow/python/keras/preprocessing/image_test.py", "tensorflow/python/keras/optimizer_v2/ftrl_test.py", "tensorflow/python/keras/premade/wide_deep_test.py", "tensorflow/python/eager/wrap_function.py", "tensorflow/python/data/experimental/benchmarks/parallel_interleave_benchmark.py", "tensorflow/python/ops/ragged/ragged_dynamic_partition_op_test.py", "tensorflow/python/data/experimental/kernel_tests/parse_example_dataset_test.py", "tensorflow/python/data/experimental/kernel_tests/counter_test.py", "tensorflow/python/data/experimental/kernel_tests/serialization/parallel_interleave_dataset_serialization_test.py", "tensorflow/python/autograph/converters/asserts_test.py", "tensorflow/python/kernel_tests/distributions/util_test.py", "tensorflow/python/ops/unconnected_gradients.py", "tensorflow/python/kernel_tests/xent_op_test.py", "tensorflow/python/autograph/pyct/static_analysis/liveness_py3_test.py", "tensorflow/python/data/kernel_tests/iterator_cluster_test.py", "tensorflow/python/kernel_tests/proto/decode_proto_op_test_base.py", "tensorflow/python/ops/ragged/ragged_rank_op_test.py", "tensorflow/python/data/experimental/kernel_tests/serialization/interleave_dataset_serialization_test.py", "tensorflow/python/data/experimental/ops/sleep.py", "tensorflow/python/debug/__init__.py", "tensorflow/python/debug/examples/v1/debug_keras.py", "tensorflow/python/kernel_tests/eig_op_test.py", "tensorflow/python/training/tensorboard_logging_test.py", "tensorflow/python/ops/raw_ops_test.py", "tensorflow/python/distribute/strategy_combinations_test.py", "tensorflow/python/ops/accumulate_n_benchmark.py", "tensorflow/python/kernel_tests/linalg/linear_operator_zeros_test.py", "tensorflow/tools/gcs_test/python/gcs_smoke.py", "tensorflow/python/ops/ragged/convert_to_tensor_or_ragged_tensor_op_test.py", "tensorflow/python/keras/models.py", "tensorflow/python/data/experimental/kernel_tests/optimization/hoist_random_uniform_test.py", "tensorflow/python/keras/applications/inception_v3.py", "tensorflow/lite/experimental/examples/lstm/unidirectional_sequence_lstm_test.py", "tensorflow/python/kernel_tests/control_flow_util_v2_test.py", "tensorflow/python/distribute/mirrored_function_strategy_test.py", "tensorflow/tools/docs/doc_generator_visitor_test.py", "tensorflow/python/distribute/summary_op_util.py", "tensorflow/python/distribute/checkpointing_test.py", "tensorflow/python/ops/concat_benchmark.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.tf.scatter.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\ndef _AsType(v, vtype):\n return v.astype(vtype) if isinstance(v, np.ndarray) else vtype(v)\n\n\ndef _NumpyUpdate(ref, indices, updates):\n for i, indx in np.ndenumerate(indices):\n indx = i[:-1] + (indx,)\n ref[indx] = updates[i]\n\n\n_TF_OPS_TO_NUMPY = {\n state_ops.batch_scatter_update: _NumpyUpdate,\n}\n\n\nclass ScatterTest(test.TestCase):\n\n def _VariableRankTest(self,\n tf_scatter,\n vtype,\n itype,\n repeat_indices=False,\n updates_are_scalar=False,\n method=False):\n np.random.seed(8)\n with self.cached_session(use_gpu=False):\n for indices_shape in (2,), (3, 7), (3, 4, 7):\n for extra_shape in (), (5,), (5, 9):\n # Generate random indices with no duplicates for easy numpy comparison\n sparse_dim = len(indices_shape) - 1\n indices = np.random.randint(\n indices_shape[sparse_dim], size=indices_shape, dtype=itype)\n updates = _AsType(\n np.random.randn(*(indices_shape + extra_shape)), vtype)\n\n old = _AsType(np.random.randn(*(indices_shape + extra_shape)), vtype)\n\n # Scatter via numpy\n new = old.copy()\n np_scatter = _TF_OPS_TO_NUMPY[tf_scatter]\n np_scatter(new, indices, updates)\n # Scatter via tensorflow\n ref = variables.Variable(old)\n ref.initializer.run()\n if method:\n ref.batch_scatter_update(ops.IndexedSlices(indices, updates))\n else:\n tf_scatter(ref, indices, updates).eval()\n self.assertAllClose(ref.eval(), new)\n\n @test_util.run_deprecated_v1\n def testVariableRankUpdate(self):\n vtypes = [np.float32, np.float64]\n for vtype in vtypes:\n for itype in (np.int32, np.int64):\n self._VariableRankTest(\n state_ops.batch_scatter_update, vtype, itype)\n\n @test_util.run_deprecated_v1\n def testBooleanScatterUpdate(self):\n with self.session(use_gpu=False) as session:\n var = variables.Variable([True, False])\n update0 = state_ops.batch_scatter_update(var, [1], [True])\n update1 = state_ops.batch_scatter_update(\n var, constant_op.constant(\n [0], dtype=dtypes.int64), [False])\n var.initializer.run()\n\n session.run([update0, update1])\n\n self.assertAllEqual([False, True], self.evaluate(var))\n\n @test_util.run_deprecated_v1\n def testScatterOutOfRange(self):\n params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32)\n updates = np.array([-3, -4, -5]).astype(np.float32)\n with self.session(use_gpu=False):\n ref = variables.Variable(params)\n ref.initializer.run()\n\n # Indices all in range, no problem.\n indices = np.array([2, 0, 5])\n state_ops.batch_scatter_update(ref, indices, updates).eval()\n\n # Test some out of range errors.\n indices = np.array([-1, 0, 5])\n with self.assertRaisesOpError(\n r'indices\\[0\\] = \\[-1\\] does not index into shape \\[6\\]'):\n state_ops.batch_scatter_update(ref, indices, updates).eval()\n\n indices = np.array([2, 0, 6])\n with self.assertRaisesOpError(r'indices\\[2\\] = \\[6\\] does not index into '\n r'shape \\[6\\]'):\n state_ops.batch_scatter_update(ref, indices, updates).eval()\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"CIFAR10 small images classification dataset.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\n\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.datasets.cifar import load_batch\nfrom tensorflow.python.keras.utils.data_utils import get_file\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.datasets.cifar10.load_data')\ndef load_data():\n \"\"\"Loads CIFAR10 dataset.\n\n Returns:\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n dirname = 'cifar-10-batches-py'\n origin = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n path = get_file(\n dirname,\n origin=origin,\n untar=True,\n file_hash=\n '6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce')\n\n num_train_samples = 50000\n\n x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')\n y_train = np.empty((num_train_samples,), dtype='uint8')\n\n for i in range(1, 6):\n fpath = os.path.join(path, 'data_batch_' + str(i))\n (x_train[(i - 1) * 10000:i * 10000, :, :, :],\n y_train[(i - 1) * 10000:i * 10000]) = load_batch(fpath)\n\n fpath = os.path.join(path, 'test_batch')\n x_test, y_test = load_batch(fpath)\n\n y_train = np.reshape(y_train, (len(y_train), 1))\n y_test = np.reshape(y_test, (len(y_test), 1))\n\n if K.image_data_format() == 'channels_last':\n x_train = x_train.transpose(0, 2, 3, 1)\n x_test = x_test.transpose(0, 2, 3, 1)\n\n x_test = x_test.astype(x_train.dtype)\n y_test = y_test.astype(y_train.dtype)\n\n return (x_train, y_train), (x_test, y_test)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Functions for querying registered kernels.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.core.framework import kernel_def_pb2\nfrom tensorflow.python import pywrap_tensorflow as c_api\nfrom tensorflow.python.util import compat\n\n\ndef get_all_registered_kernels():\n \"\"\"Returns a KernelList proto of all registered kernels.\n \"\"\"\n buf = c_api.TF_GetAllRegisteredKernels()\n data = c_api.TF_GetBuffer(buf)\n kernel_list = kernel_def_pb2.KernelList()\n kernel_list.ParseFromString(compat.as_bytes(data))\n return kernel_list\n\n\ndef get_registered_kernels_for_op(name):\n \"\"\"Returns a KernelList proto of registered kernels for a given op.\n\n Args:\n name: A string representing the name of the op whose kernels to retrieve.\n \"\"\"\n buf = c_api.TF_GetRegisteredKernelsForOp(name)\n data = c_api.TF_GetBuffer(buf)\n kernel_list = kernel_def_pb2.KernelList()\n kernel_list.ParseFromString(compat.as_bytes(data))\n return kernel_list\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.tf.BatchMatMul.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python import tf2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker_v2\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import benchmark\nfrom tensorflow.python.platform import test\n\n\ndef GetRandomNormalInput(shape, dtype):\n # float16 has limited range so we reduce the variance of the scalars.\n scale = 10.0 if dtype != np.float16 else 0.1\n loc = -10.0 if dtype != np.float16 else 0.1\n vals = np.array(np.random.normal(loc, scale, np.prod(shape)), dtype=dtype)\n if dtype in (np.complex64, np.complex128):\n imag = np.array(np.random.normal(loc, scale, np.prod(shape)), dtype=dtype)\n vals += 1j * imag\n return vals.reshape(shape)\n\n\nclass BatchMatmulOpTest(test.TestCase):\n\n # Uses numpy to compute batch_matmul(x, y, adjoint_a, adjoint_b).\n def _npBatchMatmul(self, x, y, adjoint_a, adjoint_b):\n # output's shape depends on adj[0] and adj[1]\n if adjoint_a:\n x = np.conjugate(np.swapaxes(x, -1, -2))\n if adjoint_b:\n y = np.conjugate(np.swapaxes(y, -1, -2))\n return np.matmul(x, y)\n\n # Compares TensorFlow BatchMatmul with NumPy's matmul.\n def _compare(self, x_in, y_in, adjoint_a, adjoint_b, static_shape):\n x_t_shape = x_in.shape[:-2] + (x_in.shape[-1], x_in.shape[-2])\n y_t_shape = y_in.shape[:-2] + (y_in.shape[-1], y_in.shape[-2])\n x = x_in if not adjoint_a else x_in.reshape(x_t_shape)\n y = y_in if not adjoint_b else y_in.reshape(y_t_shape)\n is_floating = x.dtype != np.int32\n tol = 100 * np.finfo(x.dtype).eps if is_floating else 0\n with self.cached_session(use_gpu=is_floating) as sess:\n if static_shape:\n z0 = math_ops.matmul(x, y, adjoint_a=adjoint_a, adjoint_b=adjoint_b)\n z0_val = self.evaluate(z0)\n else:\n x_ph = array_ops.placeholder(x.dtype)\n y_ph = array_ops.placeholder(y.dtype)\n z0 = math_ops.matmul(\n x_ph, y_ph, adjoint_a=adjoint_a, adjoint_b=adjoint_b)\n z0_val = sess.run(z0, feed_dict={x_ph: x, y_ph: y})\n z1 = self._npBatchMatmul(x, y, adjoint_a, adjoint_b)\n self.assertAllClose(z0_val, z1, rtol=tol, atol=tol)\n\n def _testNonEmpty(self, dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def CompareNonEmpty(self, a_shape, b_shape):\n self._compare(\n GetRandomNormalInput(a_shape, dtype),\n GetRandomNormalInput(b_shape, dtype),\n adjoint_a,\n adjoint_b,\n static_shape=use_static_shape)\n\n CompareNonEmpty(self, [1, 2, 3], [1, 3, 5])\n CompareNonEmpty(self, [1, 2, 3], [1, 3, 1])\n CompareNonEmpty(self, [1, 1, 3], [1, 3, 5])\n CompareNonEmpty(self, [1, 2, 3], [1, 3, 5])\n CompareNonEmpty(self, [7, 1, 3], [7, 3, 5])\n CompareNonEmpty(self, [7, 2, 3], [7, 3, 1])\n CompareNonEmpty(self, [7, 2, 3], [7, 3, 5])\n CompareNonEmpty(self, [10, 64, 75], [10, 75, 30])\n CompareNonEmpty(self, [5, 7, 2, 3], [5, 7, 3, 5])\n\n def _testBroadcasting(self, dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def CompareNonEmpty(self, a_shape, b_shape):\n self._compare(\n GetRandomNormalInput(a_shape, dtype),\n GetRandomNormalInput(b_shape, dtype),\n adjoint_a,\n adjoint_b,\n static_shape=use_static_shape)\n\n CompareNonEmpty(self, [2, 3], [1, 3, 5])\n CompareNonEmpty(self, [1, 2, 3], [3, 5])\n CompareNonEmpty(self, [5, 1, 2, 3], [1, 7, 3, 5])\n CompareNonEmpty(self, [5, 2, 2, 3], [3, 5])\n CompareNonEmpty(self, [2, 3], [5, 2, 3, 5])\n CompareNonEmpty(self, [4, 5, 1, 2, 3], [1, 1, 3, 5])\n CompareNonEmpty(self, [1, 2, 1, 4, 2, 1, 3, 4], [3, 2, 1, 1, 1, 2, 4, 2])\n\n def _testEmpty(self, dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def CompareEmpty(self, a_shape, b_shape):\n self._compare(\n np.zeros(a_shape).astype(dtype),\n np.zeros(b_shape).astype(dtype),\n adjoint_a,\n adjoint_b,\n static_shape=use_static_shape)\n\n CompareEmpty(self, [0, 3, 2], [0, 2, 4])\n CompareEmpty(self, [3, 0, 2], [3, 2, 5])\n CompareEmpty(self, [3, 3, 2], [3, 2, 0])\n\n\ndef _GetBatchMatmulOpTest(dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def Test(self):\n np.random.seed(42)\n self._testNonEmpty(dtype, adjoint_a, adjoint_b, use_static_shape)\n self._testEmpty(dtype, adjoint_a, adjoint_b, use_static_shape)\n\n return Test\n\n\ndef _GetBatchMatmulOpBroadcastingTest(dtype, adjoint_a, adjoint_b,\n use_static_shape):\n\n def Test(self):\n with compat.forward_compatibility_horizon(2019, 4, 26):\n np.random.seed(42)\n self._testBroadcasting(dtype, adjoint_a, adjoint_b, use_static_shape)\n\n return Test\n\n\nclass BatchMatmulGradientTest(test.TestCase):\n\n # loss = sum(batch_matmul(x, y)). Verify dl/dx and dl/dy via the\n # gradient checker.\n def _checkGrad(self, x_in, y_in, adjoint_a, adjoint_b):\n x_t_shape = x_in.shape[:-2] + (x_in.shape[-1], x_in.shape[-2])\n y_t_shape = y_in.shape[:-2] + (y_in.shape[-1], y_in.shape[-2])\n x = x_in if not adjoint_a else x_in.reshape(x_t_shape)\n y = y_in if not adjoint_b else y_in.reshape(y_t_shape)\n epsilon = np.finfo(x.dtype).eps\n # Since our gradient is linear, a larger delta decreases the error.\n delta = 10 * epsilon**(1.0 / 3.0)\n\n def Loss(x, y):\n return math_ops.reduce_sum(math_ops.matmul(x, y, adjoint_a, adjoint_b))\n\n with self.cached_session(use_gpu=True):\n ((x_jacob_t, y_jacob_t),\n (x_jacob_n, y_jacob_n)) = gradient_checker_v2.compute_gradient(\n Loss, [x, y], delta=delta)\n tol = 10 * delta\n self.assertAllClose(x_jacob_t, x_jacob_n, rtol=tol, atol=tol)\n self.assertAllClose(y_jacob_t, y_jacob_n, rtol=tol, atol=tol)\n\n # Tests gradients of a batched matmul of x, and y\n def _compare(self, a_shape, b_shape, dtype, adjoint_a, adjoint_b):\n np.random.seed(42)\n x = GetRandomNormalInput(a_shape, dtype)\n y = GetRandomNormalInput(b_shape, dtype)\n self._checkGrad(x, y, adjoint_a, adjoint_b)\n\n\ndef _GetBatchMatmulGradientTest(dtype, adjoint_a, adjoint_b):\n\n def Test(self):\n def CheckGradients(self, a_shape, b_shape):\n self._compare(a_shape, b_shape, dtype, adjoint_a, adjoint_b)\n\n CheckGradients(self, [1, 2, 3], [1, 3, 5])\n CheckGradients(self, [3, 4, 7], [3, 7, 10])\n\n return Test\n\n\ndef _GetBatchMatmulGradientWithBroadcastingTest(dtype, adjoint_a, adjoint_b):\n\n def Test(self):\n def CheckGradients(self, a_shape, b_shape):\n self._compare(a_shape, b_shape, dtype, adjoint_a, adjoint_b)\n\n with compat.forward_compatibility_horizon(2019, 4, 26):\n CheckGradients(self, [1, 5, 2, 3], [7, 1, 3, 2])\n CheckGradients(self, [2, 3], [1, 3, 5])\n CheckGradients(self, [2, 3], [5, 3, 5])\n CheckGradients(self, [5, 2, 5], [5, 3])\n CheckGradients(self, [5, 2, 2, 3], [3, 5])\n CheckGradients(self, [4, 5, 1, 2, 3], [1, 1, 3, 5])\n CheckGradients(self, [1, 2, 1, 4, 2, 1, 3, 4], [3, 2, 1, 1, 1, 2, 4, 2])\n\n return Test\n\n\nclass BatchMatMulBenchmark(test.Benchmark):\n # Batch sizes are 512.\n shape_pairs = [\n # Typical fully connected layer.\n ((4, 8, 4, 2, 1, 1024), (1024, 1024)),\n ((4, 1, 4, 1, 1, 1024), (1, 8, 1, 2, 1024, 1024)),\n # Square matmul.\n ((4, 8, 4, 2, 512, 512), (512, 512)),\n ((4, 1, 4, 1, 512, 512), (1, 8, 1, 2, 512, 512)),\n # Matrix-vector multiplies.\n ((4, 8, 4, 2, 10000, 200), (200, 1)),\n ((4, 1, 4, 1, 10000, 200), (1, 8, 1, 2, 200, 1)),\n # Vector-matrix multiplies.\n ((4, 8, 4, 2, 1, 200), (200, 10000)),\n ((4, 1, 4, 1, 1, 200), (1, 8, 1, 2, 200, 10000)),\n ]\n\n def benchmarkBatchMatMulBroadcast(self):\n for (a_shape, b_shape) in self.shape_pairs:\n with compat.forward_compatibility_horizon(2019, 4, 26):\n with ops.Graph().as_default(), \\\n session.Session(config=benchmark.benchmark_config()) as sess, \\\n ops.device(\"/cpu:0\"):\n matrix_a = variables.Variable(\n GetRandomNormalInput(a_shape, np.float32))\n matrix_b = variables.Variable(\n GetRandomNormalInput(b_shape, np.float32))\n variables.global_variables_initializer().run()\n\n # Use batch matmul op's internal broadcasting.\n self.run_op_benchmark(\n sess,\n math_ops.matmul(matrix_a, matrix_b),\n min_iters=50,\n name=\"batch_matmul_cpu_{}_{}\".format(a_shape, b_shape))\n\n # Manually broadcast the input matrices using the broadcast_to op.\n broadcasted_batch_shape = array_ops.broadcast_static_shape(\n matrix_a.shape[:-2], matrix_b.shape[:-2])\n broadcasted_a_shape = broadcasted_batch_shape.concatenate(\n matrix_a.shape[-2:])\n broadcasted_b_shape = broadcasted_batch_shape.concatenate(\n matrix_b.shape[-2:])\n self.run_op_benchmark(\n sess,\n math_ops.matmul(\n array_ops.broadcast_to(matrix_a, broadcasted_a_shape),\n array_ops.broadcast_to(matrix_b, broadcasted_b_shape)),\n min_iters=50,\n name=\"batch_matmul_manual_broadcast_cpu_{}_{}\".format(\n a_shape, b_shape))\n\n\nif __name__ == \"__main__\":\n dtypes_to_test = [np.float16, np.float32, np.float64, np.int32]\n if not test.is_built_with_rocm():\n # ROCm does not support BLAS operations for complex types\n dtypes_to_test += [np.complex64, np.complex128]\n for dtype_ in dtypes_to_test:\n for adjoint_a_ in False, True:\n for adjoint_b_ in False, True:\n name = \"%s_%s_%s\" % (dtype_.__name__, adjoint_a_, adjoint_b_)\n # TF2 does not support placeholders under eager so we skip it.\n for use_static_shape_ in set([True, tf2.enabled()]):\n setattr(\n BatchMatmulOpTest,\n \"testBatchMatmulOp_\" + name + \"_{}\".format(use_static_shape_),\n test_util.xla_allow_fallback(\n \"TODO(b/134526360): XLA:CPU hasn't implemented int32 dot.\")(\n _GetBatchMatmulOpTest(dtype_, adjoint_a_, adjoint_b_,\n use_static_shape_)))\n # Broadcasting is supported only in v2.\n setattr(\n BatchMatmulOpTest, \"testBatchMatmulBroadcasting_\" + name +\n (\"_%s\" % use_static_shape_),\n test_util.xla_allow_fallback(\n \"TODO(b/134526360): XLA:CPU hasn't implemented int32 dot.\")(\n _GetBatchMatmulOpBroadcastingTest(dtype_, adjoint_a_,\n adjoint_b_,\n use_static_shape_)))\n if dtype_ == np.int32:\n continue\n setattr(BatchMatmulGradientTest, \"testBatchMatmulGradient_\" + name,\n _GetBatchMatmulGradientTest(dtype_, adjoint_a_, adjoint_b_))\n # Broadcasting is supported only in v2.\n setattr(\n BatchMatmulGradientTest,\n \"testBatchMatmulGradientWithBroadcasting_\" + name,\n _GetBatchMatmulGradientWithBroadcastingTest(dtype_, adjoint_a_,\n adjoint_b_))\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"InputSpec tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras.engine import input_spec\nfrom tensorflow.python.platform import test\n\n\nclass InputSpecTest(test.TestCase):\n\n def test_axes_initialization(self):\n input_spec.InputSpec(shape=[1, None, 2, 3], axes={3: 5, '2': 2})\n with self.assertRaisesRegexp(ValueError, 'Axis 4 is greater than'):\n input_spec.InputSpec(shape=[1, None, 2, 3], axes={4: 5})\n with self.assertRaisesRegexp(TypeError, 'keys in axes must be integers'):\n input_spec.InputSpec(shape=[1, None, 2, 3], axes={'string': 5})\n\n\nclass InputSpecToTensorShapeTest(test.TestCase):\n\n def test_defined_shape(self):\n spec = input_spec.InputSpec(shape=[1, None, 2, 3])\n self.assertAllEqual(\n [1, None, 2, 3], input_spec.to_tensor_shape(spec).as_list())\n\n def test_defined_ndims(self):\n spec = input_spec.InputSpec(ndim=5)\n self.assertAllEqual(\n [None] * 5, input_spec.to_tensor_shape(spec).as_list())\n\n spec = input_spec.InputSpec(ndim=0)\n self.assertAllEqual(\n [], input_spec.to_tensor_shape(spec).as_list())\n\n spec = input_spec.InputSpec(ndim=3, axes={1: 3, -1: 2})\n self.assertAllEqual(\n [None, 3, 2], input_spec.to_tensor_shape(spec).as_list())\n\n def test_undefined_shapes(self):\n spec = input_spec.InputSpec(max_ndim=5)\n with self.assertRaisesRegexp(ValueError, 'unknown TensorShape'):\n input_spec.to_tensor_shape(spec).as_list()\n\n spec = input_spec.InputSpec(min_ndim=5, max_ndim=5)\n with self.assertRaisesRegexp(ValueError, 'unknown TensorShape'):\n input_spec.to_tensor_shape(spec).as_list()\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Ops to use variables as resources.\"\"\"\n\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport functools\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import variable_pb2\nfrom tensorflow.python import _pywrap_utils\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import cpp_shape_inference_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_logging_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.ops import gen_state_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_resource_variable_ops import *\n# pylint: enable=wildcard-import\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util.deprecation import deprecated\nfrom tensorflow.python.util.deprecation import deprecated_args\n\n\ndef get_resource_handle_data(graph_op):\n assert type(graph_op) == ops.Tensor # pylint: disable=unidiomatic-typecheck\n\n handle_data = pywrap_tensorflow.GetHandleShapeAndType(\n graph_op.graph._c_graph, graph_op._as_tf_output()) # pylint: disable=protected-access\n\n return cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData.FromString(\n compat.as_bytes(handle_data))\n\n\ndef get_eager_safe_handle_data(handle):\n \"\"\"Get the data handle from the Tensor `handle`.\"\"\"\n assert isinstance(handle, ops.Tensor)\n\n if isinstance(handle, ops.EagerTensor):\n return handle._handle_data # pylint: disable=protected-access\n else:\n return get_resource_handle_data(handle)\n\n\ndef _set_handle_shapes_and_types(tensor, handle_data, graph_mode):\n \"\"\"Sets the shape inference result HandleData on tensor.\n\n Args:\n tensor: A `Tensor` or `EagerTensor`.\n handle_data: A `CppShapeInferenceResult.HandleData`.\n graph_mode: A python bool.\n \"\"\"\n tensor._handle_data = handle_data # pylint: disable=protected-access\n if not graph_mode:\n return\n\n # Not an EagerTensor, so a graph tensor.\n shapes, types = zip(*[(pair.shape, pair.dtype)\n for pair in handle_data.shape_and_type])\n ranks = [len(s.dim) if not s.unknown_rank else -1 for s in shapes]\n shapes = [[d.size for d in s.dim] # pylint: disable=g-complex-comprehension\n if not s.unknown_rank else None for s in shapes]\n pywrap_tensorflow.TF_GraphSetOutputHandleShapesAndTypes_wrapper(\n tensor._op._graph._c_graph, # pylint: disable=protected-access\n tensor._as_tf_output(), # pylint: disable=protected-access\n shapes, ranks, types)\n\n\ndef _combine_handle_data(handle, initial_value):\n \"\"\"Concats HandleData from tensors `handle` and `initial_value`.\n\n Args:\n handle: A `Tensor` of dtype `resource`.\n initial_value: A `Tensor`.\n\n Returns:\n A `CppShapeInferenceResult.HandleData`. If `initial_value` has dtype\n `variant`, the `HandleData` contains the concatenation of the shape_and_type\n from both `handle` and `initial_value`.\n\n Raises:\n RuntimeError: If handle, which was returned by VarHandleOp, either has\n no handle data, or its len(handle_data.shape_and_type) != 1.\n \"\"\"\n assert handle.dtype == dtypes.resource\n\n variable_handle_data = get_eager_safe_handle_data(handle)\n\n if initial_value.dtype != dtypes.variant:\n return variable_handle_data\n\n extra_handle_data = get_eager_safe_handle_data(initial_value)\n if extra_handle_data is not None and extra_handle_data.is_set:\n if (variable_handle_data is None\n or not variable_handle_data.is_set\n or len(variable_handle_data.shape_and_type) != 1):\n raise RuntimeError(\n \"Expected VarHandleOp to return a length==1 shape_and_type, \"\n \"but saw: '%s'\" % (variable_handle_data,))\n variable_handle_data.shape_and_type.extend(\n extra_handle_data.shape_and_type)\n return variable_handle_data\n\n\ndef _variable_handle_from_shape_and_dtype(\n shape, dtype, shared_name, name, graph_mode, initial_value=None):\n \"\"\"Create a variable handle, copying in handle data from `initial_value`.\"\"\"\n container = ops.get_default_graph()._container # pylint: disable=protected-access\n if container is None:\n container = \"\"\n shape = tensor_shape.as_shape(shape)\n dtype = dtypes.as_dtype(dtype)\n handle = gen_resource_variable_ops.var_handle_op(shape=shape, dtype=dtype,\n shared_name=shared_name,\n name=name,\n container=container)\n if initial_value is None:\n initial_value = handle\n if graph_mode:\n full_handle_data = _combine_handle_data(handle, initial_value)\n _set_handle_shapes_and_types(handle, full_handle_data, graph_mode)\n return handle\n else:\n # We do not want two distinct ResourceVariable objects for the same\n # underlying resource in the runtime.\n # When in eager mode, explicitly ensure so here. When in graph mode, it's\n # ensured by always generating different variable names.\n exists = gen_resource_variable_ops.var_is_initialized_op(handle)\n\n # We create an assert Op instead of checking right away in order to be\n # compatible with ASYNC execution mode. Further, since not all devices\n # support string tensors, we encode the assertion string in the Op name\n gen_logging_ops._assert( # pylint: disable=protected-access\n math_ops.logical_not(exists), [exists], name=\"EagerVariableNameReuse\")\n\n handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData()\n handle_data.is_set = True\n handle_data.shape_and_type.append(\n cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType(\n shape=shape.as_proto(), dtype=dtype.as_datatype_enum))\n\n if initial_value is not None and initial_value.dtype == dtypes.variant:\n extra_handle_data = get_eager_safe_handle_data(initial_value)\n if extra_handle_data is not None and extra_handle_data.is_set:\n if (not handle_data.is_set\n or len(handle_data.shape_and_type) != 1):\n raise RuntimeError(\n \"Expected VarHandleOp to return a length==1 shape_and_type, \"\n \"but saw: '%s'\" % (handle_data,))\n handle_data.shape_and_type.extend(\n extra_handle_data.shape_and_type)\n\n _set_handle_shapes_and_types(handle, handle_data, graph_mode)\n return handle\n\n\ndef eager_safe_variable_handle(initial_value, shape, shared_name, name,\n graph_mode):\n \"\"\"Creates a variable handle with information to do shape inference.\n\n The dtype is read from `initial_value` and stored in the returned\n resource tensor's handle data.\n\n If `initial_value.dtype == tf.variant`, we additionally extract the handle\n data (if any) from `initial_value` and append it to the `handle_data`.\n In this case, the returned tensor's handle data is in the form\n\n ```\n is_set: true\n shape_and_type {\n shape {\n // initial_value.shape\n }\n dtype: DT_VARIANT\n }\n shape_and_type {\n // handle_data(initial_value).shape_and_type[0]\n }\n shape_and_type {\n // handle_data(initial_value).shape_and_type[1]\n }\n ...\n ```\n\n Ops that read from this tensor, such as `ReadVariableOp` and\n `AssignVariableOp`, know that `handle_data(handle).shape_and_type[1:]`\n correspond to the handle data of the variant(s) stored in the Variable.\n\n Args:\n initial_value: A `Tensor`.\n shape: The shape of the handle data. Can be `TensorShape(None)`\n (i.e. unknown shape).\n shared_name: A string.\n name: A string.\n graph_mode: A python bool.\n\n Returns:\n The handle, a `Tensor` of type `resource`.\n \"\"\"\n dtype = initial_value.dtype.base_dtype\n return _variable_handle_from_shape_and_dtype(\n shape, dtype, shared_name, name, graph_mode, initial_value)\n\n\[email protected]\ndef _handle_graph(handle):\n # Note: might have an eager tensor but not be executing eagerly when building\n # functions.\n if (context.executing_eagerly() or isinstance(handle, ops.EagerTensor)\n or ops.has_default_graph()):\n yield\n else:\n with handle.graph.as_default():\n yield\n\n\nclass EagerResourceDeleter(object):\n \"\"\"An object which cleans up a resource handle.\n\n An alternative to defining a __del__ method on an object. The intended use is\n that ResourceVariables or other objects with resource handles will maintain a\n single reference to this object. When the parent object is collected, this\n object will be too. Even if the parent object is part of a reference cycle,\n the cycle will be collectable.\n \"\"\"\n\n def __init__(self, handle, handle_device):\n if not isinstance(handle, ops.Tensor):\n raise ValueError(\n (\"Passed handle=%s to EagerResourceDeleter. Was expecting a handle \"\n \"Tensor.\" % (handle,)))\n self._handle = handle\n self._handle_device = handle_device\n # This is held since the __del__ function runs an op, and if the context()\n # is collected before this object, there will be a segfault when running the\n # op.\n self._context = context.context()\n\n def __del__(self):\n # Resources follow object-identity when executing eagerly, so it is safe to\n # delete the resource we have a handle to.\n try:\n # This resource was created in eager mode. However, this destructor may be\n # running in graph mode (especially during unit tests). To clean up\n # successfully, we switch back into eager mode temporarily.\n with context.eager_mode():\n with ops.device(self._handle_device):\n gen_resource_variable_ops.destroy_resource_op(\n self._handle, ignore_lookup_error=True)\n except TypeError:\n # Suppress some exceptions, mainly for the case when we're running on\n # module deletion. Things that can go wrong include the context module\n # already being unloaded, self._handle._handle_data no longer being\n # valid, and so on. Printing warnings in these cases is silly\n # (exceptions raised from __del__ are printed as warnings to stderr).\n pass # 'NoneType' object is not callable when the handle has been\n # partially unloaded.\n except AttributeError:\n pass # 'NoneType' object has no attribute 'eager_mode' when context has\n # been unloaded. Will catch other module unloads as well.\n\n\ndef shape_safe_assign_variable_handle(handle, shape, value, name=None):\n \"\"\"Helper that checks shape compatibility and assigns variable.\"\"\"\n with _handle_graph(handle):\n value_tensor = ops.convert_to_tensor(value)\n shape.assert_is_compatible_with(value_tensor.shape)\n return gen_resource_variable_ops.assign_variable_op(handle,\n value_tensor,\n name=name)\n\n\ndef _maybe_set_handle_data(dtype, handle, tensor):\n if dtype == dtypes.variant:\n # For DT_VARIANT types, the handle's shape_and_type[1:] stores the\n # variant's handle data. Extract it.\n handle_data = get_eager_safe_handle_data(handle)\n if handle_data.is_set and len(handle_data.shape_and_type) > 1:\n tensor._handle_data = ( # pylint: disable=protected-access\n cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData(\n is_set=True,\n shape_and_type=handle_data.shape_and_type[1:]))\n\n\ndef variable_accessed(variable):\n \"\"\"Records that `variable` was accessed for the tape and FuncGraph.\"\"\"\n if hasattr(ops.get_default_graph(), \"watch_variable\"):\n ops.get_default_graph().watch_variable(variable)\n if variable.trainable:\n tape.variable_accessed(variable)\n\n\nclass BaseResourceVariable(variables.VariableV1):\n \"\"\"A python variable from an existing handle.\"\"\"\n\n @deprecated_args(\n None,\n \"If using Keras pass *_constraint arguments to layers.\",\n \"constraint\")\n def __init__( # pylint: disable=super-init-not-called\n self,\n trainable=None,\n shape=None,\n dtype=None,\n handle=None,\n constraint=None,\n synchronization=None,\n aggregation=None,\n distribute_strategy=None,\n name=None,\n unique_id=None,\n handle_name=None,\n graph_element=None,\n initial_value=None,\n initializer_op=None,\n is_initialized_op=None,\n cached_value=None,\n save_slice_info=None,\n handle_deleter=None,\n **unused_kwargs):\n \"\"\"Creates a variable from a handle.\n\n Args:\n trainable: If `True`, GradientTapes automatically watch uses of this\n Variable.\n shape: The variable's shape.\n dtype: The variable's dtype.\n handle: The variable's handle\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value\n (which must have the same shape). Constraints are not safe to\n use when doing asynchronous distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses\n when to synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n distribute_strategy: The distribution strategy this variable was created\n under.\n name: The name for this variable.\n unique_id: Internal. Unique ID for this variable's handle.\n handle_name: The name for the variable's handle.\n graph_element: Optional, required only in session.run-mode. Pre-created\n tensor which reads this variable's value.\n initial_value: Optional. Variable's initial value.\n initializer_op: Operation which assigns the variable's initial value.\n is_initialized_op: Pre-created operation to check whether this variable\n is initialized.\n cached_value: Pre-created operation to read this variable in a specific\n device.\n save_slice_info: Metadata for variable partitioning.\n handle_deleter: EagerResourceDeleter responsible for cleaning up the\n handle.\n \"\"\"\n with ops.init_scope():\n self._in_graph_mode = not context.executing_eagerly()\n synchronization, aggregation, trainable = (\n variables.validate_synchronization_aggregation_trainable(\n synchronization, aggregation, trainable, name))\n self._trainable = trainable\n self._synchronization = synchronization\n self._aggregation = aggregation\n self._save_slice_info = save_slice_info\n self._initial_value = initial_value\n self._initializer_op = initializer_op\n self._is_initialized_op = is_initialized_op\n self._graph_element = graph_element\n self._cached_value = cached_value\n self._distribute_strategy = distribute_strategy\n # Store the graph key so optimizers know how to only retrieve variables from\n # this graph. Guaranteed to be the same as the eager graph_key.\n self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access\n self._shape = tensor_shape.as_shape(shape)\n self._dtype = dtypes.as_dtype(dtype)\n self._handle = handle\n self._graph_element = graph_element\n self._unique_id = unique_id\n self._handle_name = handle_name + \":0\"\n self._constraint = constraint\n # After the handle has been created, set up a way to clean it up when\n # executing eagerly. We'll hold the only reference to the deleter, so that\n # when this object is garbage collected the deleter will be too. This\n # means ResourceVariables can be part of reference cycles without those\n # cycles being uncollectable.\n if not self._in_graph_mode:\n if handle_deleter is None:\n handle_deleter = EagerResourceDeleter(\n handle=self._handle, handle_device=self._handle.device)\n self._handle_deleter = handle_deleter\n self._cached_shape_as_list = None\n\n def __repr__(self):\n if context.executing_eagerly() and not self._in_graph_mode:\n return \"<tf.Variable '%s' shape=%s dtype=%s, numpy=%s>\" % (\n self.name, self.get_shape(), self.dtype.name,\n ops.numpy_text(self.read_value(), is_repr=True))\n else:\n return \"<tf.Variable '%s' shape=%s dtype=%s>\" % (\n self.name, self.get_shape(), self.dtype.name)\n\n @contextlib.contextmanager\n def _assign_dependencies(self):\n \"\"\"Makes assignments depend on the cached value, if any.\n\n This prevents undefined behavior with reads not ordered wrt writes.\n\n Yields:\n None.\n \"\"\"\n if self._cached_value is not None:\n with ops.control_dependencies([self._cached_value]):\n yield\n else:\n yield\n\n def __nonzero__(self):\n return self.__bool__()\n\n def __bool__(self):\n return bool(self.read_value())\n\n def __copy__(self):\n return self\n\n def __deepcopy__(self, memo):\n if not context.executing_eagerly():\n raise NotImplementedError(\n \"__deepcopy__() is only available when eager execution is enabled.\")\n copied_variable = ResourceVariable(\n initial_value=self.read_value(),\n trainable=self._trainable,\n constraint=self._constraint,\n dtype=self._dtype,\n name=self._shared_name,\n distribute_strategy=self._distribute_strategy)\n memo[self._unique_id] = copied_variable\n return copied_variable\n\n @property\n def dtype(self):\n \"\"\"The dtype of this variable.\"\"\"\n return self._dtype\n\n @property\n def device(self):\n \"\"\"The device this variable is on.\"\"\"\n return self._handle.device\n\n @property\n def graph(self):\n \"\"\"The `Graph` of this variable.\"\"\"\n return self._handle.graph\n\n @property\n def name(self):\n \"\"\"The name of the handle for this variable.\"\"\"\n return self._handle_name\n\n @property\n def shape(self):\n \"\"\"The shape of this variable.\"\"\"\n return self._shape\n\n def _shape_as_list(self):\n if self.shape.ndims is None:\n return None\n return [dim.value for dim in self.shape.dims]\n\n def _shape_tuple(self):\n shape = self._shape_as_list()\n if shape is None:\n return None\n return tuple(shape)\n\n @property\n def create(self):\n \"\"\"The op responsible for initializing this variable.\"\"\"\n if not self._in_graph_mode:\n raise RuntimeError(\"Calling create is not supported when eager execution\"\n \" is enabled.\")\n return self._initializer_op\n\n @property\n def handle(self):\n \"\"\"The handle by which this variable can be accessed.\"\"\"\n return self._handle\n\n def value(self):\n \"\"\"A cached operation which reads the value of this variable.\"\"\"\n if self._cached_value is not None:\n return self._cached_value\n with ops.colocate_with(None, ignore_existing=True):\n return self._read_variable_op()\n\n def _as_graph_element(self):\n \"\"\"Conversion function for Graph.as_graph_element().\"\"\"\n return self._graph_element\n\n @property\n def initializer(self):\n \"\"\"The op responsible for initializing this variable.\"\"\"\n return self._initializer_op\n\n @property\n def initial_value(self):\n \"\"\"Returns the Tensor used as the initial value for the variable.\"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"initial_value not supported in EAGER mode.\")\n return self._initial_value\n\n @property\n def constraint(self):\n \"\"\"Returns the constraint function associated with this variable.\n\n Returns:\n The constraint function that was passed to the variable constructor.\n Can be `None` if no constraint was passed.\n \"\"\"\n return self._constraint\n\n @property\n def op(self):\n \"\"\"The op for this variable.\"\"\"\n return self._handle.op\n\n @property\n def trainable(self):\n return self._trainable\n\n @property\n def synchronization(self):\n return self._synchronization\n\n @property\n def aggregation(self):\n return self._aggregation\n\n def eval(self, session=None):\n \"\"\"Evaluates and returns the value of this variable.\"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"Trying to eval in EAGER mode\")\n return self._graph_element.eval(session=session)\n\n def numpy(self):\n if context.executing_eagerly():\n return self.read_value().numpy()\n raise NotImplementedError(\n \"numpy() is only available when eager execution is enabled.\")\n\n @deprecated(None, \"Prefer Dataset.range instead.\")\n def count_up_to(self, limit):\n \"\"\"Increments this variable until it reaches `limit`.\n\n When that Op is run it tries to increment the variable by `1`. If\n incrementing the variable would bring it above `limit` then the Op raises\n the exception `OutOfRangeError`.\n\n If no error is raised, the Op outputs the value of the variable before\n the increment.\n\n This is essentially a shortcut for `count_up_to(self, limit)`.\n\n Args:\n limit: value at which incrementing the variable raises an error.\n\n Returns:\n A `Tensor` that will hold the variable value before the increment. If no\n other Op modifies this variable, the values produced will all be\n distinct.\n \"\"\"\n return gen_state_ops.resource_count_up_to(self.handle, limit=limit,\n T=self.dtype)\n\n def _read_variable_op(self):\n variable_accessed(self)\n result = gen_resource_variable_ops.read_variable_op(self._handle,\n self._dtype)\n _maybe_set_handle_data(self._dtype, self._handle, result)\n\n if not context.executing_eagerly():\n # Note that if a control flow context is active the input of the read op\n # might not actually be the handle. This line bypasses it.\n tape.record_operation(\n \"ReadVariableOp\", [result], [self._handle],\n backward_function=lambda x: [x],\n forward_function=lambda x: [x])\n return result\n\n def read_value(self):\n \"\"\"Constructs an op which reads the value of this variable.\n\n Should be used when there are multiple reads, or when it is desirable to\n read the value only after some condition is true.\n\n Returns:\n the read operation.\n \"\"\"\n with ops.name_scope(\"Read\"):\n value = self._read_variable_op()\n # Return an identity so it can get placed on whatever device the context\n # specifies instead of the device where the variable is.\n return array_ops.identity(value)\n\n def sparse_read(self, indices, name=None):\n \"\"\"Reads the value of this variable sparsely, using `gather`.\"\"\"\n with ops.name_scope(\"Gather\" if name is None else name) as name:\n variable_accessed(self)\n value = gen_resource_variable_ops.resource_gather(\n self._handle, indices, dtype=self._dtype, name=name)\n\n if self._dtype == dtypes.variant:\n # For DT_VARIANT types, the handle's shape_and_type[1:] stores the\n # variant's handle data. Extract it.\n handle_data = get_eager_safe_handle_data(self._handle)\n if handle_data.is_set and len(handle_data.shape_and_type) > 1:\n value._handle_data = ( # pylint: disable=protected-access\n cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData(\n is_set=True,\n shape_and_type=handle_data.shape_and_type[1:]))\n\n return array_ops.identity(value)\n\n def gather_nd(self, indices, name=None):\n \"\"\"Reads the value of this variable sparsely, using `gather_nd`.\"\"\"\n with ops.name_scope(\"GatherNd\" if name is None else name) as name:\n if self.trainable:\n variable_accessed(self)\n value = gen_resource_variable_ops.resource_gather_nd(\n self._handle, indices, dtype=self._dtype, name=name)\n\n return array_ops.identity(value)\n\n def to_proto(self, export_scope=None):\n \"\"\"Converts a `ResourceVariable` to a `VariableDef` protocol buffer.\n\n Args:\n export_scope: Optional `string`. Name scope to remove.\n\n Raises:\n RuntimeError: If run in EAGER mode.\n\n Returns:\n A `VariableDef` protocol buffer, or `None` if the `Variable` is not\n in the specified name scope.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"to_proto not supported in EAGER mode.\")\n if export_scope is None or self.handle.name.startswith(export_scope):\n var_def = variable_pb2.VariableDef()\n var_def.variable_name = ops.strip_name_scope(self.handle.name,\n export_scope)\n if self._initial_value is not None:\n # This is inside an if-statement for backwards compatibility, since\n # self._initial_value might be None for variables constructed from old\n # protos.\n var_def.initial_value_name = ops.strip_name_scope(\n self._initial_value.name, export_scope)\n var_def.initializer_name = ops.strip_name_scope(self.initializer.name,\n export_scope)\n if self._cached_value is not None:\n var_def.snapshot_name = ops.strip_name_scope(self._cached_value.name,\n export_scope)\n else:\n # Store the graph_element here\n var_def.snapshot_name = ops.strip_name_scope(self._graph_element.name,\n export_scope)\n var_def.is_resource = True\n var_def.trainable = self.trainable\n var_def.synchronization = self.synchronization.value\n var_def.aggregation = self.aggregation.value\n if self._save_slice_info:\n var_def.save_slice_info_def.MergeFrom(\n self._save_slice_info.to_proto(export_scope=export_scope))\n return var_def\n else:\n return None\n\n @staticmethod\n def from_proto(variable_def, import_scope=None):\n if context.executing_eagerly():\n raise RuntimeError(\"from_proto not supported in EAGER mode.\")\n return ResourceVariable(\n variable_def=variable_def, import_scope=import_scope)\n\n def set_shape(self, shape):\n \"\"\"Unsupported.\"\"\"\n raise NotImplementedError(\"ResourceVariable does not implement set_shape()\")\n\n __array_priority__ = 100\n\n def is_initialized(self, name=None):\n \"\"\"Checks whether a resource variable has been initialized.\n\n Outputs boolean scalar indicating whether the tensor has been initialized.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `bool`.\n \"\"\"\n return gen_resource_variable_ops.var_is_initialized_op(self.handle, name)\n\n def assign_sub(self, delta, use_locking=None, name=None, read_value=True):\n \"\"\"Subtracts a value from this variable.\n\n Args:\n delta: A `Tensor`. The value to subtract from this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name to use for the operation.\n read_value: A `bool`. Whether to read and return the new value of the\n variable or not.\n\n Returns:\n If `read_value` is `True`, this method will return the new value of the\n variable after the assignment has completed. Otherwise, when in graph mode\n it will return the `Operation` that does the assignment, and when in eager\n mode it will return `None`.\n \"\"\"\n # TODO(apassos): this here and below is not atomic. Consider making it\n # atomic if there's a way to do so without a performance cost for those who\n # don't need it.\n with _handle_graph(self.handle), self._assign_dependencies():\n assign_sub_op = gen_resource_variable_ops.assign_sub_variable_op(\n self.handle, ops.convert_to_tensor(delta, dtype=self.dtype),\n name=name)\n if read_value:\n return self._lazy_read(assign_sub_op)\n return assign_sub_op\n\n def assign_add(self, delta, use_locking=None, name=None, read_value=True):\n \"\"\"Adds a value to this variable.\n\n Args:\n delta: A `Tensor`. The value to add to this variable.\n use_locking: If `True`, use locking during the operation.\n name: The name to use for the operation.\n read_value: A `bool`. Whether to read and return the new value of the\n variable or not.\n\n Returns:\n If `read_value` is `True`, this method will return the new value of the\n variable after the assignment has completed. Otherwise, when in graph mode\n it will return the `Operation` that does the assignment, and when in eager\n mode it will return `None`.\n \"\"\"\n with _handle_graph(self.handle), self._assign_dependencies():\n assign_add_op = gen_resource_variable_ops.assign_add_variable_op(\n self.handle, ops.convert_to_tensor(delta, dtype=self.dtype),\n name=name)\n if read_value:\n return self._lazy_read(assign_add_op)\n return assign_add_op\n\n def _lazy_read(self, op):\n variable_accessed(self)\n return _UnreadVariable(\n handle=self._handle, dtype=self.dtype, shape=self._shape,\n in_graph_mode=self._in_graph_mode,\n deleter=self._handle_deleter if not self._in_graph_mode else None,\n parent_op=op, unique_id=self._unique_id)\n\n def assign(self, value, use_locking=None, name=None, read_value=True):\n \"\"\"Assigns a new value to this variable.\n\n Args:\n value: A `Tensor`. The new value for this variable.\n use_locking: If `True`, use locking during the assignment.\n name: The name to use for the assignment.\n read_value: A `bool`. Whether to read and return the new value of the\n variable or not.\n\n Returns:\n If `read_value` is `True`, this method will return the new value of the\n variable after the assignment has completed. Otherwise, when in graph mode\n it will return the `Operation` that does the assignment, and when in eager\n mode it will return `None`.\n \"\"\"\n # Note: not depending on the cached value here since this can used to\n # initialize the variable.\n with _handle_graph(self.handle):\n value_tensor = ops.convert_to_tensor(value, dtype=self.dtype)\n self._shape.assert_is_compatible_with(value_tensor.shape)\n assign_op = gen_resource_variable_ops.assign_variable_op(\n self.handle, value_tensor, name=name)\n if read_value:\n return self._lazy_read(assign_op)\n return assign_op\n\n def __reduce__(self):\n # The implementation mirrors that of __deepcopy__.\n return functools.partial(\n ResourceVariable,\n initial_value=self.numpy(),\n trainable=self.trainable,\n name=self._shared_name,\n dtype=self.dtype,\n constraint=self.constraint,\n distribute_strategy=self._distribute_strategy), ()\n\n def scatter_sub(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Subtracts `tf.IndexedSlices` from this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be subtracted from this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_sub(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_add(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Adds `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be added to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered addition has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_add(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_max(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the max of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of max\n with this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered maximization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_max(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_min(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Updates this variable with the min of `tf.IndexedSlices` and itself.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to use as an argument of min\n with this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered minimization has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_min(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_mul(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Multiply this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to multiply this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered multiplication has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_mul(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_div(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Divide this variable by `tf.IndexedSlices`.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to divide this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered division has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_div(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(gen_resource_variable_ops.resource_scatter_update(\n self.handle, sparse_delta.indices,\n ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))\n\n def batch_scatter_update(self, sparse_delta, use_locking=False, name=None):\n \"\"\"Assigns `tf.IndexedSlices` to this variable batch-wise.\n\n Analogous to `batch_gather`. This assumes that this variable and the\n sparse_delta IndexedSlices have a series of leading dimensions that are the\n same for all of them, and the updates are performed on the last dimension of\n indices. In other words, the dimensions should be the following:\n\n `num_prefix_dims = sparse_delta.indices.ndims - 1`\n `batch_dim = num_prefix_dims + 1`\n `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[\n batch_dim:]`\n\n where\n\n `sparse_delta.updates.shape[:num_prefix_dims]`\n `== sparse_delta.indices.shape[:num_prefix_dims]`\n `== var.shape[:num_prefix_dims]`\n\n And the operation performed can be expressed as:\n\n `var[i_1, ..., i_n,\n sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[\n i_1, ..., i_n, j]`\n\n When sparse_delta.indices is a 1D tensor, this operation is equivalent to\n `scatter_update`.\n\n To avoid this operation one can looping over the first `ndims` of the\n variable and using `scatter_update` on the subtensors that result of slicing\n the first dimension. This is a valid option for `ndims = 1`, but less\n efficient than this implementation.\n\n Args:\n sparse_delta: `tf.IndexedSlices` to be assigned to this variable.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n\n Raises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.\n \"\"\"\n if not isinstance(sparse_delta, ops.IndexedSlices):\n raise TypeError(\"sparse_delta is not IndexedSlices: %s\" % sparse_delta)\n return self._lazy_read(state_ops.batch_scatter_update(\n self, sparse_delta.indices, sparse_delta.values,\n use_locking=use_locking, name=name))\n\n def scatter_nd_sub(self, indices, updates, name=None):\n \"\"\"Applies sparse subtraction to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = ref.scatter_nd_sub(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to ref would look like this:\n\n [1, -9, 3, -6, -6, 6, 7, -4]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n \"\"\"\n return self._lazy_read(gen_state_ops.resource_scatter_nd_sub(\n self.handle, indices, ops.convert_to_tensor(updates, self.dtype),\n name=name))\n\n def scatter_nd_add(self, indices, updates, name=None):\n \"\"\"Applies sparse addition to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n add = ref.scatter_nd_add(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(add)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n \"\"\"\n return self._lazy_read(gen_state_ops.resource_scatter_nd_add(\n self.handle, indices, ops.convert_to_tensor(updates, self.dtype),\n name=name))\n\n def scatter_nd_update(self, indices, updates, name=None):\n \"\"\"Applies sparse assignment to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = ref.scatter_nd_update(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\n Args:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\n Returns:\n A `Tensor` that will hold the new value of this variable after\n the scattered subtraction has completed.\n \"\"\"\n return self._lazy_read(gen_state_ops.resource_scatter_nd_update(\n self.handle, indices, ops.convert_to_tensor(updates, self.dtype),\n name=name))\n\n def _strided_slice_assign(self, begin, end, strides, value, name, begin_mask,\n end_mask, ellipsis_mask, new_axis_mask,\n shrink_axis_mask):\n with _handle_graph(self.handle), self._assign_dependencies():\n return self._lazy_read(\n gen_array_ops.resource_strided_slice_assign(\n ref=self.handle,\n begin=begin,\n end=end,\n strides=strides,\n value=ops.convert_to_tensor(value, dtype=self.dtype),\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask))\n\n def __int__(self):\n if self.dtype != dtypes.int32 and self.dtype != dtypes.int64:\n raise TypeError(\"Non-integer variable can't be converted to integer.\")\n return int(self.value().numpy())\n\n def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):\n del name\n if dtype is not None and not dtype.is_compatible_with(self.dtype):\n raise ValueError(\n \"Incompatible type conversion requested to type {!r} for variable \"\n \"of type {!r}\".format(dtype.name, self.dtype.name))\n if as_ref:\n return self.read_value().op.inputs[0]\n else:\n return self.value()\n\n def __iadd__(self, unused_other):\n raise RuntimeError(\"Variable += value not supported. Use \"\n \"variable.assign_add(value) to modify the variable \"\n \"value and variable = variable + value to get a new \"\n \"Tensor object.\")\n\n def __isub__(self, unused_other):\n raise RuntimeError(\"Variable -= value not supported. Use \"\n \"variable.assign_sub(value) to modify the variable \"\n \"value and variable = variable - value to get a new \"\n \"Tensor object.\")\n\n def __imul__(self, unused_other):\n raise RuntimeError(\"Variable *= value not supported. Use \"\n \"`var.assign(var * value)` to modify the variable or \"\n \"`var = var * value` to get a new Tensor object.\")\n\n def __idiv__(self, unused_other):\n raise RuntimeError(\"Variable /= value not supported. Use \"\n \"`var.assign(var / value)` to modify the variable or \"\n \"`var = var / value` to get a new Tensor object.\")\n\n def __itruediv__(self, unused_other):\n raise RuntimeError(\"Variable /= value not supported. Use \"\n \"`var.assign(var / value)` to modify the variable or \"\n \"`var = var / value` to get a new Tensor object.\")\n\n def __irealdiv__(self, unused_other):\n raise RuntimeError(\"Variable /= value not supported. Use \"\n \"`var.assign(var / value)` to modify the variable or \"\n \"`var = var / value` to get a new Tensor object.\")\n\n def __ipow__(self, unused_other):\n raise RuntimeError(\"Variable **= value not supported. Use \"\n \"`var.assign(var ** value)` to modify the variable or \"\n \"`var = var ** value` to get a new Tensor object.\")\n\n\nclass ResourceVariable(BaseResourceVariable):\n \"\"\"Variable based on resource handles.\n\n See the [Variables How To](https://tensorflow.org/guide/variables)\n for a high level overview.\n\n A `ResourceVariable` allows you to maintain state across subsequent calls to\n session.run.\n\n The `ResourceVariable` constructor requires an initial value for the variable,\n which can be a `Tensor` of any type and shape. The initial value defines the\n type and shape of the variable. After construction, the type and shape of\n the variable are fixed. The value can be changed using one of the assign\n methods.\n\n Just like any `Tensor`, variables created with\n `tf.Variable(use_resource=True)` can be used as inputs for other Ops in the\n graph. Additionally, all the operators overloaded for the `Tensor` class are\n carried over to variables, so you can also add nodes to the graph by just\n doing arithmetic on variables.\n\n Unlike ref-based variable, a ResourceVariable has well-defined semantics. Each\n usage of a ResourceVariable in a TensorFlow graph adds a read_value operation\n to the graph. The Tensors returned by a read_value operation are guaranteed to\n see all modifications to the value of the variable which happen in any\n operation on which the read_value depends on (either directly, indirectly, or\n via a control dependency) and guaranteed to not see any modification to the\n value of the variable from operations that depend on the read_value operation.\n Updates from operations that have no dependency relationship to the read_value\n operation might or might not be visible to read_value.\n\n For example, if there is more than one assignment to a ResourceVariable in\n a single session.run call there is a well-defined value for each operation\n which uses the variable's value if the assignments and the read are connected\n by edges in the graph. Consider the following example, in which two writes\n can cause tf.Variable and tf.ResourceVariable to behave differently:\n\n ```python\n a = tf.Variable(1.0, use_resource=True)\n a.initializer.run()\n\n assign = a.assign(2.0)\n with tf.control_dependencies([assign]):\n b = a.read_value()\n with tf.control_dependencies([b]):\n other_assign = a.assign(3.0)\n with tf.control_dependencies([other_assign]):\n # Will print 2.0 because the value was read before other_assign ran. If\n # `a` was a tf.Variable instead, 2.0 or 3.0 could be printed.\n tf.compat.v1.Print(b, [b]).eval()\n ```\n \"\"\"\n\n def __init__(self, # pylint: disable=super-init-not-called\n initial_value=None,\n trainable=None,\n collections=None,\n validate_shape=True, # pylint: disable=unused-argument\n caching_device=None,\n name=None,\n dtype=None,\n variable_def=None,\n import_scope=None,\n constraint=None,\n distribute_strategy=None,\n synchronization=None,\n aggregation=None,\n shape=None):\n \"\"\"Creates a variable.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. Can also be a\n callable with no argument that returns the initial value when called.\n (Note that initializer functions from init_ops.py must first be bound\n to a shape before being used here.)\n trainable: If `True`, the default, also adds the variable to the graph\n collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as\n the default list of variables to use by the `Optimizer` classes.\n Defaults to `True`, unless `synchronization` is set to `ON_READ`, in\n which case it defaults to `False`.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n validate_shape: Ignored. Provided for compatibility with tf.Variable.\n caching_device: Optional device string or function describing where the\n Variable should be cached for reading. Defaults to the Variable's\n device. If not `None`, caches on another device. Typical use is to\n cache on the device where the Ops using the Variable reside, to\n deduplicate copying through `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n dtype: If set, initial_value will be converted to the given type.\n If None, either the datatype will be kept (if initial_value is\n a Tensor) or float32 will be used (if it is a Python object convertible\n to a Tensor).\n variable_def: `VariableDef` protocol buffer. If not None, recreates the\n `ResourceVariable` object with its contents. `variable_def` and other\n arguments (except for import_scope) are mutually exclusive.\n import_scope: Optional `string`. Name scope to add to the\n ResourceVariable. Only used when `variable_def` is provided.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value\n (which must have the same shape). Constraints are not safe to\n use when doing asynchronous distributed training.\n distribute_strategy: The tf.distribute.Strategy this variable is being\n created inside of.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses\n when to synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n\n @compatibility(eager)\n When Eager Execution is enabled, the default for the `collections` argument\n is `None`, which signifies that this `Variable` will not be added to any\n collections.\n @end_compatibility\n \"\"\"\n if variable_def:\n if initial_value is not None:\n raise ValueError(\"variable_def and initial_value are mutually \"\n \"exclusive.\")\n if context.executing_eagerly():\n raise ValueError(\"Creating ResourceVariable from variable_def is \"\n \"not supported when eager execution is enabled.\")\n self._init_from_proto(variable_def, import_scope=import_scope)\n else:\n self._init_from_args(\n initial_value=initial_value,\n trainable=trainable,\n collections=collections,\n caching_device=caching_device,\n name=name,\n dtype=dtype,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation,\n shape=shape,\n distribute_strategy=distribute_strategy)\n\n def _init_from_args(self,\n initial_value=None,\n trainable=None,\n collections=None,\n caching_device=None,\n name=None,\n dtype=None,\n constraint=None,\n synchronization=None,\n aggregation=None,\n distribute_strategy=None,\n shape=None):\n \"\"\"Creates a variable.\n\n Args:\n initial_value: A `Tensor`, or Python object convertible to a `Tensor`,\n which is the initial value for the Variable. The initial value must have\n a shape specified unless `validate_shape` is set to False. Can also be a\n callable with no argument that returns the initial value when called.\n (Note that initializer functions from init_ops.py must first be bound\n to a shape before being used here.)\n trainable: If `True`, the default, also adds the variable to the graph\n collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as\n the default list of variables to use by the `Optimizer` classes.\n Defaults to `True`, unless `synchronization` is set to `ON_READ`, in\n which case it defaults to `False`.\n collections: List of graph collections keys. The new variable is added to\n these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n caching_device: Optional device string or function describing where the\n Variable should be cached for reading. Defaults to the Variable's\n device. If not `None`, caches on another device. Typical use is to\n cache on the device where the Ops using the Variable reside, to\n deduplicate copying through `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n dtype: If set, initial_value will be converted to the given type.\n If None, either the datatype will be kept (if initial_value is\n a Tensor) or float32 will be used (if it is a Python object convertible\n to a Tensor).\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value\n (which must have the same shape). Constraints are not safe to\n use when doing asynchronous distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses\n when to synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n distribute_strategy: DistributionStrategy under which this variable\n was created.\n shape: (optional) The shape of this variable. If None, the shape of\n `initial_value` will be used. When setting this argument to\n `tf.TensorShape(None)` (representing an unspecified shape), the variable\n can be assigned with values of different shapes.\n\n Raises:\n ValueError: If the initial value is not specified, or does not have a\n shape and `validate_shape` is `True`.\n\n @compatibility(eager)\n When Eager Execution is enabled, variables are never added to collections.\n It is not implicitly added to the `GLOBAL_VARIABLES` or\n `TRAINABLE_VARIABLES` collections, and the `collections` argument is\n ignored.\n @end_compatibility\n \"\"\"\n synchronization, aggregation, trainable = (\n variables.validate_synchronization_aggregation_trainable(\n synchronization, aggregation, trainable, name))\n if initial_value is None:\n raise ValueError(\"initial_value must be specified.\")\n init_from_fn = callable(initial_value)\n\n if isinstance(initial_value, ops.Tensor) and hasattr(\n initial_value, \"graph\") and initial_value.graph.building_function:\n raise ValueError(\"Tensor-typed variable initializers must either be \"\n \"wrapped in an init_scope or callable \"\n \"(e.g., `tf.Variable(lambda : \"\n \"tf.truncated_normal([10, 40]))`) when building \"\n \"functions. Please file a feature request if this \"\n \"restriction inconveniences you.\")\n\n if collections is None:\n collections = [ops.GraphKeys.GLOBAL_VARIABLES]\n if not isinstance(collections, (list, tuple, set)):\n raise ValueError(\n \"collections argument to Variable constructor must be a list, tuple, \"\n \"or set. Got %s of type %s\" % (collections, type(collections)))\n if constraint is not None and not callable(constraint):\n raise ValueError(\"The `constraint` argument must be a callable.\")\n\n if isinstance(initial_value, trackable.CheckpointInitialValue):\n self._maybe_initialize_trackable()\n self._update_uid = initial_value.checkpoint_position.restore_uid\n initial_value = initial_value.wrapped_value\n\n if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections:\n collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES]\n with ops.init_scope():\n self._in_graph_mode = not context.executing_eagerly()\n with ops.name_scope(name, \"Variable\", []\n if init_from_fn else [initial_value]) as name:\n # pylint: disable=protected-access\n handle_name = ops.name_from_scope_name(name)\n if self._in_graph_mode:\n shared_name = handle_name\n unique_id = shared_name\n else:\n # When in eager mode use a uid for the shared_name, to prevent\n # accidental sharing.\n unique_id = \"%s_%d\" % (handle_name, ops.uid())\n shared_name = context.shared_name()\n # Use attr_scope and device(None) to simulate the behavior of\n # colocate_with when the variable we want to colocate with doesn't\n # yet exist.\n device_context_manager = (\n ops.device if self._in_graph_mode else ops.NullContextmanager)\n attr = attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(\n s=[compat.as_bytes(\"loc:@%s\" % handle_name)]))\n with ops.get_default_graph()._attr_scope({\"_class\": attr}):\n with ops.name_scope(\"Initializer\"), device_context_manager(None):\n initial_value = ops.convert_to_tensor(\n initial_value() if init_from_fn else initial_value,\n name=\"initial_value\", dtype=dtype)\n if shape is not None:\n if not initial_value.shape.is_compatible_with(shape):\n raise ValueError(\n \"The initial value's shape (%s) is not compatible with \"\n \"the explicitly supplied `shape` argument (%s).\" %\n (initial_value.shape, shape))\n else:\n shape = initial_value.shape\n handle = eager_safe_variable_handle(\n initial_value=initial_value,\n shape=shape,\n shared_name=shared_name,\n name=name,\n graph_mode=self._in_graph_mode)\n # pylint: disable=protected-access\n if (self._in_graph_mode and initial_value is not None and\n initial_value.op._get_control_flow_context() is not None):\n raise ValueError(\n \"Initializer for variable %s is from inside a control-flow \"\n \"construct, such as a loop or conditional. When creating a \"\n \"variable inside a loop or conditional, use a lambda as the \"\n \"initializer.\" % name)\n # pylint: enable=protected-access\n dtype = initial_value.dtype.base_dtype\n\n if self._in_graph_mode:\n with ops.name_scope(\"IsInitialized\"):\n is_initialized_op = (\n gen_resource_variable_ops.var_is_initialized_op(handle))\n if initial_value is not None:\n # pylint: disable=g-backslash-continuation\n with ops.name_scope(\"Assign\") as n, \\\n ops.colocate_with(None, ignore_existing=True), \\\n ops.device(handle.device):\n # pylint: disable=protected-access\n initializer_op = (\n gen_resource_variable_ops.assign_variable_op(\n handle,\n variables._try_guard_against_uninitialized_dependencies(\n name,\n initial_value),\n name=n))\n # pylint: enable=protected-access\n # pylint: enable=g-backslash-continuation\n with ops.name_scope(\"Read\"):\n # Manually assign reads to the handle's device to avoid log\n # messages.\n with ops.device(handle.device):\n value = gen_resource_variable_ops.read_variable_op(handle, dtype)\n _maybe_set_handle_data(dtype, handle, value)\n graph_element = value\n if caching_device is not None:\n # Variables may be created in a tf.device() or ops.colocate_with()\n # context. At the same time, users would expect caching device to\n # be independent of this context, and/or would not expect the\n # current device context to be merged with the caching device\n # spec. Therefore we reset the colocation stack before creating\n # the cached value. Note that resetting the colocation stack will\n # also reset the device stack.\n with ops.colocate_with(None, ignore_existing=True):\n with ops.device(caching_device):\n cached_value = array_ops.identity(value)\n else:\n cached_value = None\n else:\n gen_resource_variable_ops.assign_variable_op(handle, initial_value)\n is_initialized_op = None\n initializer_op = None\n graph_element = None\n if caching_device:\n with ops.device(caching_device):\n cached_value = gen_resource_variable_ops.read_variable_op(\n handle, dtype)\n _maybe_set_handle_data(dtype, handle, cached_value)\n else:\n cached_value = None\n if not context.executing_eagerly():\n # Eager variables are only added to collections if they are part of an\n # eager variable store (otherwise in an interactive session they would\n # hog memory and cause OOM). This is done in ops/variable_scope.py.\n ops.add_to_collections(collections, self)\n elif ops.GraphKeys.GLOBAL_STEP in collections:\n ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, self)\n initial_value = initial_value if self._in_graph_mode else None\n super(ResourceVariable, self).__init__(\n trainable=trainable, shape=shape, dtype=dtype, handle=handle,\n synchronization=synchronization, constraint=constraint,\n aggregation=aggregation, distribute_strategy=distribute_strategy,\n name=name, unique_id=unique_id, handle_name=handle_name,\n graph_element=graph_element, initial_value=initial_value,\n initializer_op=initializer_op, is_initialized_op=is_initialized_op,\n cached_value=cached_value)\n\n def _init_from_proto(self, variable_def, import_scope=None):\n \"\"\"Initializes from `VariableDef` proto.\"\"\"\n # Note that init_from_proto is currently not supported in Eager mode.\n assert not context.executing_eagerly()\n self._in_graph_mode = True\n assert isinstance(variable_def, variable_pb2.VariableDef)\n if not variable_def.is_resource:\n raise ValueError(\"Trying to restore Variable as ResourceVariable.\")\n\n # Create from variable_def.\n g = ops.get_default_graph()\n self._handle = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.variable_name, import_scope=import_scope))\n self._shape = tensor_shape.TensorShape(\n self._handle.op.get_attr(\"shape\"))\n self._handle_name = self._handle.name\n self._unique_id = self._handle_name\n self._initializer_op = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.initializer_name, import_scope=import_scope))\n # Check whether initial_value_name exists for backwards compatibility.\n if (hasattr(variable_def, \"initial_value_name\") and\n variable_def.initial_value_name):\n self._initial_value = g.as_graph_element(\n ops.prepend_name_scope(variable_def.initial_value_name,\n import_scope=import_scope))\n else:\n self._initial_value = None\n synchronization, aggregation, trainable = (\n variables.validate_synchronization_aggregation_trainable(\n variable_def.synchronization,\n variable_def.aggregation,\n variable_def.trainable,\n variable_def.variable_name))\n self._synchronization = synchronization\n self._aggregation = aggregation\n self._trainable = trainable\n if variable_def.snapshot_name:\n snapshot = g.as_graph_element(\n ops.prepend_name_scope(\n variable_def.snapshot_name, import_scope=import_scope))\n if snapshot.op.type != \"ReadVariableOp\":\n self._cached_value = snapshot\n else:\n self._cached_value = None\n while snapshot.op.type != \"ReadVariableOp\":\n snapshot = snapshot.op.inputs[0]\n self._graph_element = snapshot\n else:\n self._cached_value = None\n # Legacy case for protos without the snapshot name; assume it's the\n # following.\n self._graph_element = g.get_tensor_by_name(\n self._handle.op.name + \"/Read/ReadVariableOp:0\")\n if variable_def.HasField(\"save_slice_info_def\"):\n self._save_slice_info = variables.Variable.SaveSliceInfo(\n save_slice_info_def=variable_def.save_slice_info_def,\n import_scope=import_scope)\n else:\n self._save_slice_info = None\n self._caching_device = None\n self._dtype = dtypes.as_dtype(self._handle.op.get_attr(\"dtype\"))\n self._constraint = None\n\n\nclass UninitializedVariable(BaseResourceVariable):\n \"\"\"A variable with no initializer.\"\"\"\n\n def __init__( # pylint: disable=super-init-not-called\n self,\n trainable=None,\n caching_device=None,\n name=None,\n shape=None,\n dtype=None,\n constraint=None,\n synchronization=None,\n aggregation=None,\n extra_handle_data=None,\n distribute_strategy=None,\n **unused_kwargs):\n \"\"\"Creates the variable handle.\n\n Args:\n trainable: If `True`, GradientTapes automatically watch uses of this\n Variable.\n caching_device: Optional device string or function describing where the\n Variable should be cached for reading. Defaults to the Variable's\n device. If not `None`, caches on another device. Typical use is to\n cache on the device where the Ops using the Variable reside, to\n deduplicate copying through `Switch` and other conditional statements.\n name: Optional name for the variable. Defaults to `'Variable'` and gets\n uniquified automatically.\n shape: The variable's shape.\n dtype: The variable's dtype.\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value\n (which must have the same shape). Constraints are not safe to\n use when doing asynchronous distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses\n when to synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n extra_handle_data: Optional, another resource handle or Tensor with handle\n data to merge with `shape` and `dtype`.\n distribute_strategy: The tf.distribute.Strategy this variable is being\n created inside of.\n \"\"\"\n with ops.init_scope():\n self._in_graph_mode = not context.executing_eagerly()\n with ops.init_scope():\n with ops.name_scope(name, \"Variable\") as name:\n handle_name = ops.name_from_scope_name(name)\n if self._in_graph_mode:\n shared_name = handle_name\n unique_id = shared_name\n else:\n unique_id = \"%s_%d\" % (handle_name, ops.uid())\n shared_name = context.shared_name(unique_id)\n handle = _variable_handle_from_shape_and_dtype(\n shape=shape, dtype=dtype, shared_name=shared_name,\n name=name, graph_mode=self._in_graph_mode,\n initial_value=extra_handle_data)\n if not context.executing_eagerly():\n with ops.name_scope(\"Read\"):\n # Manually assign reads to the handle's device to avoid log\n # messages.\n with ops.device(handle.device):\n value = gen_resource_variable_ops.read_variable_op(handle, dtype)\n _maybe_set_handle_data(dtype, handle, value)\n graph_element = value\n ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, self)\n # Do *not* add to TRAINABLE_VARIABLES here, even if self._trainable,\n # because retraining or frozen use of imported SavedModels is\n # controlled at higher levels of model building.\n else:\n graph_element = None\n super(UninitializedVariable, self).__init__(\n distribute_strategy=distribute_strategy, shape=shape, dtype=dtype,\n unique_id=unique_id, handle_name=handle_name, constraint=constraint,\n handle=handle, graph_element=graph_element, trainable=trainable,\n synchronization=synchronization, aggregation=aggregation)\n\n\n_pywrap_utils.RegisterType(\"ResourceVariable\", ResourceVariable)\nmath_ops._resource_variable_type = ResourceVariable # pylint: disable=protected-access\n\n\ndef _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):\n return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access\n\n\n# Register a conversion function which reads the value of the variable,\n# allowing instances of the class to be used as tensors.\nops.register_tensor_conversion_function(BaseResourceVariable,\n _dense_var_to_tensor)\nops.register_dense_tensor_like_type(BaseResourceVariable)\n\n\nclass _UnreadVariable(BaseResourceVariable):\n \"\"\"Represents a future for a read of a variable.\n\n Pretends to be the tensor if anyone looks.\n \"\"\"\n\n def __init__(self, handle, dtype, shape, in_graph_mode, deleter,\n parent_op, unique_id):\n if isinstance(handle, ops.EagerTensor):\n handle_name = \"\"\n else:\n handle_name = handle.name\n # Only create a graph_element if we're in session.run-land as only\n # session.run requires a preexisting tensor to evaluate. Otherwise we can\n # avoid accidentally reading the variable.\n if (context.executing_eagerly()\n or ops.get_default_graph()._building_function): # pylint: disable=protected-access\n graph_element = None\n else:\n with ops.control_dependencies([parent_op]):\n graph_element = gen_resource_variable_ops.read_variable_op(\n handle, dtype)\n _maybe_set_handle_data(dtype, handle, graph_element)\n super(_UnreadVariable, self).__init__(\n handle=handle, shape=shape, handle_name=handle_name,\n unique_id=unique_id, dtype=dtype, handle_deleter=deleter,\n graph_element=graph_element)\n self._parent_op = parent_op\n\n @property\n def name(self):\n if self._in_graph_mode:\n return self._parent_op.name\n else:\n return \"UnreadVariable\"\n\n def value(self):\n return self._read_variable_op()\n\n def read_value(self):\n return self._read_variable_op()\n\n def _read_variable_op(self):\n with ops.control_dependencies([self._parent_op]):\n result = gen_resource_variable_ops.read_variable_op(self._handle,\n self._dtype)\n _maybe_set_handle_data(self._dtype, self._handle, result)\n return result\n\n @property\n def op(self):\n \"\"\"The op for this variable.\"\"\"\n return self._parent_op\n\n\nops.register_dense_tensor_like_type(_UnreadVariable)\n\n\[email protected](\"ReadVariableOp\")\ndef _ReadGrad(_, grad):\n \"\"\"Gradient for read op.\"\"\"\n return grad\n\n\ndef variable_shape(handle, out_type=dtypes.int32):\n if getattr(\n handle, \"_handle_data\", None) is None or not handle._handle_data.is_set: # pylint: disable=protected-access\n return gen_resource_variable_ops.variable_shape(handle, out_type=out_type)\n shape_proto = handle._handle_data.shape_and_type[0].shape # pylint: disable=protected-access\n if shape_proto.unknown_rank or any(x.size == -1 for x in shape_proto.dim):\n return gen_resource_variable_ops.variable_shape(handle, out_type=out_type)\n return constant_op.constant([x.size for x in shape_proto.dim], dtype=out_type)\n\n\[email protected](\"ResourceGather\")\ndef _GatherGrad(op, grad):\n \"\"\"Gradient for gather op.\"\"\"\n # Build appropriately shaped IndexedSlices\n handle = op.inputs[0]\n indices = op.inputs[1]\n params_shape = variable_shape(handle)\n size = array_ops.expand_dims(array_ops.size(indices), 0)\n values_shape = array_ops.concat([size, params_shape[1:]], 0)\n values = array_ops.reshape(grad, values_shape)\n indices = array_ops.reshape(indices, size)\n return (ops.IndexedSlices(values, indices, params_shape), None)\n\n\ndef _to_proto_fn(v, export_scope=None):\n \"\"\"Converts Variable and ResourceVariable to VariableDef for collections.\"\"\"\n return v.to_proto(export_scope=export_scope)\n\n\ndef _from_proto_fn(v, import_scope=None):\n \"\"\"Creates Variable or ResourceVariable from VariableDef as needed.\"\"\"\n if v.is_resource:\n return ResourceVariable.from_proto(v, import_scope=import_scope)\n return variables.Variable.from_proto(v, import_scope=import_scope)\n\n\nops.register_proto_function(\n ops.GraphKeys.GLOBAL_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.TRAINABLE_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.MOVING_AVERAGE_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.LOCAL_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.MODEL_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.GLOBAL_STEP,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\nops.register_proto_function(\n ops.GraphKeys.METRIC_VARIABLES,\n proto_type=variable_pb2.VariableDef,\n to_proto=_to_proto_fn,\n from_proto=_from_proto_fn)\n\n\ndef is_resource_variable(var):\n \"\"\"\"Returns True if `var` is to be considered a ResourceVariable.\"\"\"\n return isinstance(var, BaseResourceVariable) or hasattr(\n var, \"_should_act_as_resource_variable\")\n\n\ndef copy_to_graph_uninitialized(var):\n \"\"\"Copies an existing variable to a new graph, with no initializer.\"\"\"\n # Like ResourceVariable.__deepcopy__, but does not set an initializer on the\n # new variable.\n # pylint: disable=protected-access\n new_variable = UninitializedVariable(\n trainable=var.trainable,\n constraint=var._constraint,\n shape=var.shape,\n dtype=var.dtype,\n name=var._shared_name,\n synchronization=var.synchronization,\n aggregation=var.aggregation,\n extra_handle_data=var.handle)\n new_variable._maybe_initialize_trackable()\n # pylint: enable=protected-access\n return new_variable\n\nops.NotDifferentiable(\"Assert\")\nops.NotDifferentiable(\"VarIsInitializedOp\")\nops.NotDifferentiable(\"VariableShape\")\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Unit tests for the basic data structures and algorithms for profiling.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.core.framework import step_stats_pb2\nfrom tensorflow.python.debug.lib import profiling\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import googletest\n\n\nclass AggregateProfile(test_util.TensorFlowTestCase):\n\n def setUp(self):\n node_1 = step_stats_pb2.NodeExecStats(\n node_name=\"Add/123\",\n op_start_rel_micros=3,\n op_end_rel_micros=5,\n all_end_rel_micros=4)\n self.profile_datum_1 = profiling.ProfileDatum(\n \"cpu:0\", node_1, \"/foo/bar.py\", 10, \"func1\", \"Add\")\n\n node_2 = step_stats_pb2.NodeExecStats(\n node_name=\"Mul/456\",\n op_start_rel_micros=13,\n op_end_rel_micros=16,\n all_end_rel_micros=17)\n self.profile_datum_2 = profiling.ProfileDatum(\n \"cpu:0\", node_2, \"/foo/bar.py\", 11, \"func1\", \"Mul\")\n\n node_3 = step_stats_pb2.NodeExecStats(\n node_name=\"Add/123\",\n op_start_rel_micros=103,\n op_end_rel_micros=105,\n all_end_rel_micros=4)\n self.profile_datum_3 = profiling.ProfileDatum(\n \"cpu:0\", node_3, \"/foo/bar.py\", 12, \"func1\", \"Add\")\n\n node_4 = step_stats_pb2.NodeExecStats(\n node_name=\"Add/123\",\n op_start_rel_micros=203,\n op_end_rel_micros=205,\n all_end_rel_micros=4)\n self.profile_datum_4 = profiling.ProfileDatum(\n \"gpu:0\", node_4, \"/foo/bar.py\", 13, \"func1\", \"Add\")\n\n def testAggregateProfileConstructorWorks(self):\n aggregate_data = profiling.AggregateProfile(self.profile_datum_1)\n\n self.assertEqual(2, aggregate_data.total_op_time)\n self.assertEqual(4, aggregate_data.total_exec_time)\n self.assertEqual(1, aggregate_data.node_count)\n self.assertEqual(1, aggregate_data.node_exec_count)\n\n def testAddToAggregateProfileWithDifferentNodeWorks(self):\n aggregate_data = profiling.AggregateProfile(self.profile_datum_1)\n aggregate_data.add(self.profile_datum_2)\n\n self.assertEqual(5, aggregate_data.total_op_time)\n self.assertEqual(21, aggregate_data.total_exec_time)\n self.assertEqual(2, aggregate_data.node_count)\n self.assertEqual(2, aggregate_data.node_exec_count)\n\n def testAddToAggregateProfileWithSameNodeWorks(self):\n aggregate_data = profiling.AggregateProfile(self.profile_datum_1)\n aggregate_data.add(self.profile_datum_2)\n aggregate_data.add(self.profile_datum_3)\n\n self.assertEqual(7, aggregate_data.total_op_time)\n self.assertEqual(25, aggregate_data.total_exec_time)\n self.assertEqual(2, aggregate_data.node_count)\n self.assertEqual(3, aggregate_data.node_exec_count)\n\n def testAddToAggregateProfileWithDifferentDeviceSameNodeWorks(self):\n aggregate_data = profiling.AggregateProfile(self.profile_datum_1)\n aggregate_data.add(self.profile_datum_4)\n\n self.assertEqual(4, aggregate_data.total_op_time)\n self.assertEqual(8, aggregate_data.total_exec_time)\n self.assertEqual(2, aggregate_data.node_count)\n self.assertEqual(2, aggregate_data.node_exec_count)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for image preprocessing utils.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport tempfile\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.platform import test\n\ntry:\n import PIL # pylint:disable=g-import-not-at-top\nexcept ImportError:\n PIL = None\n\n\ndef _generate_test_images():\n img_w = img_h = 20\n rgb_images = []\n gray_images = []\n for _ in range(8):\n bias = np.random.rand(img_w, img_h, 1) * 64\n variance = np.random.rand(img_w, img_h, 1) * (255 - 64)\n imarray = np.random.rand(img_w, img_h, 3) * variance + bias\n im = keras.preprocessing.image.array_to_img(imarray, scale=False)\n rgb_images.append(im)\n\n imarray = np.random.rand(img_w, img_h, 1) * variance + bias\n im = keras.preprocessing.image.array_to_img(imarray, scale=False)\n gray_images.append(im)\n\n return [rgb_images, gray_images]\n\n\nclass TestImage(test.TestCase):\n\n def test_image_data_generator(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n for test_images in _generate_test_images():\n img_list = []\n for im in test_images:\n img_list.append(keras.preprocessing.image.img_to_array(im)[None, ...])\n\n images = np.vstack(img_list)\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.5,\n zoom_range=0.2,\n channel_shift_range=0.,\n brightness_range=(1, 5),\n fill_mode='nearest',\n cval=0.5,\n horizontal_flip=True,\n vertical_flip=True)\n # Basic test before fit\n x = np.random.random((32, 10, 10, 3))\n generator.flow(x)\n\n # Fit\n generator.fit(images, augment=True)\n\n for x, _ in generator.flow(\n images,\n np.arange(images.shape[0]),\n shuffle=True):\n self.assertEqual(x.shape[1:], images.shape[1:])\n break\n\n def test_image_data_generator_with_split_value_error(self):\n with self.assertRaises(ValueError):\n keras.preprocessing.image.ImageDataGenerator(validation_split=5)\n\n def test_image_data_generator_invalid_data(self):\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_last')\n\n # Test fit with invalid data\n with self.assertRaises(ValueError):\n x = np.random.random((3, 10, 10))\n generator.fit(x)\n # Test flow with invalid data\n with self.assertRaises(ValueError):\n generator.flow(np.arange(5))\n # Invalid number of channels: will work but raise a warning\n x = np.random.random((32, 10, 10, 5))\n generator.flow(x)\n\n with self.assertRaises(ValueError):\n generator = keras.preprocessing.image.ImageDataGenerator(\n data_format='unknown')\n\n generator = keras.preprocessing.image.ImageDataGenerator(\n zoom_range=(2, 2))\n\n def test_image_data_generator_fit(self):\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_last')\n # Test grayscale\n x = np.random.random((32, 10, 10, 1))\n generator.fit(x)\n # Test RBG\n x = np.random.random((32, 10, 10, 3))\n generator.fit(x)\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n data_format='channels_first')\n # Test grayscale\n x = np.random.random((32, 1, 10, 10))\n generator.fit(x)\n # Test RBG\n x = np.random.random((32, 3, 10, 10))\n generator.fit(x)\n\n def test_directory_iterator(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n num_classes = 2\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n\n # create folders and subfolders\n paths = []\n for cl in range(num_classes):\n class_directory = 'class-{}'.format(cl)\n classpaths = [\n class_directory, os.path.join(class_directory, 'subfolder-1'),\n os.path.join(class_directory, 'subfolder-2'), os.path.join(\n class_directory, 'subfolder-1', 'sub-subfolder')\n ]\n for path in classpaths:\n os.mkdir(os.path.join(temp_dir, path))\n paths.append(classpaths)\n\n # save the images in the paths\n count = 0\n filenames = []\n for test_images in _generate_test_images():\n for im in test_images:\n # rotate image class\n im_class = count % num_classes\n # rotate subfolders\n classpaths = paths[im_class]\n filename = os.path.join(classpaths[count % len(classpaths)],\n 'image-{}.jpg'.format(count))\n filenames.append(filename)\n im.save(os.path.join(temp_dir, filename))\n count += 1\n\n # Test image loading util\n fname = os.path.join(temp_dir, filenames[0])\n _ = keras.preprocessing.image.load_img(fname)\n _ = keras.preprocessing.image.load_img(fname, grayscale=True)\n _ = keras.preprocessing.image.load_img(fname, target_size=(10, 10))\n _ = keras.preprocessing.image.load_img(fname, target_size=(10, 10),\n interpolation='bilinear')\n\n # create iterator\n generator = keras.preprocessing.image.ImageDataGenerator()\n dir_iterator = generator.flow_from_directory(temp_dir)\n\n # check number of classes and images\n self.assertEqual(len(dir_iterator.class_indices), num_classes)\n self.assertEqual(len(dir_iterator.classes), count)\n self.assertEqual(set(dir_iterator.filenames), set(filenames))\n\n def preprocessing_function(x):\n \"\"\"This will fail if not provided by a Numpy array.\n\n Note: This is made to enforce backward compatibility.\n\n Args:\n x: A numpy array.\n\n Returns:\n An array of zeros with the same shape as the given array.\n \"\"\"\n self.assertEqual(x.shape, (26, 26, 3))\n self.assertIs(type(x), np.ndarray)\n return np.zeros_like(x)\n\n # Test usage as Sequence\n generator = keras.preprocessing.image.ImageDataGenerator(\n preprocessing_function=preprocessing_function)\n dir_seq = generator.flow_from_directory(\n str(temp_dir),\n target_size=(26, 26),\n color_mode='rgb',\n batch_size=3,\n class_mode='categorical')\n self.assertEqual(len(dir_seq), count // 3 + 1)\n x1, y1 = dir_seq[1]\n self.assertEqual(x1.shape, (3, 26, 26, 3))\n self.assertEqual(y1.shape, (3, num_classes))\n x1, y1 = dir_seq[5]\n self.assertTrue((x1 == 0).all())\n\n def directory_iterator_with_validation_split_test_helper(\n self, validation_split):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n num_classes = 2\n tmp_folder = tempfile.mkdtemp(prefix='test_images')\n\n # create folders and subfolders\n paths = []\n for cl in range(num_classes):\n class_directory = 'class-{}'.format(cl)\n classpaths = [\n class_directory,\n os.path.join(class_directory, 'subfolder-1'),\n os.path.join(class_directory, 'subfolder-2'),\n os.path.join(class_directory, 'subfolder-1', 'sub-subfolder')\n ]\n for path in classpaths:\n os.mkdir(os.path.join(tmp_folder, path))\n paths.append(classpaths)\n\n # save the images in the paths\n count = 0\n filenames = []\n for test_images in _generate_test_images():\n for im in test_images:\n # rotate image class\n im_class = count % num_classes\n # rotate subfolders\n classpaths = paths[im_class]\n filename = os.path.join(classpaths[count % len(classpaths)],\n 'image-{}.jpg'.format(count))\n filenames.append(filename)\n im.save(os.path.join(tmp_folder, filename))\n count += 1\n\n # create iterator\n generator = keras.preprocessing.image.ImageDataGenerator(\n validation_split=validation_split)\n\n with self.assertRaises(ValueError):\n generator.flow_from_directory(tmp_folder, subset='foo')\n\n num_validation = int(count * validation_split)\n num_training = count - num_validation\n train_iterator = generator.flow_from_directory(\n tmp_folder, subset='training')\n self.assertEqual(train_iterator.samples, num_training)\n\n valid_iterator = generator.flow_from_directory(\n tmp_folder, subset='validation')\n self.assertEqual(valid_iterator.samples, num_validation)\n\n # check number of classes and images\n self.assertEqual(len(train_iterator.class_indices), num_classes)\n self.assertEqual(len(train_iterator.classes), num_training)\n self.assertEqual(\n len(set(train_iterator.filenames) & set(filenames)), num_training)\n\n shutil.rmtree(tmp_folder)\n\n def test_directory_iterator_with_validation_split_25_percent(self):\n self.directory_iterator_with_validation_split_test_helper(0.25)\n\n def test_directory_iterator_with_validation_split_40_percent(self):\n self.directory_iterator_with_validation_split_test_helper(0.40)\n\n def test_directory_iterator_with_validation_split_50_percent(self):\n self.directory_iterator_with_validation_split_test_helper(0.50)\n\n def test_img_utils(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n height, width = 10, 8\n\n # Test channels_first data format\n x = np.random.random((3, height, width))\n img = keras.preprocessing.image.array_to_img(\n x, data_format='channels_first')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(\n img, data_format='channels_first')\n self.assertEqual(x.shape, (3, height, width))\n # Test 2D\n x = np.random.random((1, height, width))\n img = keras.preprocessing.image.array_to_img(\n x, data_format='channels_first')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(\n img, data_format='channels_first')\n self.assertEqual(x.shape, (1, height, width))\n\n # Test channels_last data format\n x = np.random.random((height, width, 3))\n img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')\n self.assertEqual(x.shape, (height, width, 3))\n # Test 2D\n x = np.random.random((height, width, 1))\n img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')\n self.assertEqual(img.size, (width, height))\n x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')\n self.assertEqual(x.shape, (height, width, 1))\n\n def test_batch_standardize(self):\n if PIL is None:\n return # Skip test if PIL is not available.\n\n # ImageDataGenerator.standardize should work on batches\n for test_images in _generate_test_images():\n img_list = []\n for im in test_images:\n img_list.append(keras.preprocessing.image.img_to_array(im)[None, ...])\n\n images = np.vstack(img_list)\n generator = keras.preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n samplewise_center=True,\n featurewise_std_normalization=True,\n samplewise_std_normalization=True,\n zca_whitening=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.5,\n zoom_range=0.2,\n channel_shift_range=0.,\n brightness_range=(1, 5),\n fill_mode='nearest',\n cval=0.5,\n horizontal_flip=True,\n vertical_flip=True)\n generator.fit(images, augment=True)\n\n transformed = np.copy(images)\n for i, im in enumerate(transformed):\n transformed[i] = generator.random_transform(im)\n transformed = generator.standardize(transformed)\n\n def test_img_transforms(self):\n x = np.random.random((3, 200, 200))\n _ = keras.preprocessing.image.random_rotation(x, 20)\n _ = keras.preprocessing.image.random_shift(x, 0.2, 0.2)\n _ = keras.preprocessing.image.random_shear(x, 2.)\n _ = keras.preprocessing.image.random_zoom(x, (0.5, 0.5))\n _ = keras.preprocessing.image.apply_channel_shift(x, 2, 2)\n _ = keras.preprocessing.image.apply_affine_transform(x, 2)\n with self.assertRaises(ValueError):\n keras.preprocessing.image.random_zoom(x, (0, 0, 0))\n _ = keras.preprocessing.image.random_channel_shift(x, 2.)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Functional tests for Ftrl operations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.optimizer_v2 import ftrl\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import adagrad\nfrom tensorflow.python.training import gradient_descent\n\n\nclass FtrlOptimizerTest(test.TestCase):\n\n def doTestFtrlwithoutRegularization(self, use_resource=False):\n for dtype in [dtypes.float32]:\n with self.cached_session(use_gpu=True):\n if use_resource:\n var0 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype)\n var1 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype)\n else:\n var0 = variables.Variable([0.0, 0.0], dtype=dtype)\n var1 = variables.Variable([0.0, 0.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllClose([0.0, 0.0], v0_val)\n self.assertAllClose([0.0, 0.0], v1_val)\n\n # Run 3 steps FTRL\n for _ in range(3):\n update.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-2.60260963, -4.29698515]), v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.28432083, -0.56694895]), v1_val)\n\n @test_util.run_deprecated_v1\n def testFtrlWithoutRegularization(self):\n self.doTestFtrlwithoutRegularization(use_resource=False)\n\n @test_util.run_deprecated_v1\n def testResourceFtrlWithoutRegularization(self):\n self.doTestFtrlwithoutRegularization(use_resource=True)\n\n @test_util.run_deprecated_v1\n def testFtrlwithoutRegularization2(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n var0 = variables.Variable([1.0, 2.0], dtype=dtype)\n var1 = variables.Variable([4.0, 3.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 3 steps FTRL\n for _ in range(3):\n update.run()\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-2.55607247, -3.98729396]), v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.28232238, -0.56096673]), v1_val)\n\n @test_util.run_deprecated_v1\n def testMinimizeSparseResourceVariable(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.cached_session(use_gpu=True):\n var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)\n x = constant_op.constant([[4.0], [5.0]], dtype=dtype)\n\n def loss():\n pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x) # pylint: disable=cell-var-from-loop\n return pred * pred\n\n sgd_op = ftrl.Ftrl(1.0).minimize(loss, var_list=[var0])\n variables.global_variables_initializer().run()\n # Fetch params to validate initial values\n self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))\n # Run 1 step of sgd\n sgd_op.run()\n # Validate updated params\n self.assertAllCloseAccordingToType([[0, 1]],\n self.evaluate(var0),\n atol=0.01)\n\n @test_util.run_deprecated_v1\n def testFtrlWithL1(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n var0 = variables.Variable([1.0, 2.0], dtype=dtype)\n var1 = variables.Variable([4.0, 3.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-7.66718769, -10.91273689]), v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.93460727, -1.86147261]), v1_val)\n\n @test_util.run_deprecated_v1\n def testFtrlWithL1_L2(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n var0 = variables.Variable([1.0, 2.0], dtype=dtype)\n var1 = variables.Variable([4.0, 3.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-0.24059935, -0.46829352]), v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.02406147, -0.04830509]), v1_val)\n\n @test_util.run_deprecated_v1\n def testFtrlWithL1_L2_L2Shrinkage(self):\n \"\"\"Test the new FTRL op with support for l2 shrinkage.\n\n The addition of this parameter which places a constant pressure on weights\n towards the origin causes the gradient descent trajectory to differ. The\n weights will tend to have smaller magnitudes with this parameter set.\n \"\"\"\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n var0 = variables.Variable([1.0, 2.0], dtype=dtype)\n var1 = variables.Variable([4.0, 3.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0,\n l2_shrinkage_regularization_strength=0.1)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-0.22578995, -0.44345796]), v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.14378493, -0.13229476]), v1_val)\n\n @test_util.run_deprecated_v1\n def testFtrlWithL1_L2_L2ShrinkageSparse(self):\n \"\"\"Tests the new FTRL op with support for l2 shrinkage on sparse grads.\"\"\"\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n var0 = variables.Variable([[1.0], [2.0]], dtype=dtype)\n var1 = variables.Variable([[4.0], [3.0]], dtype=dtype)\n grads0 = ops.IndexedSlices(\n constant_op.constant([0.1], shape=[1, 1], dtype=dtype),\n constant_op.constant([0]), constant_op.constant([2, 1]))\n grads1 = ops.IndexedSlices(\n constant_op.constant([0.02], shape=[1, 1], dtype=dtype),\n constant_op.constant([1]), constant_op.constant([2, 1]))\n\n opt = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0,\n l2_shrinkage_regularization_strength=0.1)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([[1.0], [2.0]], v0_val)\n self.assertAllCloseAccordingToType([[4.0], [3.0]], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([[-0.22578995], [2.]], v0_val)\n self.assertAllCloseAccordingToType([[4.], [-0.13229476]], v1_val)\n\n @test_util.run_deprecated_v1\n def testFtrlWithL2ShrinkageDoesNotChangeLrSchedule(self):\n \"\"\"Verifies that l2 shrinkage in FTRL does not change lr schedule.\"\"\"\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True) as sess:\n var0 = variables.Variable([1.0, 2.0], dtype=dtype)\n var1 = variables.Variable([1.0, 2.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.1, 0.2], dtype=dtype)\n\n opt0 = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0,\n l2_shrinkage_regularization_strength=0.1)\n opt1 = ftrl.Ftrl(\n 3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0)\n update0 = opt0.apply_gradients([(grads0, var0)])\n update1 = opt1.apply_gradients([(grads1, var1)])\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([1.0, 2.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update0.run()\n update1.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n # var0 is experiencing L2 shrinkage so it should be smaller than var1\n # in magnitude.\n self.assertTrue((v0_val**2 < v1_val**2).all())\n accum0 = sess.run(opt0.get_slot(var0, \"accumulator\"))\n accum1 = sess.run(opt1.get_slot(var1, \"accumulator\"))\n # L2 shrinkage should not change how we update grad accumulator.\n self.assertAllCloseAccordingToType(accum0, accum1)\n\n def applyOptimizer(self, opt, dtype, steps=5, is_sparse=False):\n if is_sparse:\n var0 = variables.Variable([[0.0], [0.0]], dtype=dtype)\n var1 = variables.Variable([[0.0], [0.0]], dtype=dtype)\n grads0 = ops.IndexedSlices(\n constant_op.constant([0.1], shape=[1, 1], dtype=dtype),\n constant_op.constant([0]), constant_op.constant([2, 1]))\n grads1 = ops.IndexedSlices(\n constant_op.constant([0.02], shape=[1, 1], dtype=dtype),\n constant_op.constant([1]), constant_op.constant([2, 1]))\n else:\n var0 = variables.Variable([0.0, 0.0], dtype=dtype)\n var1 = variables.Variable([0.0, 0.0], dtype=dtype)\n grads0 = constant_op.constant([0.1, 0.2], dtype=dtype)\n grads1 = constant_op.constant([0.01, 0.02], dtype=dtype)\n\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n if is_sparse:\n self.assertAllCloseAccordingToType([[0.0], [0.0]], v0_val)\n self.assertAllCloseAccordingToType([[0.0], [0.0]], v1_val)\n else:\n self.assertAllCloseAccordingToType([0.0, 0.0], v0_val)\n self.assertAllCloseAccordingToType([0.0, 0.0], v1_val)\n\n # Run Ftrl for a few steps\n for _ in range(steps):\n update.run()\n\n v0_val, v1_val = self.evaluate([var0, var1])\n return v0_val, v1_val\n\n # When variables are initialized with Zero, FTRL-Proximal has two properties:\n # 1. Without L1&L2 but with fixed learning rate, FTRL-Proximal is identical\n # with GradientDescent.\n # 2. Without L1&L2 but with adaptive learning rate, FTRL-Proximal is identical\n # with Adagrad.\n # So, basing on these two properties, we test if our implementation of\n # FTRL-Proximal performs same updates as Adagrad or GradientDescent.\n @test_util.run_deprecated_v1\n def testEquivAdagradwithoutRegularization(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n val0, val1 = self.applyOptimizer(\n ftrl.Ftrl(\n 3.0,\n # Adagrad learning rate\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype)\n\n with self.cached_session(use_gpu=True):\n val2, val3 = self.applyOptimizer(\n adagrad.AdagradOptimizer(3.0, initial_accumulator_value=0.1), dtype)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n @test_util.run_deprecated_v1\n def testEquivSparseAdagradwithoutRegularization(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session():\n val0, val1 = self.applyOptimizer(\n ftrl.Ftrl(\n 3.0,\n # Adagrad learning rate\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype,\n is_sparse=True)\n\n with self.cached_session():\n val2, val3 = self.applyOptimizer(\n adagrad.AdagradOptimizer(3.0, initial_accumulator_value=0.1),\n dtype,\n is_sparse=True)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n @test_util.run_deprecated_v1\n def testEquivSparseGradientDescentwithoutRegularization(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n val0, val1 = self.applyOptimizer(\n ftrl.Ftrl(\n 3.0,\n # Fixed learning rate\n learning_rate_power=-0.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype,\n is_sparse=True)\n\n with self.cached_session(use_gpu=True):\n val2, val3 = self.applyOptimizer(\n gradient_descent.GradientDescentOptimizer(3.0),\n dtype,\n is_sparse=True)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n @test_util.run_deprecated_v1\n def testEquivGradientDescentwithoutRegularization(self):\n for dtype in [dtypes.half, dtypes.float32]:\n with self.cached_session(use_gpu=True):\n val0, val1 = self.applyOptimizer(\n ftrl.Ftrl(\n 3.0,\n # Fixed learning rate\n learning_rate_power=-0.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype)\n\n with self.cached_session(use_gpu=True):\n val2, val3 = self.applyOptimizer(\n gradient_descent.GradientDescentOptimizer(3.0), dtype)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for Keras Premade WideNDeep models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.feature_column import dense_features_v2\nfrom tensorflow.python.feature_column import feature_column_v2 as fc\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine import input_layer\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.optimizer_v2 import gradient_descent\nfrom tensorflow.python.keras.premade import linear\nfrom tensorflow.python.keras.premade import wide_deep\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass WideDeepModelTest(keras_parameterized.TestCase):\n\n def test_wide_deep_model(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n linear_inp = np.random.uniform(low=-5, high=5, size=(64, 2))\n dnn_inp = np.random.uniform(low=-5, high=5, size=(64, 3))\n inputs = [linear_inp, dnn_inp]\n output = .3 * linear_inp[:, 0] + .2 * dnn_inp[:, 1]\n wide_deep_model.compile(\n optimizer=['sgd', 'adam'],\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n wide_deep_model.fit(inputs, output, epochs=5)\n self.assertTrue(wide_deep_model.built)\n\n def test_wide_deep_model_backprop(self):\n with self.cached_session():\n linear_model = linear.LinearModel(units=1, kernel_initializer='zeros')\n dnn_model = sequential.Sequential(\n [core.Dense(units=1, kernel_initializer='zeros')])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n linear_inp = np.array([1.])\n dnn_inp = np.array([1.])\n inputs = [linear_inp, dnn_inp]\n output = linear_inp + 2 * dnn_inp\n linear_opt = gradient_descent.SGD(learning_rate=.1)\n dnn_opt = gradient_descent.SGD(learning_rate=.3)\n wide_deep_model.compile(\n optimizer=[linear_opt, dnn_opt],\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n self.evaluate(variables.global_variables_initializer())\n wide_deep_model.fit(inputs, output, epochs=1)\n self.assertAllClose(\n [[0.3]],\n self.evaluate(wide_deep_model.linear_model.dense_layers[0].kernel))\n self.assertAllClose([[0.9]],\n self.evaluate(\n wide_deep_model.dnn_model.layers[0].kernel))\n\n def test_wide_deep_model_with_single_input(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n inputs = np.random.uniform(low=-5, high=5, size=(64, 3))\n output = .3 * inputs[:, 0]\n wide_deep_model.compile(\n optimizer=['sgd', 'adam'],\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n wide_deep_model.fit(inputs, output, epochs=5)\n\n def test_wide_deep_model_with_multi_outputs(self):\n with context.eager_mode():\n inp = input_layer.Input(shape=(1,), name='linear')\n l = linear.LinearModel(units=2, use_bias=False)(inp)\n l1, l2 = array_ops.split(l, num_or_size_splits=2, axis=1)\n linear_model = training.Model(inp, [l1, l2])\n linear_model.set_weights([np.asarray([[0.5, 0.3]])])\n h = core.Dense(units=2, use_bias=False)(inp)\n h1, h2 = array_ops.split(h, num_or_size_splits=2, axis=1)\n dnn_model = training.Model(inp, [h1, h2])\n dnn_model.set_weights([np.asarray([[0.1, -0.5]])])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n inp_np = np.asarray([[1.]])\n out1, out2 = wide_deep_model(inp_np)\n # output should be 0.5 * (0.5 + 0.1), and 0.5 * (0.3 - 0.5)\n self.assertAllClose([[0.3]], out1)\n self.assertAllClose([[-0.1]], out2)\n\n wide_deep_model = wide_deep.WideDeepModel(\n linear_model, dnn_model, activation='relu')\n out1, out2 = wide_deep_model(inp_np)\n # output should be relu(0.5 * (0.5 + 0.1)), and relu(0.5 * (0.3 - 0.5))\n self.assertAllClose([[0.3]], out1)\n self.assertAllClose([[0.]], out2)\n\n def test_wide_deep_model_with_single_optimizer(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n linear_inp = np.random.uniform(low=-5, high=5, size=(64, 2))\n dnn_inp = np.random.uniform(low=-5, high=5, size=(64, 3))\n inputs = [linear_inp, dnn_inp]\n output = .3 * linear_inp[:, 0] + .2 * dnn_inp[:, 1]\n wide_deep_model.compile(\n optimizer='sgd',\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n wide_deep_model.fit(inputs, output, epochs=5)\n self.assertTrue(wide_deep_model.built)\n\n def test_wide_deep_model_as_layer(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1)])\n linear_input = input_layer.Input(shape=(3,), name='linear')\n dnn_input = input_layer.Input(shape=(5,), name='dnn')\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n wide_deep_output = wide_deep_model((linear_input, dnn_input))\n input_b = input_layer.Input(shape=(1,), name='b')\n output_b = core.Dense(units=1)(input_b)\n model = training.Model(\n inputs=[linear_input, dnn_input, input_b],\n outputs=[wide_deep_output + output_b])\n linear_input_np = np.random.uniform(low=-5, high=5, size=(64, 3))\n dnn_input_np = np.random.uniform(low=-5, high=5, size=(64, 5))\n input_b_np = np.random.uniform(low=-5, high=5, size=(64,))\n output_np = linear_input_np[:, 0] + .2 * dnn_input_np[:, 1] + input_b_np\n model.compile(\n optimizer='sgd',\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model.fit([linear_input_np, dnn_input_np, input_b_np], output_np, epochs=5)\n\n def test_wide_deep_model_with_sub_model_trained(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(\n linear.LinearModel(units=1),\n sequential.Sequential([core.Dense(units=1, input_dim=3)]))\n linear_inp = np.random.uniform(low=-5, high=5, size=(64, 2))\n dnn_inp = np.random.uniform(low=-5, high=5, size=(64, 3))\n inputs = [linear_inp, dnn_inp]\n output = .3 * linear_inp[:, 0] + .2 * dnn_inp[:, 1]\n linear_model.compile(\n optimizer='sgd',\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n dnn_model.compile(\n optimizer='adam',\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n linear_model.fit(linear_inp, output, epochs=50)\n dnn_model.fit(dnn_inp, output, epochs=50)\n wide_deep_model.compile(\n optimizer=['sgd', 'adam'],\n loss='mse',\n metrics=[],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n wide_deep_model.fit(inputs, output, epochs=50)\n\n # This test is an example for cases where linear and dnn model accepts\n # same raw input and same transformed inputs, i.e., the raw input is\n # categorical, and both linear and dnn model accept one hot encoding.\n def test_wide_deep_model_with_single_feature_column(self):\n vocab_list = ['alpha', 'beta', 'gamma']\n vocab_val = [0.4, 0.6, 0.9]\n data = np.random.choice(vocab_list, size=256)\n y = np.zeros_like(data, dtype=np.float32)\n for vocab, val in zip(vocab_list, vocab_val):\n indices = np.where(data == vocab)\n y[indices] = val + np.random.uniform(\n low=-0.01, high=0.01, size=indices[0].shape)\n cat_column = fc.categorical_column_with_vocabulary_list(\n key='symbol', vocabulary_list=vocab_list)\n ind_column = fc.indicator_column(cat_column)\n dense_feature_layer = dense_features_v2.DenseFeatures([ind_column])\n linear_model = linear.LinearModel(\n use_bias=False, kernel_initializer='zeros')\n dnn_model = sequential.Sequential([core.Dense(units=1)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n combined = sequential.Sequential([dense_feature_layer, wide_deep_model])\n opt = gradient_descent.SGD(learning_rate=0.1)\n combined.compile(\n opt,\n 'mse', [],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n combined.fit(x={'symbol': data}, y=y, batch_size=32, epochs=10)\n\n # This test is an example for cases where linear and dnn model accepts\n # same raw input but different transformed inputs, i.e,. the raw input is\n # categorical, and linear model accepts one hot encoding, while dnn model\n # accepts embedding encoding.\n def test_wide_deep_model_with_two_feature_columns(self):\n vocab_list = ['alpha', 'beta', 'gamma']\n vocab_val = [0.4, 0.6, 0.9]\n data = np.random.choice(vocab_list, size=256)\n y = np.zeros_like(data, dtype=np.float32)\n for vocab, val in zip(vocab_list, vocab_val):\n indices = np.where(data == vocab)\n y[indices] = val + np.random.uniform(\n low=-0.01, high=0.01, size=indices[0].shape)\n cat_column = fc.categorical_column_with_vocabulary_list(\n key='symbol', vocabulary_list=vocab_list)\n ind_column = fc.indicator_column(cat_column)\n emb_column = fc.embedding_column(cat_column, dimension=5)\n linear_feature_layer = dense_features_v2.DenseFeatures([ind_column])\n linear_model = linear.LinearModel(\n use_bias=False, kernel_initializer='zeros')\n combined_linear = sequential.Sequential(\n [linear_feature_layer, linear_model])\n dnn_model = sequential.Sequential([core.Dense(units=1)])\n dnn_feature_layer = dense_features_v2.DenseFeatures([emb_column])\n combined_dnn = sequential.Sequential([dnn_feature_layer, dnn_model])\n wide_deep_model = wide_deep.WideDeepModel(combined_linear, combined_dnn)\n opt = gradient_descent.SGD(learning_rate=0.1)\n wide_deep_model.compile(\n opt,\n 'mse', [],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n wide_deep_model.fit(x={'symbol': data}, y=y, batch_size=32, epochs=10)\n self.assertEqual(3, linear_model.inputs[0].shape[1])\n self.assertEqual(5, dnn_model.inputs[0].shape[1])\n\n def test_config(self):\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n config = wide_deep_model.get_config()\n cloned_wide_deep_model = wide_deep.WideDeepModel.from_config(config)\n self.assertEqual(linear_model.units,\n cloned_wide_deep_model.linear_model.units)\n self.assertEqual(dnn_model.layers[0].units,\n cloned_wide_deep_model.dnn_model.layers[0].units)\n\n def test_config_with_custom_objects(self):\n\n def my_activation(x):\n return x\n\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1, input_dim=3)])\n wide_deep_model = wide_deep.WideDeepModel(\n linear_model, dnn_model, activation=my_activation)\n config = wide_deep_model.get_config()\n cloned_wide_deep_model = wide_deep.WideDeepModel.from_config(\n config, custom_objects={'my_activation': my_activation})\n self.assertEqual(cloned_wide_deep_model.activation, my_activation)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=unidiomatic-typecheck\n\"\"\"Prototype decorator for defining legacy-graph-mode functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport weakref\n\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.core.protobuf import struct_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.eager import lift_to_graph\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import func_graph\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.saved_model import nested_structure_coder\nfrom tensorflow.python.training.tracking import data_structures\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import tf_export\n\n\nclass VariableHolder(object):\n \"\"\"Holds variables for a python function.\"\"\"\n\n def __init__(self, fn=None, share_variables=False):\n self._fn = fn\n\n self._share_variables = share_variables\n self._variables_by_name = data_structures.Mapping()\n\n @property\n def variables(self):\n return self._variables_by_name\n\n def variable_creator_scope(self, next_creator, **kwargs):\n \"\"\"Creates variables & adds them to collections to match legacy code.\"\"\"\n collections = kwargs.pop(\"collections\", None)\n v = None\n\n # Get expected variable name.\n with ops.name_scope(kwargs.get(\"name\", None), \"Variable\") as name:\n variable_name = ops.name_from_scope_name(name)\n kwargs[\"name\"] = name\n\n if self._share_variables:\n v = self._variables_by_name.get(variable_name, None)\n\n if v is None:\n v = next_creator(**kwargs)\n self._variables_by_name[variable_name] = v\n\n if collections is None:\n collections = [ops.GraphKeys.GLOBAL_VARIABLES]\n if v.trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections:\n collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES]\n\n ops.add_to_collections(collections, v)\n\n return v\n\n def __call__(self, *args, **kwargs):\n return self.call_with_variable_creator_scope(self._fn)(*args, **kwargs)\n\n def call_with_variable_creator_scope(self, fn):\n\n def wrapped(*args, **kwargs):\n with variable_scope.variable_creator_scope(self.variable_creator_scope):\n return fn(*args, **kwargs)\n\n return wrapped\n\n\ndef _get_element_from_tensor_info(tensor_info, graph):\n \"\"\"Simplified copy of the deprecated `get_tensor_from_tensor_info`.\"\"\"\n encoding = tensor_info.WhichOneof(\"encoding\")\n if encoding == \"name\":\n # We may get operations here in some cases. TensorInfo is a bit of a\n # misnomer if so.\n return graph.as_graph_element(tensor_info.name)\n elif encoding == \"coo_sparse\":\n return sparse_tensor.SparseTensor(\n graph.get_tensor_by_name(tensor_info.coo_sparse.indices_tensor_name),\n graph.get_tensor_by_name(tensor_info.coo_sparse.values_tensor_name),\n graph.get_tensor_by_name(\n tensor_info.coo_sparse.dense_shape_tensor_name))\n elif encoding == \"composite_tensor\":\n struct_coder = nested_structure_coder.StructureCoder()\n spec_proto = struct_pb2.StructuredValue(\n type_spec_value=tensor_info.composite_tensor.type_spec)\n spec = struct_coder.decode_proto(spec_proto)\n components = [graph.get_tensor_by_name(component.name) for component in\n tensor_info.composite_tensor.components]\n return spec._from_components(components) # pylint: disable=protected-access\n else:\n raise ValueError(\"Invalid TensorInfo.encoding: %s\" % encoding)\n\n\ndef _lift_single_variable(old_variable, graph, variable_holder):\n \"\"\"Lifts `old_variable` out of the `FuncGraph` `graph`.\"\"\"\n new_variable = resource_variable_ops.UninitializedVariable(\n shape=old_variable.shape,\n dtype=old_variable.dtype,\n name=old_variable.op.name,\n trainable=old_variable.trainable,\n extra_handle_data=old_variable.handle)\n new_variable._initializer_op = old_variable._initializer_op # pylint: disable=protected-access\n graph.add_capture(new_variable.handle, old_variable.handle)\n # Now that we've added the new variable to graph.captures,\n # graph.capture will use that cached value and do some post-processing\n # on the capture like recording it on the tape.\n graph.capture(new_variable.handle)\n # pylint: disable=protected-access\n variable_name = new_variable.name.split(\":\")[0]\n variable_holder._variables_by_name[variable_name] = new_variable\n graph._weak_variables.append(weakref.ref(new_variable))\n # pylint: enable=protected-access\n graph.watch_variable(new_variable)\n return new_variable\n\n\ndef _lift_unlifted_variables(graph, variable_holder):\n \"\"\"Finds resource variables and lifts them into the outer context.\n\n When we import a GraphDef inside a wrap_function, no Python graph building\n code runs. This means we get VarHandleOps which create variable resources,\n but no corresponding Python objects. Leaving them like this works but gives\n the user no way to interact with or modify the variables outside the graph.\n\n This method searches for variables and lifts them out as regular variable\n objects when possible, indicating to the FuncGraph that they are captures.\n\n Args:\n graph: The FuncGraph to lift variables from.\n variable_holder: A VariableHolder to record the lifted variables in.\n \"\"\"\n with graph.as_default():\n global_collection_variables = ops.get_collection(\n ops.GraphKeys.GLOBAL_VARIABLES)\n local_collection_variables = ops.get_collection(\n ops.GraphKeys.LOCAL_VARIABLES)\n existing_captures = {id(c) for c in graph.internal_captures}\n lifted_variables = {}\n\n def _should_lift_variable(v):\n return ((v._in_graph_mode # pylint: disable=protected-access\n and v.graph.building_function)\n and isinstance(v, resource_variable_ops.BaseResourceVariable)\n and id(v.handle) not in existing_captures)\n\n for old_variable in global_collection_variables:\n if _should_lift_variable(old_variable):\n new_variable = _lift_single_variable(\n old_variable, graph, variable_holder)\n lifted_variables[id(old_variable)] = new_variable\n existing_captures.add(id(old_variable.handle))\n\n for old_variable in local_collection_variables:\n if _should_lift_variable(old_variable):\n new_variable = _lift_single_variable(\n old_variable, graph, variable_holder)\n lifted_variables[id(old_variable)] = new_variable\n existing_captures.add(id(old_variable.handle))\n if new_variable._in_graph_mode: # pylint: disable=protected-access\n outer_graph = new_variable.graph\n # Variables are added to the global collection by default. In this\n # case we only want the variable in the local collection, so we'll pop\n # it out.\n global_collection = outer_graph.get_collection_ref(\n ops.GraphKeys.GLOBAL_VARIABLES)\n global_collection.remove(new_variable)\n outer_graph.add_to_collection(\n ops.GraphKeys.LOCAL_VARIABLES, new_variable)\n\n # Update the FuncGraph's collections, partly for the user and partly so this\n # function is idempotent when it runs again in prune() calls.\n for collection_name in [\n ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.LOCAL_VARIABLES\n ]:\n mutable_collection = ops.get_collection_ref(collection_name)\n for index, current in enumerate(mutable_collection):\n mutable_collection[index] = lifted_variables.get(id(current), current)\n if not resource_variable_ops.is_resource_variable(\n mutable_collection[index]):\n logging.log_first_n(\n logging.WARN,\n \"Unable to create a python object for variable {} because it is \"\n \"a reference variable. It may not be visible to training APIs. \"\n \"If this is a problem, consider rebuilding the SavedModel after \"\n \"running tf.compat.v1.enable_resource_variables().\".format(\n mutable_collection[index]),\n 5)\n\n\n# TODO(allenl): make this trackable\nclass WrappedFunction(function.ConcreteFunction):\n \"\"\"Wraps a tf V1 piece of code in a function.\"\"\"\n\n def __init__(self, fn_graph, variable_holder, attrs=None, signature=None):\n self._variable_holder = variable_holder\n _lift_unlifted_variables(fn_graph, variable_holder)\n # We call __init__ after lifting variables so that the function's signature\n # properly reflects the new captured inputs.\n for f in fn_graph.as_graph_def().library.function:\n context.context().add_function_def(f)\n super(WrappedFunction, self).__init__(\n fn_graph, attrs=attrs, signature=signature)\n\n def prune(self, feeds, fetches, name=None, input_signature=None):\n \"\"\"Extract a subgraph of this function's underlying graph.\n\n Wraps the subgraph in a new `WrappedFunction` object.\n\n Args:\n feeds: Input tensors to the subgraph to extract, as `Tensor` objects.\n fetches: Possibly-nested Python data structure containing information\n about outputs of the target subgraph. Each entry can either be a\n `Tensor` object (for data outputs), an `Operation` object (for control\n outputs), or a `TensorInfo` proto. Any additional shape/dtype\n information provided in a `TensorInfo` and not present in the original\n graph will be added to the returned subgraph.\n name: (optional) Name to give to the underlying `FuncGraph` of the\n returned object. If no name is provided, the graph's name will be\n `\"pruned\"`.\n input_signature: (optional) possibly-nested Python data structure\n containing `TensorSpec` objects, with which to populate the returned\n functions's `FuncGraph`'s `structured_input_signature` field.\n\n Returns:\n A new `WrappedFunction` object containing a copy of the portion of this\n object's graph that goes from `feeds` to `fetches`.\n \"\"\"\n # TODO(b/129646028): Add support for CompositeTensors.\n name = name or \"pruned\"\n flat_feeds = nest.flatten(feeds, expand_composites=True)\n flat_feeds = [self.graph.as_graph_element(t) for t in flat_feeds]\n for f in flat_feeds:\n if not isinstance(f, ops.Tensor):\n raise ValueError(\"Feeds must be tensors.\")\n\n # Ignoring all feeds that are captures allows prune to be called\n # using wrapped_func.inputs even when it uses variables\n internal_captures = {id(c) for c in self.graph.internal_captures}\n flat_feeds = [f for f in flat_feeds if id(f) not in internal_captures]\n\n operation_fetches = []\n tensor_fetches = []\n tensor_infos = []\n\n def _fetch_preprocesing_callback(fetch):\n \"\"\"Extract out lists of ops, tensors, and tensor type info.\n\n Turns TensorInfos into Tensors in the original `fetches` structure.\n Also extracts ops from `fetches`.\n\n Args:\n fetch: The fetch to preprocess: Tensor, TensorInfo, or Operation, or\n string identifying a Tensor or Operation.\n\n Returns:\n `fetch` converted to a Tensor.\n \"\"\"\n if isinstance(fetch, ops.Operation):\n operation_fetches.append(fetch)\n return fetch\n elif isinstance(fetch, meta_graph_pb2.TensorInfo):\n tensor_infos.append(fetch)\n decoded = _get_element_from_tensor_info(fetch, self._func_graph)\n if (tensor_util.is_tensor(decoded) or\n isinstance(decoded, composite_tensor.CompositeTensor)):\n tensor_fetches.append(decoded)\n else:\n operation_fetches.append(decoded)\n return decoded\n elif isinstance(fetch, (ops.Tensor, composite_tensor.CompositeTensor)):\n tensor_fetches.append(fetch)\n return fetch\n else:\n graph_element = self.graph.as_graph_element(fetch)\n return _fetch_preprocesing_callback(graph_element)\n\n fetches = nest.map_structure(_fetch_preprocesing_callback, fetches)\n\n # Expand composite tensors into their component dense Tensors.\n tensor_fetches = nest.flatten(tensor_fetches, expand_composites=True)\n\n for f in (flat_feeds + tensor_fetches + operation_fetches):\n if f.graph is not self._func_graph:\n raise ValueError(\"Can only prune function whose feeds and fetches \"\n \"are from this graph (%s). Input %s is from graph %s\" %\n (self._func_graph, f, f.graph))\n with self._func_graph.as_default():\n pruned_graph = func_graph.FuncGraph(name)\n lift_map = lift_to_graph.lift_to_graph(\n operation_fetches + tensor_fetches,\n pruned_graph,\n sources=flat_feeds + self.graph.internal_captures)\n\n # Note that we add the component tensors of any composite tensors to the\n # returned function's outputs list; the list must contain these component\n # tensors, or the function's sparse outputs won't work properly.\n pruned_graph.outputs.extend(lift_map[x] for x in tensor_fetches)\n pruned_graph.control_outputs.extend(\n [lift_map[operation] for operation in operation_fetches])\n pruned_graph.inputs.extend(lift_map[x] for x in flat_feeds)\n for external_capture, internal_capture in self.graph.captures:\n pruned_graph.add_capture(external_capture, lift_map[internal_capture])\n for ti in tensor_infos:\n if ti.WhichOneof(\"encoding\") == \"name\": # Dense tensors only\n t = pruned_graph.as_graph_element(ti.name)\n if tensor_util.is_tensor(t):\n t.set_shape(tensor_shape.TensorShape(ti.tensor_shape))\n # pylint: disable=protected-access\n for f in self.graph._functions.values():\n pruned_graph._add_function(f)\n # pylint: enable=protected-access\n\n pruned_graph.variables = self.graph.variables\n\n def _structured_output_mapping(fetched):\n \"\"\"callback for `nest.map_structure()`\"\"\"\n lifted = lift_map[fetched]\n if isinstance(lifted, ops.Operation):\n return None\n return lifted\n\n # expand_composites=True here causes composite tensors to be expanded\n # into their component dense Tensors, mapped to the new graph, and then\n # reconstituted into their original composite form.\n pruned_graph.structured_outputs = nest.map_structure(\n _structured_output_mapping, fetches, expand_composites=True)\n pruned_graph.structured_input_signature = input_signature\n pruned_fn = WrappedFunction(\n pruned_graph, variable_holder=self._variable_holder)\n pruned_fn._num_positional_args = len(flat_feeds) # pylint: disable=protected-access\n # TODO(kathywu): Enable keyword arguments if an input signature is specified\n pruned_fn._arg_keywords = [tensor.op.name for tensor in flat_feeds] # pylint: disable=protected-access\n return pruned_fn\n\n\ndef _filter_returned_ops(fn):\n \"\"\"Filtering out any ops returned by function.\n\n Args:\n fn: a function\n\n Returns:\n A tuple of (\n Wrapped function that returns `None` in place of any ops,\n dict that maps the index in the flat output structure to the returned op\n )\n \"\"\"\n returned_ops = {}\n\n def wrap_and_filter_returned_ops(*args, **kwargs):\n outputs = fn(*args, **kwargs)\n flat_outputs = nest.flatten(outputs)\n for n in range(len(flat_outputs)):\n output = flat_outputs[n]\n if isinstance(output, ops.Operation):\n returned_ops[n] = output\n flat_outputs[n] = None\n return nest.pack_sequence_as(outputs, flat_outputs)\n\n return wrap_and_filter_returned_ops, returned_ops\n\n\nclass WrappedGraph(object):\n \"\"\"Class for wrapping multiple TF 1.X functions in a single graph.\n\n Maintains a dictionary mapping names to wrapped functions. See\n `tf.compat.v1.wrap_function` to learn more about wrapping V1 functions.\n\n Functions wrapped using this class have access to variables and collections\n created in other wrapped functions, using the standard TF 1.X API (\n `tf.compat.v1.get_variable` or\n `tf.compat.v1.get_default_graph().get_collection(...)`)\n\n Outside a function, variables and collections may be accessed using the\n `variables` and `graph` properties.\n\n Example:\n\n ```\n def add_v1(x):\n with tf.compat.v1.variable_scope('vars', reuse=tf.compat.v1.AUTO_REUSE):\n v = tf.compat.v1.get_variable('v', shape=[], dtype=tf.int32)\n return v + x\n\n def increment_var_v1(x):\n with tf.compat.v1.variable_scope('vars', reuse=tf.compat.v1.AUTO_REUSE):\n v = tf.compat.v1.get_variable('v', shape=[], dtype=tf.int32)\n return v.assign_add(x)\n\n g = WrappedGraph()\n add = g.wrap_function(add_v1, [tf.TensorSpec([], tf.int32)])\n increment_var = g.wrap_function(increment_var_v1,\n [tf.TensorSpec([], tf.int32)])\n\n assert len(g.variables) == 1\n assert g.variables[0].numpy() == 0\n increment_var(tf.constant(5))\n assert g.variables[0].numpy() == 5\n\n ```\n \"\"\"\n\n def __init__(self, variable_holder=None, **kwargs):\n self._variable_holder = (\n variable_holder or VariableHolder(share_variables=True))\n\n name = kwargs.pop(\"name\", \"wrapped_function_graph\")\n # Always start with empty collections, unless otherwise specified. Setting\n # `collections=None` will copy the collections from the outer graph.\n collections = kwargs.pop(\"collections\", {})\n self.graph = func_graph.FuncGraph(name, collections=collections, **kwargs)\n\n self._wrapped_function = WrappedFunction(self.graph, self._variable_holder)\n self._functions = {}\n\n @property\n def functions(self):\n return self._functions\n\n @property\n def variables(self):\n return self._variable_holder.variables\n\n def wrap_function(self, fn, signature, name=None):\n \"\"\"Wraps a TF 1.X function and returns an eager-compatible function.\n\n All functions wrapped in the same `WrappedGraph` will have access to the\n same graph (`tf.compat.v1.get_default_graph` to get the graph object\n within a function, or `WrappedGraph.graph` to get the graph outside a\n function). Variables created within the function will be added to the\n `variables` list.\n\n Function inputs: All inputs to the function must be tensors (nested ok),\n with their shapes and dtypes defined in the `signature` argument.\n\n Function outputs:\n\n * The 1.X function may return tensors, variables, and ops. The wrapped\n eager-compatible function will always return tensors in the same nested\n structure.\n * Variables are replaced with a tensor containing the latest read values.\n * Returned ops are executed, and replaced with None.\n * The order of op execution and variable reads in the return is\n nondeterministic. For example:\n\n ```\n def update_var(x):\n v = tf.Variable(0)\n op = tf.compat.v1.assign(v, x).op\n return v, op\n\n g = WrappedGraph()\n fn = g.wrap_function(update_var)\n read_value, _ = fn(tf.constant(3))\n print(read_value.numpy()) # could be 0 or 3\n print(g.variables[0].numpy()) # always 3\n ```\n\n To ensure that ops in the function are executed (e.g. ops added to the\n `tf.GraphKeys.UPDATE_OPS` collection), include them in the function returns.\n\n Args:\n fn: a 1.X tensorflow function.\n signature: a possibly nested sequence of `TensorSpecs` specifying the\n shapes and dtypes of the arguments.\n name: an optional string name for the function. The function will be saved\n with key `name` in the `functions` dictionary.\n\n Returns:\n An eager-compatible function.\n \"\"\"\n return self._wrap_function(fn, signature=signature, name=name)\n\n def _wrap_function(self,\n fn,\n args=None,\n kwargs=None,\n signature=None,\n name=None):\n \"\"\"Internal wrap function method with extended func_graph arguments.\"\"\"\n fn_with_filter_and_scope, returned_ops = _filter_returned_ops(\n self._variable_holder.call_with_variable_creator_scope(fn))\n\n func_graph.func_graph_from_py_func(\n None, # Name is unused.\n fn_with_filter_and_scope,\n args=args,\n kwargs=kwargs,\n signature=signature,\n add_control_dependencies=False,\n func_graph=self.graph)\n\n # This code relies on questional behavior from `func_graph_from_py_func`.\n # If an existing FuncGraph is passed into the `func_graph` arg, the inputs\n # and structured outputs are overwritten. Pretty sure this is a bug,\n # because structured outputs doesn't match up with the outputs...\n fn_inputs = self.graph.inputs[:-len(self.graph.captures)]\n\n # Return filtered ops to the flattened outputs.\n flat_fn_outputs = nest.flatten(self.graph.structured_outputs)\n for index, op in returned_ops.items():\n flat_fn_outputs[index] = op\n fn_outputs = nest.pack_sequence_as(self.graph.structured_outputs,\n flat_fn_outputs)\n\n name = name or fn.__name__\n wrapped_function = self._wrapped_function.prune(\n fn_inputs, fn_outputs, name, self.graph.structured_input_signature)\n self._functions[name] = wrapped_function\n return wrapped_function\n\n\n@tf_export(v1=[\"wrap_function\"])\ndef wrap_function(fn, signature, name=None):\n \"\"\"Wraps the TF 1.x function fn into a graph function.\n\n The python function `fn` will be called once with symbolic arguments specified\n in the `signature`, traced, and turned into a graph function. Any variables\n created by `fn` will be owned by the object returned by `wrap_function`. The\n resulting graph function can be called with tensors which match the\n signature.\n\n ```python\n def f(x, do_add):\n v = tf.Variable(5.0)\n if do_add:\n op = v.assign_add(x)\n else:\n op = v.assign_sub(x)\n with tf.control_dependencies([op]):\n return v.read_value()\n\n f_add = tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), True])\n\n assert float(f_add(1.0)) == 6.0\n assert float(f_add(1.0)) == 7.0\n\n # Can call tf.compat.v1.wrap_function again to get a new trace, a new set\n # of variables, and possibly different non-template arguments.\n f_sub= tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), False])\n\n assert float(f_sub(1.0)) == 4.0\n assert float(f_sub(1.0)) == 3.0\n ```\n\n Both `tf.compat.v1.wrap_function` and `tf.function` create a callable\n TensorFlow graph. But while `tf.function` runs all stateful operations\n (e.g. `tf.print`) and sequences operations to provide the same semantics as\n eager execution, `wrap_function` is closer to the behavior of `session.run` in\n TensorFlow 1.x. It will not run any operations unless they are required to\n compute the function's outputs, either through a data dependency or a control\n dependency. Nor will it sequence operations.\n\n Unlike `tf.function`, `wrap_function` will only trace the Python function\n once. As with placeholders in TF 1.x, shapes and dtypes must be provided to\n `wrap_function`'s `signature` argument.\n\n Since it is only traced once, variables and state may be created inside the\n function and owned by the function wrapper object.\n\n Args:\n fn: python function to be wrapped\n signature: the placeholder and python arguments to be passed to the wrapped\n function\n name: Optional. The name of the function.\n\n Returns:\n the wrapped graph function.\n \"\"\"\n holder = VariableHolder(fn)\n func_graph_name = \"wrapped_function\"\n if name is not None:\n func_graph_name = \"wrapped_function_\" + name\n return WrappedFunction(\n func_graph.func_graph_from_py_func(\n func_graph_name,\n holder,\n args=None,\n kwargs=None,\n signature=signature,\n add_control_dependencies=False,\n collections={}),\n variable_holder=holder,\n signature=signature)\n\n\ndef function_from_graph_def(graph_def, inputs, outputs):\n \"\"\"Creates a ConcreteFunction from a GraphDef.\n\n Args:\n graph_def: A GraphDef to make a function out of.\n inputs: A Tensor name or nested structure of names in `graph_def` which\n should be inputs to the function.\n outputs: A Tensor name or nested structure of names in `graph_def` which\n should be outputs of the function.\n\n Returns:\n A ConcreteFunction.\n \"\"\"\n\n def _imports_graph_def():\n importer.import_graph_def(graph_def, name=\"\")\n\n wrapped_import = wrap_function(_imports_graph_def, [])\n import_graph = wrapped_import.graph\n return wrapped_import.prune(\n nest.map_structure(import_graph.as_graph_element, inputs),\n nest.map_structure(import_graph.as_graph_element, outputs))\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Benchmarks for `tf.data.experimental.parallel_interleave()`.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.data.experimental.ops import interleave_ops\nfrom tensorflow.python.data.experimental.ops import sleep\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.platform import test\n\n\ndef _make_fake_dataset_fn():\n \"\"\"Returns a dataset that emulates a remote storage data source.\n\n Returns a dataset factory which creates a dataset with 100 elements that\n emulates the performance characteristic of a file-based dataset stored in a\n remote storage. In particular, the first element will take an order of\n magnitude longer to produce than the remaining elements (1s vs. 1ms).\n \"\"\"\n\n def fake_dataset_fn(unused):\n del unused\n\n def make_dataset(time_us, num_elements):\n return dataset_ops.Dataset.range(num_elements).apply(sleep.sleep(time_us))\n\n return make_dataset(1000 * 1000, 0).concatenate(make_dataset(1000,\n 100)).take(100)\n\n return fake_dataset_fn\n\n\nclass ParallelInterleaveBenchmark(test.Benchmark):\n \"\"\"Benchmarks for `tf.data.experimental.parallel_interleave()`.\"\"\"\n\n def _benchmark(self, dataset_fn, iters, num_elements):\n with ops.Graph().as_default():\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n dataset = dataset_fn().with_options(options)\n next_element = dataset_ops.make_one_shot_iterator(dataset).get_next()\n with session.Session() as sess:\n deltas = []\n for _ in range(iters):\n start = time.time()\n for _ in range(num_elements):\n sess.run(next_element.op)\n end = time.time()\n deltas.append(end - start)\n\n mean_wall_time = np.mean(deltas) / num_elements\n self.report_benchmark(iters=iters, wall_time=mean_wall_time)\n\n def benchmark_sequential_interleave(self):\n\n def dataset_fn():\n return dataset_ops.Dataset.range(1).repeat().interleave(\n _make_fake_dataset_fn(), cycle_length=10)\n\n self._benchmark(dataset_fn=dataset_fn, iters=10, num_elements=100)\n\n def benchmark_parallel_interleave_v1(self):\n \"\"\"Benchmark for parallel interleave that does not support autotuning.\"\"\"\n\n def dataset_fn():\n return dataset_ops.Dataset.range(1).repeat().apply(\n interleave_ops.parallel_interleave(\n _make_fake_dataset_fn(), cycle_length=10))\n\n self._benchmark(dataset_fn=dataset_fn, iters=100, num_elements=1000)\n\n def benchmark_parallel_interleave_v2(self):\n \"\"\"Benchmark for parallel interleave that supports autotuning.\"\"\"\n\n def dataset_fn():\n return dataset_ops.Dataset.range(1).repeat().interleave(\n _make_fake_dataset_fn(),\n cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE)\n\n self._benchmark(dataset_fn=dataset_fn, iters=100, num_elements=1000)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for ragged_array_ops.stack_dynamic_partitions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops.ragged import ragged_array_ops\nfrom tensorflow.python.ops.ragged import ragged_concat_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import googletest\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass RaggedSegmentStackOpTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n @parameterized.parameters([\n dict( # empty inputs\n data=[],\n partitions=[],\n num_partitions=0,\n expected=[],\n expected_ragged_rank=1),\n dict( # empty data, num_partitions>0\n data=[],\n partitions=[],\n num_partitions=3,\n expected=[[], [], []]),\n dict( # 1D data, 1D partitions (docstring example)\n data=['a', 'b', 'c', 'd', 'e'],\n partitions=[3, 0, 2, 2, 3],\n num_partitions=5,\n expected=[['b'], [], ['c', 'd'], ['a', 'e'], []]),\n dict( # 2D data, 1D partitions\n data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']],\n data_ragged_rank=0,\n partitions=[2, 1, 2, 3],\n num_partitions=4,\n expected=[[], [['c', 'd']], [['a', 'b'], ['e', 'f']], [['g', 'h']]],\n expected_ragged_rank=1),\n dict( # 2D ragged data, 1D partitions\n data=[['a'], ['b', 'c', 'd'], [], ['e', 'f']],\n data_ragged_rank=1,\n partitions=[2, 1, 2, 3],\n num_partitions=4,\n expected=[[], [['b', 'c', 'd']], [['a'], []], [['e', 'f']]],\n expected_ragged_rank=2),\n dict( # 2D data, 2D partitions\n data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']],\n data_ragged_rank=0,\n partitions=[[3, 0], [2, 2], [4, 3], [2, 0]],\n num_partitions=5,\n expected=[['b', 'h'], [], ['c', 'd', 'g'], ['a', 'f'], ['e']]),\n dict( # 2D ragged data, 2D ragged partitions\n data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']],\n data_ragged_rank=0,\n partitions=[[3, 0], [2, 2], [4, 3], [2, 0]],\n num_partitions=5,\n expected=[['b', 'h'], [], ['c', 'd', 'g'], ['a', 'f'], ['e']]),\n dict( # 3D data, 1d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]],\n data_ragged_rank=0,\n partitions=[1, 0],\n num_partitions=2,\n expected=[[[['e', 'f'], ['g', 'h']]], [[['a', 'b'], ['c', 'd']]]],\n expected_ragged_rank=1),\n dict( # 3D data (ragged_rank=1), 1d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f']]],\n data_ragged_rank=1,\n partitions=[2, 0],\n num_partitions=3,\n expected=[[[['e', 'f']]], [], [[['a', 'b'], ['c', 'd']]]],\n expected_ragged_rank=2),\n dict( # 3D data (ragged_rank=2), 1d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]],\n data_ragged_rank=2,\n partitions=[2, 0],\n num_partitions=3,\n expected=[[[['e', 'f', 'g', 'h']]], [], [[['a', 'b'], ['c', 'd']]]],\n expected_ragged_rank=3),\n dict( # 3D data, 2d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]],\n data_ragged_rank=0,\n partitions=[[1, 0], [0, 3]],\n segment_ids_ragged_rank=0,\n num_partitions=4,\n expected=[[['c', 'd'], ['e', 'f']], [['a', 'b']], [], [['g', 'h']]],\n expected_ragged_rank=1),\n dict( # 3D data (ragged_rank=1), 2d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f']]],\n data_ragged_rank=1,\n partitions=[[1, 0], [0]],\n segment_ids_ragged_rank=1,\n num_partitions=2,\n expected=[[['c', 'd'], ['e', 'f']], [['a', 'b']]],\n expected_ragged_rank=1),\n dict( # 3D data (ragged_rank=2), 2d partitions\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]],\n data_ragged_rank=2,\n partitions=[[1, 0], [0]],\n segment_ids_ragged_rank=1,\n num_partitions=3,\n expected=[[['c', 'd'], ['e', 'f', 'g', 'h']], [['a', 'b']], []],\n expected_ragged_rank=2),\n dict( # 3D data (ragged_rank=2), 3d partitions (ragged_rank=2)\n data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]],\n data_ragged_rank=2,\n partitions=[[[3, 0], [1, 2]], [[1, 1, 0, 1]]],\n segment_ids_ragged_rank=2,\n num_partitions=4,\n expected=[['b', 'g'], ['c', 'e', 'f', 'h'], ['d'], ['a']]),\n dict( # 0D data, 0D partitions\n data='a',\n partitions=3,\n num_partitions=5,\n expected=[[], [], [], ['a'], []]),\n dict( # 1D data, 0D partitions\n data=['a', 'b', 'c'],\n partitions=3,\n num_partitions=5,\n expected=[[], [], [], [['a', 'b', 'c']], []],\n expected_ragged_rank=1),\n dict( # 2D data, 0D partitions\n data=[['a', 'b'], ['c', 'd']],\n data_ragged_rank=0,\n partitions=3,\n num_partitions=5,\n expected=[[], [], [], [[['a', 'b'], ['c', 'd']]], []],\n expected_ragged_rank=1),\n dict( # 2D data (ragged_rank=1), 0D partitions\n data=[['a', 'b'], ['c']],\n data_ragged_rank=1,\n partitions=3,\n num_partitions=5,\n expected=[[], [], [], [[['a', 'b'], ['c']]], []],\n expected_ragged_rank=3),\n ])\n def testRaggedSegmentStack(self,\n data,\n partitions,\n num_partitions,\n expected,\n data_ragged_rank=None,\n segment_ids_ragged_rank=None,\n expected_ragged_rank=None):\n for seg_dtype in [dtypes.int32, dtypes.int64]:\n data_tensor = ragged_factory_ops.constant(\n data, row_splits_dtype=seg_dtype, ragged_rank=data_ragged_rank)\n segment_ids_tensor = ragged_factory_ops.constant(\n partitions,\n dtype=seg_dtype,\n row_splits_dtype=seg_dtype,\n ragged_rank=segment_ids_ragged_rank)\n expected_tensor = ragged_factory_ops.constant(\n expected,\n row_splits_dtype=seg_dtype,\n ragged_rank=expected_ragged_rank)\n result = ragged_array_ops.stack_dynamic_partitions(\n data_tensor, segment_ids_tensor, num_partitions)\n self.assertAllEqual(result, expected_tensor)\n\n # Check that it's equivalent to tf.stack(dynamic_partition(...)),\n # where applicable.\n if (data_ragged_rank == 0 and segment_ids_ragged_rank == 0 and\n seg_dtype == dtypes.int32):\n equiv = ragged_concat_ops.stack(\n data_flow_ops.dynamic_partition(data_tensor, segment_ids_tensor,\n num_partitions))\n self.assertAllEqual(result, self.evaluate(equiv).to_list())\n\n @parameterized.parameters([\n dict(\n data=['a', 'b', 'c'],\n partitions=[2, -1, 0],\n num_partitions=10,\n error='must be non-negative'),\n dict(\n data=['a', 'b', 'c'],\n partitions=[2, 10, 0],\n num_partitions=1,\n error='partitions must be less than num_partitions'),\n dict(\n data=['a', 'b', 'c'],\n partitions=[2, 10, 0],\n num_partitions=10,\n error='partitions must be less than num_partitions'),\n dict(\n data=[['a', 'b'], ['c']],\n partitions=[[2], [3, 0]],\n num_partitions=10,\n error='data and partitions have incompatible ragged shapes'),\n ])\n def testRuntimeError(self, data, partitions, num_partitions, error):\n data = ragged_factory_ops.constant(data)\n partitions = ragged_factory_ops.constant(partitions, dtype=dtypes.int64)\n with self.assertRaisesRegexp((ValueError, errors.InvalidArgumentError),\n error):\n self.evaluate(\n ragged_array_ops.stack_dynamic_partitions(data, partitions,\n num_partitions))\n\n @parameterized.parameters([\n dict(\n data=['a', 'b', 'c'],\n partitions=[1, 2],\n num_partitions=10,\n error=r'Shapes \\(2,\\) and \\(3,\\) are incompatible'),\n dict(\n data=[['a', 'b'], ['c', 'd']],\n partitions=[[1, 2, 3], [4, 5, 6]],\n num_partitions=10,\n error=r'Shapes \\(2, 3\\) and \\(2, 2\\) are incompatible'),\n dict(\n data=['a', 'b', 'c'],\n partitions=[1, 2, 3],\n num_partitions=[1, 2, 3],\n error='must have rank 0'),\n ])\n def testStaticError(self, data, partitions, num_partitions, error):\n with self.assertRaisesRegexp((ValueError, errors.InvalidArgumentError),\n error):\n ragged_array_ops.stack_dynamic_partitions(data, partitions,\n num_partitions)\n\n def testUnknownRankError(self):\n if context.executing_eagerly():\n return\n partitions = array_ops.placeholder(dtypes.int32, None)\n with self.assertRaisesRegexp((ValueError, errors.InvalidArgumentError),\n 'partitions must have known rank'):\n ragged_array_ops.stack_dynamic_partitions(['a', 'b', 'c'], partitions, 10)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `tf.data.experimental.parse_example_dataset().\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\n\nimport numpy as np\n\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.core.example import feature_pb2\nfrom tensorflow.python.data.experimental.ops import parsing_ops as contrib_parsing_ops\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import test\n\n# Helpers for creating Example objects\nexample = example_pb2.Example\nfeature = feature_pb2.Feature\nfeatures = lambda d: feature_pb2.Features(feature=d)\nbytes_feature = lambda v: feature(bytes_list=feature_pb2.BytesList(value=v))\nint64_feature = lambda v: feature(int64_list=feature_pb2.Int64List(value=v))\nfloat_feature = lambda v: feature(float_list=feature_pb2.FloatList(value=v))\n# Helpers for creating SequenceExample objects\nfeature_list = lambda l: feature_pb2.FeatureList(feature=l)\nfeature_lists = lambda d: feature_pb2.FeatureLists(feature_list=d)\nsequence_example = example_pb2.SequenceExample\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass ParseExampleDatasetTest(test_base.DatasetTestBase):\n\n def _compare_output_to_expected(self, dict_tensors, expected_tensors):\n self.assertEqual(set(dict_tensors.keys()), set(expected_tensors.keys()))\n\n for k, v in sorted(dict_tensors.items()):\n expected_v = expected_tensors[k]\n self.assertValuesEqual(expected_v, v)\n\n def _test(self,\n input_tensor,\n feature_val,\n expected_values=None,\n expected_err=None,\n create_iterator_twice=False):\n\n if expected_err:\n with self.assertRaisesWithPredicateMatch(expected_err[0],\n expected_err[1]):\n dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply(\n contrib_parsing_ops.parse_example_dataset(feature_val))\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n return\n else:\n # Returns dict w/ Tensors and SparseTensors.\n # Check values.\n dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply(\n contrib_parsing_ops.parse_example_dataset(feature_val))\n get_next = self.getNext(dataset)\n result = self.evaluate(get_next())\n self._compare_output_to_expected(result, expected_values)\n with self.assertRaises(errors_impl.OutOfRangeError):\n self.evaluate(get_next())\n with self.assertRaises(errors_impl.OutOfRangeError):\n self.evaluate(get_next())\n if create_iterator_twice:\n get_next = self.getNext(dataset)\n result = self.evaluate(get_next())\n self._compare_output_to_expected(result, expected_values)\n with self.assertRaises(errors_impl.OutOfRangeError):\n self.evaluate(get_next())\n # Check shapes; if serialized is a Tensor we need its size to\n # properly check.\n batch_size = (\n self.evaluate(input_tensor).size if isinstance(input_tensor, ops.Tensor)\n else np.asarray(input_tensor).size)\n for k, f in feature_val.items():\n if isinstance(f, parsing_ops.FixedLenFeature) and f.shape is not None:\n self.assertEqual(\n dataset_ops.get_legacy_output_shapes(dataset)[k].as_list()[0],\n batch_size)\n elif isinstance(f, parsing_ops.VarLenFeature):\n self.assertEqual(\n dataset_ops.get_legacy_output_shapes(dataset)[k].as_list()[1], None)\n\n def testEmptySerializedWithAllDefaults(self):\n sparse_name = \"st_a\"\n a_name = \"a\"\n b_name = \"b\"\n c_name = \"c:has_a_tricky_name\"\n a_default = [0, 42, 0]\n b_default = np.random.rand(3, 3).astype(bytes)\n c_default = np.random.rand(2).astype(np.float32)\n\n expected_st_a = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.empty((0, 2), dtype=np.int64), # indices\n np.empty((0,), dtype=np.int64), # sp_a is DT_INT64\n np.array([2, 0], dtype=np.int64)) # batch == 2, max_elems = 0\n\n expected_output = {\n sparse_name: expected_st_a,\n a_name: np.array(2 * [[a_default]]),\n b_name: np.array(2 * [b_default]),\n c_name: np.array(2 * [c_default]),\n }\n\n self._test(\n ops.convert_to_tensor([\"\", \"\"]), {\n sparse_name:\n parsing_ops.VarLenFeature(dtypes.int64),\n a_name:\n parsing_ops.FixedLenFeature(\n (1, 3), dtypes.int64, default_value=a_default),\n b_name:\n parsing_ops.FixedLenFeature(\n (3, 3), dtypes.string, default_value=b_default),\n c_name:\n parsing_ops.FixedLenFeature(\n (2,), dtypes.float32, default_value=c_default),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n @test_util.run_deprecated_v1\n def testEmptySerializedWithoutDefaultsShouldFail(self):\n input_features = {\n \"st_a\":\n parsing_ops.VarLenFeature(dtypes.int64),\n \"a\":\n parsing_ops.FixedLenFeature(\n (1, 3), dtypes.int64, default_value=[0, 42, 0]),\n \"b\":\n parsing_ops.FixedLenFeature(\n (3, 3),\n dtypes.string,\n default_value=np.random.rand(3, 3).astype(bytes)),\n # Feature \"c\" is missing a default, this gap will cause failure.\n \"c\":\n parsing_ops.FixedLenFeature(\n (2,), dtype=dtypes.float32),\n }\n\n # Edge case where the key is there but the feature value is empty\n original = example(features=features({\"c\": feature()}))\n self._test(\n [original.SerializeToString()],\n input_features,\n expected_err=(errors_impl.InvalidArgumentError,\n \"Feature: c \\\\(data type: float\\\\) is required\"))\n\n # Standard case of missing key and value.\n self._test(\n [\"\", \"\"],\n input_features,\n expected_err=(errors_impl.InvalidArgumentError,\n \"Feature: c \\\\(data type: float\\\\) is required\"))\n\n @test_util.run_deprecated_v1\n def testDenseNotMatchingShapeShouldFail(self):\n original = [\n example(features=features({\n \"a\": float_feature([1, 1, 3]),\n })), example(features=features({\n \"a\": float_feature([-1, -1]),\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n self._test(\n ops.convert_to_tensor(serialized),\n {\"a\": parsing_ops.FixedLenFeature((1, 3), dtypes.float32)},\n expected_err=(errors_impl.InvalidArgumentError,\n \"Key: a, Index: 1. Number of float values\"))\n\n def testDenseDefaultNoShapeShouldFail(self):\n original = [example(features=features({\"a\": float_feature([1, 1, 3]),})),]\n\n serialized = [m.SerializeToString() for m in original]\n\n self._test(\n ops.convert_to_tensor(serialized),\n {\"a\": parsing_ops.FixedLenFeature(None, dtypes.float32)},\n expected_err=(ValueError, \"Missing shape for feature a\"))\n\n def testSerializedContainingSparse(self):\n original = [\n example(features=features({\n \"st_c\": float_feature([3, 4])\n })),\n example(features=features({\n \"st_c\": float_feature([]), # empty float list\n })),\n example(features=features({\n \"st_d\": feature(), # feature with nothing in it\n })),\n example(features=features({\n \"st_c\": float_feature([1, 2, -1]),\n \"st_d\": bytes_feature([b\"hi\"])\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_st_c = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 0], [0, 1], [3, 0], [3, 1], [3, 2]], dtype=np.int64),\n np.array([3.0, 4.0, 1.0, 2.0, -1.0], dtype=np.float32),\n np.array([4, 3], dtype=np.int64)) # batch == 2, max_elems = 3\n\n expected_st_d = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[3, 0]], dtype=np.int64), np.array([\"hi\"], dtype=bytes),\n np.array([4, 1], dtype=np.int64)) # batch == 2, max_elems = 1\n\n expected_output = {\n \"st_c\": expected_st_c,\n \"st_d\": expected_st_d,\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"st_c\": parsing_ops.VarLenFeature(dtypes.float32),\n \"st_d\": parsing_ops.VarLenFeature(dtypes.string)\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingSparseFeature(self):\n original = [\n example(features=features({\n \"val\": float_feature([3, 4]),\n \"idx\": int64_feature([5, 10])\n })),\n example(features=features({\n \"val\": float_feature([]), # empty float list\n \"idx\": int64_feature([])\n })),\n example(features=features({\n \"val\": feature(), # feature with nothing in it\n # missing idx feature\n })),\n example(features=features({\n \"val\": float_feature([1, 2, -1]),\n \"idx\":\n int64_feature([0, 9, 3]) # unsorted\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 5], [0, 10], [3, 0], [3, 3], [3, 9]], dtype=np.int64),\n np.array([3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32),\n np.array([4, 13], dtype=np.int64)) # batch == 4, max_elems = 13\n\n expected_output = {\"sp\": expected_sp,}\n\n self._test(\n ops.convert_to_tensor(serialized),\n {\"sp\": parsing_ops.SparseFeature([\"idx\"], \"val\", dtypes.float32, [13])},\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingSparseFeatureReuse(self):\n original = [\n example(features=features({\n \"val1\": float_feature([3, 4]),\n \"val2\": float_feature([5, 6]),\n \"idx\": int64_feature([5, 10])\n })),\n example(features=features({\n \"val1\": float_feature([]), # empty float list\n \"idx\": int64_feature([])\n })),\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_sp1 = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 5], [0, 10]], dtype=np.int64),\n np.array([3.0, 4.0], dtype=np.float32),\n np.array([2, 13], dtype=np.int64)) # batch == 2, max_elems = 13\n\n expected_sp2 = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 5], [0, 10]], dtype=np.int64),\n np.array([5.0, 6.0], dtype=np.float32),\n np.array([2, 7], dtype=np.int64)) # batch == 2, max_elems = 13\n\n expected_output = {\n \"sp1\": expected_sp1,\n \"sp2\": expected_sp2,\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"sp1\":\n parsing_ops.SparseFeature(\"idx\", \"val1\", dtypes.float32, 13),\n \"sp2\":\n parsing_ops.SparseFeature(\n \"idx\", \"val2\", dtypes.float32, size=7, already_sorted=True)\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContaining3DSparseFeature(self):\n original = [\n example(features=features({\n \"val\": float_feature([3, 4]),\n \"idx0\": int64_feature([5, 10]),\n \"idx1\": int64_feature([0, 2]),\n })),\n example(features=features({\n \"val\": float_feature([]), # empty float list\n \"idx0\": int64_feature([]),\n \"idx1\": int64_feature([]),\n })),\n example(features=features({\n \"val\": feature(), # feature with nothing in it\n # missing idx feature\n })),\n example(features=features({\n \"val\": float_feature([1, 2, -1]),\n \"idx0\": int64_feature([0, 9, 3]), # unsorted\n \"idx1\": int64_feature([1, 0, 2]),\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_sp = sparse_tensor.SparseTensorValue(\n # indices\n np.array([[0, 5, 0], [0, 10, 2], [3, 0, 1], [3, 3, 2], [3, 9, 0]],\n dtype=np.int64),\n # values\n np.array([3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32),\n # shape batch == 4, max_elems = 13\n np.array([4, 13, 3], dtype=np.int64))\n\n expected_output = {\"sp\": expected_sp,}\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"sp\":\n parsing_ops.SparseFeature([\"idx0\", \"idx1\"], \"val\",\n dtypes.float32, [13, 3])\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingDense(self):\n aname = \"a\"\n bname = \"b*has+a:tricky_name\"\n original = [\n example(features=features({\n aname: float_feature([1, 1]),\n bname: bytes_feature([b\"b0_str\"]),\n })), example(features=features({\n aname: float_feature([-1, -1]),\n bname: bytes_feature([b\"\"]),\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_output = {\n aname:\n np.array(\n [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1),\n bname:\n np.array(\n [\"b0_str\", \"\"], dtype=bytes).reshape(2, 1, 1, 1, 1),\n }\n\n # No defaults, values required\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32),\n bname:\n parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n # This test is identical as the previous one except\n # for the creation of 'serialized'.\n def testSerializedContainingDenseWithConcat(self):\n aname = \"a\"\n bname = \"b*has+a:tricky_name\"\n # TODO(lew): Feature appearing twice should be an error in future.\n original = [\n (example(features=features({\n aname: float_feature([10, 10]),\n })), example(features=features({\n aname: float_feature([1, 1]),\n bname: bytes_feature([b\"b0_str\"]),\n }))),\n (\n example(features=features({\n bname: bytes_feature([b\"b100\"]),\n })),\n example(features=features({\n aname: float_feature([-1, -1]),\n bname: bytes_feature([b\"b1\"]),\n })),),\n ]\n\n serialized = [\n m.SerializeToString() + n.SerializeToString() for (m, n) in original\n ]\n\n expected_output = {\n aname:\n np.array(\n [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1),\n bname:\n np.array(\n [\"b0_str\", \"b1\"], dtype=bytes).reshape(2, 1, 1, 1, 1),\n }\n\n # No defaults, values required\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32),\n bname:\n parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingDenseScalar(self):\n original = [\n example(features=features({\n \"a\": float_feature([1]),\n })), example(features=features({}))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_output = {\n \"a\":\n np.array(\n [[1], [-1]], dtype=np.float32) # 2x1 (column vector)\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"a\":\n parsing_ops.FixedLenFeature(\n (1,), dtype=dtypes.float32, default_value=-1),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingDenseWithDefaults(self):\n original = [\n example(features=features({\n \"a\": float_feature([1, 1]),\n })),\n example(features=features({\n \"b\": bytes_feature([b\"b1\"]),\n })),\n example(features=features({\n \"b\": feature()\n })),\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_output = {\n \"a\":\n np.array(\n [[1, 1], [3, -3], [3, -3]], dtype=np.float32).reshape(3, 1, 2,\n 1),\n \"b\":\n np.array(\n [\"tmp_str\", \"b1\", \"tmp_str\"], dtype=bytes).reshape(3, 1, 1, 1,\n 1),\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"a\":\n parsing_ops.FixedLenFeature(\n (1, 2, 1), dtype=dtypes.float32, default_value=[3.0, -3.0]),\n \"b\":\n parsing_ops.FixedLenFeature(\n (1, 1, 1, 1), dtype=dtypes.string, default_value=\"tmp_str\"),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedSparseAndSparseFeatureAndDenseWithNoDefault(self):\n expected_st_a = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.empty((0, 2), dtype=np.int64), # indices\n np.empty((0,), dtype=np.int64), # sp_a is DT_INT64\n np.array([2, 0], dtype=np.int64)) # batch == 2, max_elems = 0\n expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 0], [0, 3], [1, 7]], dtype=np.int64),\n np.array([\"a\", \"b\", \"c\"], dtype=\"|S\"),\n np.array([2, 13], dtype=np.int64)) # batch == 4, max_elems = 13\n\n original = [\n example(features=features({\n \"c\": float_feature([3, 4]),\n \"val\": bytes_feature([b\"a\", b\"b\"]),\n \"idx\": int64_feature([0, 3])\n })), example(features=features({\n \"c\": float_feature([1, 2]),\n \"val\": bytes_feature([b\"c\"]),\n \"idx\": int64_feature([7])\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n a_default = [1, 2, 3]\n b_default = np.random.rand(3, 3).astype(bytes)\n expected_output = {\n \"st_a\": expected_st_a,\n \"sp\": expected_sp,\n \"a\": np.array(2 * [[a_default]]),\n \"b\": np.array(2 * [b_default]),\n \"c\": np.array(\n [[3, 4], [1, 2]], dtype=np.float32),\n }\n\n self._test(\n ops.convert_to_tensor(serialized),\n {\n \"st_a\":\n parsing_ops.VarLenFeature(dtypes.int64),\n \"sp\":\n parsing_ops.SparseFeature(\"idx\", \"val\", dtypes.string, 13),\n \"a\":\n parsing_ops.FixedLenFeature(\n (1, 3), dtypes.int64, default_value=a_default),\n \"b\":\n parsing_ops.FixedLenFeature(\n (3, 3), dtypes.string, default_value=b_default),\n # Feature \"c\" must be provided, since it has no default_value.\n \"c\":\n parsing_ops.FixedLenFeature((2,), dtypes.float32),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testerializedContainingSparseAndSparseFeatureWithReuse(self):\n expected_idx = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.int64),\n np.array([0, 3, 7, 1]),\n np.array([2, 2], dtype=np.int64)) # batch == 4, max_elems = 2\n\n expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape\n np.array([[0, 0], [0, 3], [1, 1], [1, 7]], dtype=np.int64),\n np.array([\"a\", \"b\", \"d\", \"c\"], dtype=\"|S\"),\n np.array([2, 13], dtype=np.int64)) # batch == 4, max_elems = 13\n\n original = [\n example(features=features({\n \"val\": bytes_feature([b\"a\", b\"b\"]),\n \"idx\": int64_feature([0, 3])\n })), example(features=features({\n \"val\": bytes_feature([b\"c\", b\"d\"]),\n \"idx\": int64_feature([7, 1])\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_output = {\n \"idx\": expected_idx,\n \"sp\": expected_sp,\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"idx\":\n parsing_ops.VarLenFeature(dtypes.int64),\n \"sp\":\n parsing_ops.SparseFeature([\"idx\"], \"val\", dtypes.string, [13]),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def _testSerializedContainingVarLenDenseLargerBatch(self, batch_size):\n # During parsing, data read from the serialized proto is stored in buffers.\n # For small batch sizes, a buffer will contain one minibatch entry.\n # For larger batch sizes, a buffer may contain several minibatch\n # entries. This test identified a bug where the code that copied\n # data out of the buffers and into the output tensors assumed each\n # buffer only contained one minibatch entry. The bug has since been fixed.\n truth_int = [i for i in range(batch_size)]\n truth_str = [[(\"foo%d\" % i).encode(), (\"bar%d\" % i).encode()]\n for i in range(batch_size)]\n\n expected_str = copy.deepcopy(truth_str)\n\n # Delete some intermediate entries\n for i in range(batch_size):\n col = 1\n if np.random.rand() < 0.25:\n # w.p. 25%, drop out the second entry\n expected_str[i][col] = b\"default\"\n col -= 1\n truth_str[i].pop()\n if np.random.rand() < 0.25:\n # w.p. 25%, drop out the second entry (possibly again)\n expected_str[i][col] = b\"default\"\n truth_str[i].pop()\n\n expected_output = {\n # Batch size batch_size, 1 time step.\n \"a\": np.array(truth_int, dtype=np.int64).reshape(batch_size, 1),\n # Batch size batch_size, 2 time steps.\n \"b\": np.array(expected_str, dtype=\"|S\").reshape(batch_size, 2),\n }\n\n original = [\n example(features=features(\n {\"a\": int64_feature([truth_int[i]]),\n \"b\": bytes_feature(truth_str[i])}))\n for i in range(batch_size)\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n self._test(\n ops.convert_to_tensor(serialized, dtype=dtypes.string), {\n \"a\":\n parsing_ops.FixedLenSequenceFeature(\n shape=(),\n dtype=dtypes.int64,\n allow_missing=True,\n default_value=-1),\n \"b\":\n parsing_ops.FixedLenSequenceFeature(\n shape=[],\n dtype=dtypes.string,\n allow_missing=True,\n default_value=\"default\"),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingVarLenDenseLargerBatch(self):\n np.random.seed(3456)\n for batch_size in (1, 10, 20, 100, 256):\n self._testSerializedContainingVarLenDenseLargerBatch(batch_size)\n\n def testSerializedShapeMismatch(self):\n aname = \"a\"\n bname = \"b\"\n cname = \"c\"\n original = [\n example(features=features({\n cname: int64_feature([2]),\n })),\n example(features=features({\n aname: float_feature([1, 1]),\n bname: bytes_feature([b\"b0_str\", b\"b1_str\"]),\n })),\n example(features=features({\n aname: float_feature([-1, -1, 2, 2]),\n bname: bytes_feature([b\"b1\"]),\n })),\n example(features=features({\n aname: float_feature([]),\n cname: int64_feature([3]),\n })),\n ]\n\n serialized = [m.SerializeToString() for m in original]\n if context.executing_eagerly():\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature((2, 1),\n dtype=dtypes.float32,\n allow_missing=True,\n default_value=[]),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1, 1), dtype=dtypes.string, allow_missing=True),\n },\n expected_err=(errors_impl.InvalidArgumentError,\n \"Input to reshape is a tensor with 0 values\"))\n else:\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature((2, 1),\n dtype=dtypes.float32,\n allow_missing=True,\n default_value=[]),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1, 1), dtype=dtypes.string, allow_missing=True),\n },\n expected_err=(ValueError,\n \"Cannot reshape a tensor with 0 elements to shape\"))\n\n @test_util.run_deprecated_v1\n def testSerializedContainingVarLenDense(self):\n aname = \"a\"\n bname = \"b\"\n cname = \"c\"\n dname = \"d\"\n original = [\n example(features=features({\n cname: int64_feature([2]),\n })),\n example(\n features=features({\n aname: float_feature([1, 1]),\n bname: bytes_feature([b\"b0_str\", b\"b1_str\"]),\n })),\n example(\n features=features({\n aname: float_feature([-1, -1, 2, 2]),\n bname: bytes_feature([b\"b1\"]),\n })),\n example(\n features=features({\n aname: float_feature([]),\n cname: int64_feature([3]),\n })),\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_output = {\n aname:\n np.array(\n [\n [0, 0, 0, 0],\n [1, 1, 0, 0],\n [-1, -1, 2, 2],\n [0, 0, 0, 0],\n ],\n dtype=np.float32).reshape(4, 2, 2, 1),\n bname:\n np.array(\n [[\"\", \"\"], [\"b0_str\", \"b1_str\"], [\"b1\", \"\"], [\"\", \"\"]],\n dtype=bytes).reshape(4, 2, 1, 1, 1),\n cname:\n np.array([2, 0, 0, 3], dtype=np.int64).reshape(4, 1),\n dname:\n np.empty(shape=(4, 0), dtype=bytes),\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1), dtype=dtypes.float32, allow_missing=True),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (1, 1, 1), dtype=dtypes.string, allow_missing=True),\n cname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.int64, allow_missing=True),\n dname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.string, allow_missing=True),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n # Test with padding values.\n expected_output_custom_padding = dict(expected_output)\n expected_output_custom_padding[aname] = np.array(\n [\n [-2, -2, -2, -2],\n [1, 1, -2, -2],\n [-1, -1, 2, 2],\n [-2, -2, -2, -2],\n ],\n dtype=np.float32).reshape(4, 2, 2, 1)\n\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1),\n dtype=dtypes.float32,\n allow_missing=True,\n default_value=-2.0),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (1, 1, 1), dtype=dtypes.string, allow_missing=True),\n cname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.int64, allow_missing=True),\n dname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.string, allow_missing=True),\n }, expected_output_custom_padding)\n\n # Change number of required values so the inputs are not a\n # multiple of this size.\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1), dtype=dtypes.float32, allow_missing=True),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1, 1), dtype=dtypes.string, allow_missing=True),\n },\n expected_err=(\n errors_impl.OpError, \"Key: b, Index: 2. \"\n \"Number of bytes values is not a multiple of stride length.\"))\n\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenFeature((None, 2, 1), dtype=dtypes.float32),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1, 1), dtype=dtypes.string, allow_missing=True),\n },\n expected_err=(ValueError,\n \"First dimension of shape for feature a unknown. \"\n \"Consider using FixedLenSequenceFeature.\"))\n\n self._test(\n ops.convert_to_tensor(serialized), {\n cname:\n parsing_ops.FixedLenFeature(\n (1, None), dtype=dtypes.int64, default_value=[[1]]),\n },\n expected_err=(ValueError,\n \"All dimensions of shape for feature c need to be known \"\n r\"but received \\(1, None\\).\"))\n\n self._test(\n ops.convert_to_tensor(serialized), {\n aname:\n parsing_ops.FixedLenSequenceFeature(\n (2, 1), dtype=dtypes.float32, allow_missing=True),\n bname:\n parsing_ops.FixedLenSequenceFeature(\n (1, 1, 1), dtype=dtypes.string, allow_missing=True),\n cname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.int64, allow_missing=False),\n dname:\n parsing_ops.FixedLenSequenceFeature(\n shape=[], dtype=dtypes.string, allow_missing=True),\n },\n expected_err=(ValueError,\n \"Unsupported: FixedLenSequenceFeature requires \"\n \"allow_missing to be True.\"))\n\n def testSerializedContainingRaggedFeatureWithNoPartitions(self):\n original = [\n example(\n features=features({\n \"rt_c\": float_feature([3, 4, 5, 6, 7, 8]),\n })),\n example(\n features=features({\n \"rt_c\": float_feature([]), # empty float list\n })),\n example(\n features=features({\n \"rt_d\": feature(), # feature with nothing in it\n })),\n example(\n features=features({\n \"rt_c\": float_feature([1, 2, -1]),\n \"rt_d\": bytes_feature([b\"hi\"]),\n }))\n ]\n\n serialized = [m.SerializeToString() for m in original]\n\n expected_rt_c = ragged_factory_ops.constant_value(\n [[3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [], [], [1.0, 2.0, -1.0]],\n row_splits_dtype=dtypes.int32)\n expected_rt_d = ragged_factory_ops.constant_value(\n [[], [], [], [b\"hi\"]], row_splits_dtype=dtypes.int64)\n\n expected_output = {\n \"rt_c\": expected_rt_c,\n \"rt_d\": expected_rt_d,\n }\n\n self._test(\n ops.convert_to_tensor(serialized), {\n \"rt_c\":\n parsing_ops.RaggedFeature(dtypes.float32),\n \"rt_d\":\n parsing_ops.RaggedFeature(\n dtypes.string, row_splits_dtype=dtypes.int64),\n },\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingRaggedFeatureWithOnePartition(self):\n original = [\n example(\n features=features({\n # rt = [[3], [4, 5, 6]]\n \"rt_values\": float_feature([3, 4, 5, 6]),\n \"rt_splits\": int64_feature([0, 1, 4]),\n \"rt_lengths\": int64_feature([1, 3]),\n \"rt_starts\": int64_feature([0, 1]),\n \"rt_limits\": int64_feature([1, 4]),\n \"rt_rowids\": int64_feature([0, 1, 1, 1]),\n })),\n example(\n features=features({\n # rt = []\n \"rt_values\": float_feature([]),\n \"rt_splits\": int64_feature([0]),\n \"rt_lengths\": int64_feature([]),\n \"rt_starts\": int64_feature([]),\n \"rt_limits\": int64_feature([]),\n \"rt_rowids\": int64_feature([]),\n })),\n example(\n features=features({\n # rt = []\n \"rt_values\": feature(), # feature with nothing in it\n \"rt_splits\": int64_feature([0]),\n \"rt_lengths\": feature(),\n \"rt_starts\": feature(),\n \"rt_limits\": feature(),\n \"rt_rowids\": feature(),\n })),\n example(\n features=features({\n # rt = [[1.0, 2.0, -1.0], [], [8.0, 9.0], [5.0]]\n \"rt_values\": float_feature([1, 2, -1, 8, 9, 5]),\n \"rt_splits\": int64_feature([0, 3, 3, 5, 6]),\n \"rt_lengths\": int64_feature([3, 0, 2, 1]),\n \"rt_starts\": int64_feature([0, 3, 3, 5]),\n \"rt_limits\": int64_feature([3, 3, 5, 6]),\n \"rt_rowids\": int64_feature([0, 0, 0, 2, 2, 3]),\n }))\n ]\n serialized = [m.SerializeToString() for m in original]\n\n test_features = {\n \"rt1\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.RowSplits(\"rt_splits\")],\n dtype=dtypes.float32),\n \"rt2\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.RowLengths(\"rt_lengths\")],\n dtype=dtypes.float32),\n \"rt3\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.RowStarts(\"rt_starts\")],\n dtype=dtypes.float32),\n \"rt4\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.RowLimits(\"rt_limits\")],\n dtype=dtypes.float32),\n \"rt5\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.ValueRowIds(\"rt_rowids\")],\n dtype=dtypes.float32),\n \"uniform1\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[parsing_ops.RaggedFeature.UniformRowLength(2)],\n dtype=dtypes.float32),\n \"uniform2\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[\n parsing_ops.RaggedFeature.UniformRowLength(2),\n parsing_ops.RaggedFeature.RowSplits(\"rt_splits\")\n ],\n dtype=dtypes.float32),\n }\n\n expected_rt = ragged_factory_ops.constant(\n [[[3], [4, 5, 6]], [], [], [[1, 2, -1], [], [8, 9], [5]]],\n dtype=dtypes.float32,\n row_splits_dtype=dtypes.int32)\n\n expected_uniform1 = ragged_factory_ops.constant(\n [[[3, 4], [5, 6]], [], [], [[1, 2], [-1, 8], [9, 5]]],\n ragged_rank=1,\n dtype=dtypes.float32,\n row_splits_dtype=dtypes.int32)\n\n expected_uniform2 = ragged_factory_ops.constant(\n [[[[3], [4, 5, 6]]], [], [], [[[1, 2, -1], []], [[8, 9], [5]]]],\n dtype=dtypes.float32,\n row_splits_dtype=dtypes.int32)\n\n expected_output = {\n \"rt1\": expected_rt,\n \"rt2\": expected_rt,\n \"rt3\": expected_rt,\n \"rt4\": expected_rt,\n \"rt5\": expected_rt,\n \"uniform1\": expected_uniform1,\n \"uniform2\": expected_uniform2,\n }\n\n self._test(\n ops.convert_to_tensor(serialized),\n test_features,\n expected_values=expected_output,\n create_iterator_twice=True)\n\n def testSerializedContainingRaggedFeatureWithMultiplePartitions(self):\n original = [\n # rt shape: [(batch), 2, None, None]\n example(\n features=features({\n # rt = [[[[1]], [[2, 3], [4]]], [[], [[5, 6, 7]]]]\n \"rt_values\": float_feature([1, 2, 3, 4, 5, 6, 7]),\n \"lengths_axis2\": int64_feature([1, 2, 0, 1]),\n \"lengths_axis3\": int64_feature([1, 2, 1, 3]),\n \"splits_axis3\": int64_feature([0, 1, 3, 4, 7]),\n })),\n example(\n features=features({\n # rt = [[[[1, 2, 3], [4]], [[5], [6], [7, 8]]]]\n \"rt_values\": float_feature([1, 2, 3, 4, 5, 6, 7, 8]),\n \"lengths_axis2\": int64_feature([2, 3]),\n \"lengths_axis3\": int64_feature([3, 1, 1, 1, 2]),\n \"splits_axis3\": int64_feature([0, 3, 4, 5, 6, 8]),\n }))\n ]\n serialized = [m.SerializeToString() for m in original]\n\n test_features = {\n \"rt1\":\n parsing_ops.RaggedFeature(\n value_key=\"rt_values\",\n partitions=[\n parsing_ops.RaggedFeature.UniformRowLength(2),\n parsing_ops.RaggedFeature.RowLengths(\"lengths_axis2\"),\n parsing_ops.RaggedFeature.RowSplits(\"splits_axis3\"),\n ],\n dtype=dtypes.float32,\n row_splits_dtype=dtypes.int64,\n ),\n }\n\n expected_rt = ragged_factory_ops.constant(\n [[[[[1]], [[2, 3], [4]]], [[], [[5, 6, 7]]]],\n [[[[1, 2, 3], [4]], [[5], [6], [7, 8]]]]],\n dtype=dtypes.float32,\n row_splits_dtype=dtypes.int64)\n\n expected_output = {\n \"rt1\": expected_rt,\n }\n\n self._test(\n ops.convert_to_tensor(serialized),\n test_features,\n expected_values=expected_output,\n create_iterator_twice=True)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `tf.data.experimental.Counter`.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.data.experimental.ops import counter\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass CounterTest(test_base.DatasetTestBase):\n\n def testCounter(self):\n \"\"\"Test dataset construction using `count`.\"\"\"\n dataset = counter.Counter(start=3, step=4)\n self.assertEqual(\n [], dataset_ops.get_legacy_output_shapes(dataset).as_list())\n self.assertEqual(dtypes.int64, dataset_ops.get_legacy_output_types(dataset))\n get_next = self.getNext(dataset)\n\n negative_dataset = counter.Counter(start=0, step=-1)\n negative_get_next = self.getNext(negative_dataset)\n\n self.assertEqual(3, self.evaluate(get_next()))\n self.assertEqual(3 + 4, self.evaluate(get_next()))\n self.assertEqual(3 + 2 * 4, self.evaluate(get_next()))\n\n self.assertEqual(0, self.evaluate(negative_get_next()))\n self.assertEqual(-1, self.evaluate(negative_get_next()))\n self.assertEqual(-2, self.evaluate(negative_get_next()))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the ParallelInterleaveDataset serialization.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.kernel_tests.serialization import dataset_serialization_test_base\nfrom tensorflow.python.data.experimental.ops import interleave_ops\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import test\n\n\nclass ParallelInterleaveDatasetSerializationTest(\n dataset_serialization_test_base.DatasetSerializationTestBase,\n parameterized.TestCase):\n\n def setUp(self):\n self.input_values = np.array([4, 5, 6], dtype=np.int64)\n self.num_repeats = 2\n self.num_outputs = np.sum(self.input_values) * 2\n\n def _build_ds(self, cycle_length, block_length, sloppy=False):\n return (dataset_ops.Dataset.from_tensor_slices(\n self.input_values).repeat(self.num_repeats).apply(\n interleave_ops.parallel_interleave(\n lambda x: dataset_ops.Dataset.range(10 * x, 11 * x),\n cycle_length, block_length, sloppy)))\n\n @combinations.generate(test_base.default_test_combinations())\n def testSerializationCore(self):\n # cycle_length > 1, block_length > 1\n cycle_length = 2\n block_length = 3\n self.run_core_tests(lambda: self._build_ds(cycle_length, block_length),\n self.num_outputs)\n # cycle_length = 1\n cycle_length = 1\n block_length = 3\n self.run_core_tests(lambda: self._build_ds(cycle_length, block_length),\n self.num_outputs)\n # block_length = 1\n cycle_length = 2\n block_length = 1\n self.run_core_tests(lambda: self._build_ds(cycle_length, block_length),\n self.num_outputs)\n\n @combinations.generate(test_base.default_test_combinations())\n def testSerializationWithSloppy(self):\n break_points = self.gen_break_points(self.num_outputs, 10)\n expected_outputs = np.repeat(\n np.concatenate([np.arange(10 * x, 11 * x) for x in self.input_values]),\n self.num_repeats).tolist()\n\n def run_test(cycle_length, block_length):\n actual = self.gen_outputs(\n lambda: self._build_ds(cycle_length, block_length, True),\n break_points, self.num_outputs)\n self.assertSequenceEqual(sorted(actual), expected_outputs)\n\n # cycle_length > 1, block_length > 1\n run_test(2, 3)\n # cycle_length = 1\n run_test(1, 3)\n # block_length = 1\n run_test(2, 1)\n\n @combinations.generate(test_base.default_test_combinations())\n def testSparseCore(self):\n\n def _map_fn(i):\n return sparse_tensor.SparseTensorValue(\n indices=[[0, 0], [1, 1]], values=(i * [1, -1]), dense_shape=[2, 2])\n\n def _interleave_fn(x):\n return dataset_ops.Dataset.from_tensor_slices(\n sparse_ops.sparse_to_dense(x.indices, x.dense_shape, x.values))\n\n def _build_dataset():\n return dataset_ops.Dataset.range(10).map(_map_fn).apply(\n interleave_ops.parallel_interleave(_interleave_fn, 1))\n\n self.run_core_tests(_build_dataset, 20)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for asserts module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.autograph.converters import asserts\nfrom tensorflow.python.autograph.converters import function_scopes\nfrom tensorflow.python.autograph.core import converter_testing\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.platform import test\n\n\nclass AssertsTest(converter_testing.TestCase):\n\n def test_basic(self):\n\n def test_fn(a):\n assert a, 'testmsg'\n return a\n\n with ops.Graph().as_default():\n with self.converted(test_fn, (function_scopes, asserts), {}) as result:\n op = result.test_fn(constant_op.constant(False))\n\n with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'testmsg'):\n self.evaluate(op)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for utility functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport importlib\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops.distributions import util as distribution_util\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging\n\ndu = distribution_util\n\n\ndef try_import(name): # pylint: disable=invalid-name\n module = None\n try:\n module = importlib.import_module(name)\n except ImportError as e:\n tf_logging.warning(\"Could not import %s: %s\" % (name, str(e)))\n return module\n\n\nspecial = try_import(\"scipy.special\")\n\n\ndef _logit(x):\n x = np.asarray(x)\n return np.log(x) - np.log1p(-x)\n\n\nclass AssertCloseTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testAssertIntegerForm(self):\n # This should only be detected as an integer.\n x = array_ops.placeholder(dtypes.float32)\n y = array_ops.placeholder(dtypes.float32)\n # First component isn't less than float32.eps = 1e-7\n z = array_ops.placeholder(dtypes.float32)\n # This shouldn\"t be detected as an integer.\n w = array_ops.placeholder(dtypes.float32)\n feed_dict = {x: [1., 5, 10, 15, 20], y: [1.1, 5, 10, 15, 20],\n z: [1.0001, 5, 10, 15, 20], w: [1e-8, 5, 10, 15, 20]}\n with self.cached_session():\n with ops.control_dependencies([du.assert_integer_form(x)]):\n array_ops.identity(x).eval(feed_dict=feed_dict)\n\n with self.assertRaisesOpError(\"has non-integer components\"):\n with ops.control_dependencies(\n [du.assert_integer_form(y)]):\n array_ops.identity(y).eval(feed_dict=feed_dict)\n\n with self.assertRaisesOpError(\"has non-integer components\"):\n with ops.control_dependencies(\n [du.assert_integer_form(z)]):\n array_ops.identity(z).eval(feed_dict=feed_dict)\n\n with self.assertRaisesOpError(\"has non-integer components\"):\n with ops.control_dependencies(\n [du.assert_integer_form(w)]):\n array_ops.identity(w).eval(feed_dict=feed_dict)\n\n\nclass MaybeGetStaticTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testGetStaticInt(self):\n x = 2\n self.assertEqual(x, du.maybe_get_static_value(x))\n self.assertAllClose(\n np.array(2.), du.maybe_get_static_value(x, dtype=np.float64))\n\n @test_util.run_in_graph_and_eager_modes\n def testGetStaticNumpyArray(self):\n x = np.array(2, dtype=np.int32)\n self.assertEqual(x, du.maybe_get_static_value(x))\n self.assertAllClose(\n np.array(2.), du.maybe_get_static_value(x, dtype=np.float64))\n\n @test_util.run_in_graph_and_eager_modes\n def testGetStaticConstant(self):\n x = constant_op.constant(2, dtype=dtypes.int32)\n self.assertEqual(np.array(2, dtype=np.int32), du.maybe_get_static_value(x))\n self.assertAllClose(\n np.array(2.), du.maybe_get_static_value(x, dtype=np.float64))\n\n @test_util.run_deprecated_v1\n def testGetStaticPlaceholder(self):\n x = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n self.assertEqual(None, du.maybe_get_static_value(x))\n self.assertEqual(None, du.maybe_get_static_value(x, dtype=np.float64))\n\n\nclass GetLogitsAndProbsTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testImproperArguments(self):\n with self.assertRaises(ValueError):\n du.get_logits_and_probs(logits=None, probs=None)\n\n with self.assertRaises(ValueError):\n du.get_logits_and_probs(logits=[0.1], probs=[0.1])\n\n @test_util.run_in_graph_and_eager_modes\n def testLogits(self):\n p = np.array([0.01, 0.2, 0.5, 0.7, .99], dtype=np.float32)\n logits = _logit(p)\n\n new_logits, new_p = du.get_logits_and_probs(\n logits=logits, validate_args=True)\n\n self.assertAllClose(p, self.evaluate(new_p), rtol=1e-5, atol=0.)\n self.assertAllClose(logits, self.evaluate(new_logits), rtol=1e-5, atol=0.)\n\n @test_util.run_in_graph_and_eager_modes\n def testLogitsMultidimensional(self):\n p = np.array([0.2, 0.3, 0.5], dtype=np.float32)\n logits = np.log(p)\n\n new_logits, new_p = du.get_logits_and_probs(\n logits=logits, multidimensional=True, validate_args=True)\n\n self.assertAllClose(self.evaluate(new_p), p)\n self.assertAllClose(self.evaluate(new_logits), logits)\n\n @test_util.run_in_graph_and_eager_modes\n def testProbability(self):\n p = np.array([0.01, 0.2, 0.5, 0.7, .99], dtype=np.float32)\n\n new_logits, new_p = du.get_logits_and_probs(probs=p, validate_args=True)\n\n self.assertAllClose(_logit(p), self.evaluate(new_logits))\n self.assertAllClose(p, self.evaluate(new_p))\n\n @test_util.run_in_graph_and_eager_modes\n def testProbabilityMultidimensional(self):\n p = np.array([[0.3, 0.4, 0.3], [0.1, 0.5, 0.4]], dtype=np.float32)\n\n new_logits, new_p = du.get_logits_and_probs(\n probs=p, multidimensional=True, validate_args=True)\n\n self.assertAllClose(np.log(p), self.evaluate(new_logits))\n self.assertAllClose(p, self.evaluate(new_p))\n\n @test_util.run_in_graph_and_eager_modes\n def testProbabilityValidateArgs(self):\n p = [0.01, 0.2, 0.5, 0.7, .99]\n # Component less than 0.\n p2 = [-1, 0.2, 0.5, 0.3, .2]\n # Component greater than 1.\n p3 = [2, 0.2, 0.5, 0.3, .2]\n\n _, prob = du.get_logits_and_probs(probs=p, validate_args=True)\n self.evaluate(prob)\n\n with self.assertRaisesOpError(\"Condition x >= 0\"):\n _, prob = du.get_logits_and_probs(probs=p2, validate_args=True)\n self.evaluate(prob)\n\n _, prob = du.get_logits_and_probs(probs=p2, validate_args=False)\n self.evaluate(prob)\n\n with self.assertRaisesOpError(\"probs has components greater than 1\"):\n _, prob = du.get_logits_and_probs(probs=p3, validate_args=True)\n self.evaluate(prob)\n\n _, prob = du.get_logits_and_probs(probs=p3, validate_args=False)\n self.evaluate(prob)\n\n @test_util.run_in_graph_and_eager_modes\n def testProbabilityValidateArgsMultidimensional(self):\n p = np.array([[0.3, 0.4, 0.3], [0.1, 0.5, 0.4]], dtype=np.float32)\n # Component less than 0. Still sums to 1.\n p2 = np.array([[-.3, 0.4, 0.9], [0.1, 0.5, 0.4]], dtype=np.float32)\n # Component greater than 1. Does not sum to 1.\n p3 = np.array([[1.3, 0.0, 0.0], [0.1, 0.5, 0.4]], dtype=np.float32)\n # Does not sum to 1.\n p4 = np.array([[1.1, 0.3, 0.4], [0.1, 0.5, 0.4]], dtype=np.float32)\n\n _, prob = du.get_logits_and_probs(probs=p, multidimensional=True)\n self.evaluate(prob)\n\n with self.assertRaisesOpError(\"Condition x >= 0\"):\n _, prob = du.get_logits_and_probs(\n probs=p2, multidimensional=True, validate_args=True)\n self.evaluate(prob)\n\n _, prob = du.get_logits_and_probs(\n probs=p2, multidimensional=True, validate_args=False)\n self.evaluate(prob)\n\n with self.assertRaisesOpError(\n \"(probs has components greater than 1|probs does not sum to 1)\"):\n _, prob = du.get_logits_and_probs(\n probs=p3, multidimensional=True, validate_args=True)\n self.evaluate(prob)\n\n _, prob = du.get_logits_and_probs(\n probs=p3, multidimensional=True, validate_args=False)\n self.evaluate(prob)\n\n with self.assertRaisesOpError(\"probs does not sum to 1\"):\n _, prob = du.get_logits_and_probs(\n probs=p4, multidimensional=True, validate_args=True)\n self.evaluate(prob)\n\n _, prob = du.get_logits_and_probs(\n probs=p4, multidimensional=True, validate_args=False)\n self.evaluate(prob)\n\n @test_util.run_deprecated_v1\n def testProbsMultidimShape(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n p = array_ops.ones([int(2**11+1)], dtype=np.float16)\n du.get_logits_and_probs(\n probs=p, multidimensional=True, validate_args=True)\n\n with self.assertRaisesOpError(\n \"Number of classes exceeds `dtype` precision\"):\n p = array_ops.placeholder(dtype=dtypes.float16)\n _, prob = du.get_logits_and_probs(\n probs=p, multidimensional=True, validate_args=True)\n prob.eval(feed_dict={p: np.ones([int(2**11+1)])})\n\n @test_util.run_deprecated_v1\n def testLogitsMultidimShape(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n l = array_ops.ones([int(2**11+1)], dtype=np.float16)\n du.get_logits_and_probs(\n logits=l, multidimensional=True, validate_args=True)\n\n with self.assertRaisesOpError(\n \"Number of classes exceeds `dtype` precision\"):\n l = array_ops.placeholder(dtype=dtypes.float16)\n logit, _ = du.get_logits_and_probs(\n logits=l, multidimensional=True, validate_args=True)\n logit.eval(feed_dict={l: np.ones([int(2**11+1)])})\n\n\nclass EmbedCheckCategoricalEventShapeTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testTooSmall(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n param = array_ops.ones([1], dtype=np.float16)\n checked_param = du.embed_check_categorical_event_shape(\n param)\n\n with self.assertRaisesOpError(\n \"must have at least 2 events\"):\n param = array_ops.placeholder(dtype=dtypes.float16)\n checked_param = du.embed_check_categorical_event_shape(\n param)\n checked_param.eval(feed_dict={param: np.ones([1])})\n\n @test_util.run_deprecated_v1\n def testTooLarge(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n param = array_ops.ones([int(2**11+1)], dtype=dtypes.float16)\n checked_param = du.embed_check_categorical_event_shape(\n param)\n\n with self.assertRaisesOpError(\n \"Number of classes exceeds `dtype` precision\"):\n param = array_ops.placeholder(dtype=dtypes.float16)\n checked_param = du.embed_check_categorical_event_shape(\n param)\n checked_param.eval(feed_dict={param: np.ones([int(2**11+1)])})\n\n @test_util.run_in_graph_and_eager_modes\n def testUnsupportedDtype(self):\n param = ops.convert_to_tensor(\n np.ones([2**11 + 1]).astype(dtypes.qint16.as_numpy_dtype),\n dtype=dtypes.qint16)\n with self.assertRaises(TypeError):\n du.embed_check_categorical_event_shape(param)\n\n\nclass EmbedCheckIntegerCastingClosedTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testCorrectlyAssertsNonnegative(self):\n with self.cached_session():\n with self.assertRaisesOpError(\"Elements must be non-negative\"):\n x = array_ops.placeholder(dtype=dtypes.float16)\n x_checked = du.embed_check_integer_casting_closed(\n x, target_dtype=dtypes.int16)\n x_checked.eval(feed_dict={x: np.array([1, -1], dtype=np.float16)})\n\n @test_util.run_deprecated_v1\n def testCorrectlyAssersIntegerForm(self):\n with self.cached_session():\n with self.assertRaisesOpError(\"Elements must be int16-equivalent.\"):\n x = array_ops.placeholder(dtype=dtypes.float16)\n x_checked = du.embed_check_integer_casting_closed(\n x, target_dtype=dtypes.int16)\n x_checked.eval(feed_dict={x: np.array([1, 1.5], dtype=np.float16)})\n\n @test_util.run_deprecated_v1\n def testCorrectlyAssertsLargestPossibleInteger(self):\n with self.cached_session():\n with self.assertRaisesOpError(\"Elements cannot exceed 32767.\"):\n x = array_ops.placeholder(dtype=dtypes.int32)\n x_checked = du.embed_check_integer_casting_closed(\n x, target_dtype=dtypes.int16)\n x_checked.eval(feed_dict={x: np.array([1, 2**15], dtype=np.int32)})\n\n @test_util.run_deprecated_v1\n def testCorrectlyAssertsSmallestPossibleInteger(self):\n with self.cached_session():\n with self.assertRaisesOpError(\"Elements cannot be smaller than 0.\"):\n x = array_ops.placeholder(dtype=dtypes.int32)\n x_checked = du.embed_check_integer_casting_closed(\n x, target_dtype=dtypes.uint16, assert_nonnegative=False)\n x_checked.eval(feed_dict={x: np.array([1, -1], dtype=np.int32)})\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass LogCombinationsTest(test.TestCase):\n\n def testLogCombinationsBinomial(self):\n n = [2, 5, 12, 15]\n k = [1, 2, 4, 11]\n\n if not special:\n return\n\n log_combs = np.log(special.binom(n, k))\n\n n = np.array(n, dtype=np.float32)\n counts = [[1., 1], [2., 3], [4., 8], [11, 4]]\n log_binom = du.log_combinations(n, counts)\n self.assertEqual([4], log_binom.get_shape())\n self.assertAllClose(log_combs, self.evaluate(log_binom))\n\n def testLogCombinationsShape(self):\n # Shape [2, 2]\n n = [[2, 5], [12, 15]]\n\n n = np.array(n, dtype=np.float32)\n # Shape [2, 2, 4]\n counts = [[[1., 1, 0, 0], [2., 2, 1, 0]], [[4., 4, 1, 3], [10, 1, 1, 4]]]\n log_binom = du.log_combinations(n, counts)\n self.assertEqual([2, 2], log_binom.get_shape())\n\n\nclass DynamicShapeTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testSameDynamicShape(self):\n with self.cached_session():\n scalar = constant_op.constant(2.0)\n scalar1 = array_ops.placeholder(dtype=dtypes.float32)\n\n vector = [0.3, 0.4, 0.5]\n vector1 = array_ops.placeholder(dtype=dtypes.float32, shape=[None])\n vector2 = array_ops.placeholder(dtype=dtypes.float32, shape=[None])\n\n multidimensional = [[0.3, 0.4], [0.2, 0.6]]\n multidimensional1 = array_ops.placeholder(\n dtype=dtypes.float32, shape=[None, None])\n multidimensional2 = array_ops.placeholder(\n dtype=dtypes.float32, shape=[None, None])\n\n # Scalar\n self.assertTrue(\n du.same_dynamic_shape(scalar, scalar1).eval({\n scalar1: 2.0\n }))\n\n # Vector\n\n self.assertTrue(\n du.same_dynamic_shape(vector, vector1).eval({\n vector1: [2.0, 3.0, 4.0]\n }))\n self.assertTrue(\n du.same_dynamic_shape(vector1, vector2).eval({\n vector1: [2.0, 3.0, 4.0],\n vector2: [2.0, 3.5, 6.0]\n }))\n\n # Multidimensional\n self.assertTrue(\n du.same_dynamic_shape(\n multidimensional, multidimensional1).eval({\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]]\n }))\n self.assertTrue(\n du.same_dynamic_shape(\n multidimensional1, multidimensional2).eval({\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]],\n multidimensional2: [[1.0, 3.5], [6.3, 2.3]]\n }))\n\n # Scalar, X\n self.assertFalse(\n du.same_dynamic_shape(scalar, vector1).eval({\n vector1: [2.0, 3.0, 4.0]\n }))\n self.assertFalse(\n du.same_dynamic_shape(scalar1, vector1).eval({\n scalar1: 2.0,\n vector1: [2.0, 3.0, 4.0]\n }))\n self.assertFalse(\n du.same_dynamic_shape(scalar, multidimensional1).eval({\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]]\n }))\n self.assertFalse(\n du.same_dynamic_shape(scalar1, multidimensional1).eval(\n {\n scalar1: 2.0,\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]]\n }))\n\n # Vector, X\n self.assertFalse(\n du.same_dynamic_shape(vector, vector1).eval({\n vector1: [2.0, 3.0]\n }))\n self.assertFalse(\n du.same_dynamic_shape(vector1, vector2).eval({\n vector1: [2.0, 3.0, 4.0],\n vector2: [6.0]\n }))\n self.assertFalse(\n du.same_dynamic_shape(vector, multidimensional1).eval({\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]]\n }))\n self.assertFalse(\n du.same_dynamic_shape(vector1, multidimensional1).eval(\n {\n vector1: [2.0, 3.0, 4.0],\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]]\n }))\n\n # Multidimensional, X\n self.assertFalse(\n du.same_dynamic_shape(\n multidimensional, multidimensional1).eval({\n multidimensional1: [[1.0, 3.5, 5.0], [6.3, 2.3, 7.1]]\n }))\n self.assertFalse(\n du.same_dynamic_shape(\n multidimensional1, multidimensional2).eval({\n multidimensional1: [[2.0, 3.0], [3.0, 4.0]],\n multidimensional2: [[1.0, 3.5, 5.0], [6.3, 2.3, 7.1]]\n }))\n\n\nclass RotateTransposeTest(test.TestCase):\n\n def _np_rotate_transpose(self, x, shift):\n if not isinstance(x, np.ndarray):\n x = np.array(x)\n return np.transpose(x, np.roll(np.arange(len(x.shape)), shift))\n\n @test_util.run_in_graph_and_eager_modes\n def testRollStatic(self):\n if context.executing_eagerly():\n error_message = r\"Attempt to convert a value \\(None\\)\"\n else:\n error_message = \"None values not supported.\"\n with self.assertRaisesRegexp(ValueError, error_message):\n du.rotate_transpose(None, 1)\n for x in (np.ones(1), np.ones((2, 1)), np.ones((3, 2, 1))):\n for shift in np.arange(-5, 5):\n y = du.rotate_transpose(x, shift)\n self.assertAllEqual(\n self._np_rotate_transpose(x, shift), self.evaluate(y))\n self.assertAllEqual(np.roll(x.shape, shift), y.get_shape().as_list())\n\n @test_util.run_deprecated_v1\n def testRollDynamic(self):\n with self.cached_session() as sess:\n x = array_ops.placeholder(dtypes.float32)\n shift = array_ops.placeholder(dtypes.int32)\n for x_value in (np.ones(\n 1, dtype=x.dtype.as_numpy_dtype()), np.ones(\n (2, 1), dtype=x.dtype.as_numpy_dtype()), np.ones(\n (3, 2, 1), dtype=x.dtype.as_numpy_dtype())):\n for shift_value in np.arange(-5, 5):\n self.assertAllEqual(\n self._np_rotate_transpose(x_value, shift_value),\n sess.run(du.rotate_transpose(x, shift),\n feed_dict={x: x_value,\n shift: shift_value}))\n\n\nclass PickVectorTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testCorrectlyPicksVector(self):\n with self.cached_session():\n x = np.arange(10, 12)\n y = np.arange(15, 18)\n self.assertAllEqual(\n x, self.evaluate(du.pick_vector(math_ops.less(0, 5), x, y)))\n self.assertAllEqual(\n y, self.evaluate(du.pick_vector(math_ops.less(5, 0), x, y)))\n self.assertAllEqual(x,\n du.pick_vector(\n constant_op.constant(True), x, y)) # No eval.\n self.assertAllEqual(y,\n du.pick_vector(\n constant_op.constant(False), x, y)) # No eval.\n\n\nclass PreferStaticRankTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testNonEmptyConstantTensor(self):\n x = array_ops.zeros((2, 3, 4))\n rank = du.prefer_static_rank(x)\n self.assertIsInstance(rank, np.ndarray)\n self.assertEqual(3, rank)\n\n @test_util.run_deprecated_v1\n def testEmptyConstantTensor(self):\n x = constant_op.constant([])\n rank = du.prefer_static_rank(x)\n self.assertIsInstance(rank, np.ndarray)\n self.assertEqual(1, rank)\n\n @test_util.run_deprecated_v1\n def testScalarTensor(self):\n x = constant_op.constant(1.)\n rank = du.prefer_static_rank(x)\n self.assertIsInstance(rank, np.ndarray)\n self.assertEqual(0, rank)\n\n @test_util.run_deprecated_v1\n def testDynamicRankEndsUpBeingNonEmpty(self):\n x = array_ops.placeholder(np.float64, shape=None)\n rank = du.prefer_static_rank(x)\n with self.cached_session():\n self.assertAllEqual(2, rank.eval(feed_dict={x: np.zeros((2, 3))}))\n\n @test_util.run_deprecated_v1\n def testDynamicRankEndsUpBeingEmpty(self):\n x = array_ops.placeholder(np.int32, shape=None)\n rank = du.prefer_static_rank(x)\n with self.cached_session():\n self.assertAllEqual(1, rank.eval(feed_dict={x: []}))\n\n @test_util.run_deprecated_v1\n def testDynamicRankEndsUpBeingScalar(self):\n x = array_ops.placeholder(np.int32, shape=None)\n rank = du.prefer_static_rank(x)\n with self.cached_session():\n self.assertAllEqual(0, rank.eval(feed_dict={x: 1}))\n\n\nclass PreferStaticShapeTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testNonEmptyConstantTensor(self):\n x = array_ops.zeros((2, 3, 4))\n shape = du.prefer_static_shape(x)\n self.assertIsInstance(shape, np.ndarray)\n self.assertAllEqual(np.array([2, 3, 4]), shape)\n\n @test_util.run_deprecated_v1\n def testEmptyConstantTensor(self):\n x = constant_op.constant([])\n shape = du.prefer_static_shape(x)\n self.assertIsInstance(shape, np.ndarray)\n self.assertAllEqual(np.array([0]), shape)\n\n @test_util.run_deprecated_v1\n def testScalarTensor(self):\n x = constant_op.constant(1.)\n shape = du.prefer_static_shape(x)\n self.assertIsInstance(shape, np.ndarray)\n self.assertAllEqual(np.array([]), shape)\n\n @test_util.run_deprecated_v1\n def testDynamicShapeEndsUpBeingNonEmpty(self):\n x = array_ops.placeholder(np.float64, shape=None)\n shape = du.prefer_static_shape(x)\n with self.cached_session():\n self.assertAllEqual((2, 3), shape.eval(feed_dict={x: np.zeros((2, 3))}))\n\n @test_util.run_deprecated_v1\n def testDynamicShapeEndsUpBeingEmpty(self):\n x = array_ops.placeholder(np.int32, shape=None)\n shape = du.prefer_static_shape(x)\n with self.cached_session():\n self.assertAllEqual(np.array([0]), shape.eval(feed_dict={x: []}))\n\n @test_util.run_deprecated_v1\n def testDynamicShapeEndsUpBeingScalar(self):\n x = array_ops.placeholder(np.int32, shape=None)\n shape = du.prefer_static_shape(x)\n with self.cached_session():\n self.assertAllEqual(np.array([]), shape.eval(feed_dict={x: 1}))\n\n\nclass PreferStaticValueTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testNonEmptyConstantTensor(self):\n x = array_ops.zeros((2, 3, 4))\n value = du.prefer_static_value(x)\n self.assertIsInstance(value, np.ndarray)\n self.assertAllEqual(np.zeros((2, 3, 4)), value)\n\n @test_util.run_deprecated_v1\n def testEmptyConstantTensor(self):\n x = constant_op.constant([])\n value = du.prefer_static_value(x)\n self.assertIsInstance(value, np.ndarray)\n self.assertAllEqual(np.array([]), value)\n\n @test_util.run_deprecated_v1\n def testScalarTensor(self):\n x = constant_op.constant(1.)\n value = du.prefer_static_value(x)\n self.assertIsInstance(value, np.ndarray)\n self.assertAllEqual(np.array(1.), value)\n\n @test_util.run_deprecated_v1\n def testDynamicValueEndsUpBeingNonEmpty(self):\n x = array_ops.placeholder(np.float64, shape=None)\n value = du.prefer_static_value(x)\n with self.cached_session():\n self.assertAllEqual(np.zeros((2, 3)),\n value.eval(feed_dict={x: np.zeros((2, 3))}))\n\n @test_util.run_deprecated_v1\n def testDynamicValueEndsUpBeingEmpty(self):\n x = array_ops.placeholder(np.int32, shape=None)\n value = du.prefer_static_value(x)\n with self.cached_session():\n self.assertAllEqual(np.array([]), value.eval(feed_dict={x: []}))\n\n @test_util.run_deprecated_v1\n def testDynamicValueEndsUpBeingScalar(self):\n x = array_ops.placeholder(np.int32, shape=None)\n value = du.prefer_static_value(x)\n with self.cached_session():\n self.assertAllEqual(np.array(1), value.eval(feed_dict={x: 1}))\n\n\nclass FillTriangularTest(test.TestCase):\n\n def setUp(self):\n self._rng = np.random.RandomState(42)\n\n def _fill_triangular(self, x, upper=False):\n \"\"\"Numpy implementation of `fill_triangular`.\"\"\"\n x = np.asarray(x)\n # Formula derived by solving for n: m = n(n+1)/2.\n m = np.int32(x.shape[-1])\n n = np.sqrt(0.25 + 2. * m) - 0.5\n if n != np.floor(n):\n raise ValueError(\"Invalid shape.\")\n n = np.int32(n)\n # We can't do: `x[..., -(n**2-m):]` because this doesn't correctly handle\n # `m == n == 1`. Hence, we do absolute indexing.\n x_tail = x[..., (m - (n * n - m)):]\n y = np.concatenate(\n [x, x_tail[..., ::-1]] if upper else [x_tail, x[..., ::-1]],\n axis=-1)\n y = y.reshape(np.concatenate([\n np.int32(x.shape[:-1]),\n np.int32([n, n]),\n ], axis=0))\n return np.triu(y) if upper else np.tril(y)\n\n def _run_test(self, x_, use_deferred_shape=False, **kwargs):\n x_ = np.asarray(x_)\n with self.cached_session() as sess:\n static_shape = None if use_deferred_shape else x_.shape\n x_pl = array_ops.placeholder_with_default(x_, shape=static_shape)\n # Add `zeros_like(x)` such that x's value and gradient are identical. We\n # do this so we can ensure each gradient value is mapped to the right\n # gradient location. (Not doing this means the gradient wrt `x` is simple\n # `ones_like(x)`.)\n # Note:\n # zeros_like_x_pl == zeros_like(x_pl)\n # gradient(zeros_like_x_pl, x_pl) == x_pl - 1\n zeros_like_x_pl = (x_pl * array_ops.stop_gradient(x_pl - 1.)\n - array_ops.stop_gradient(x_pl * (x_pl - 1.)))\n x = x_pl + zeros_like_x_pl\n actual = du.fill_triangular(x, **kwargs)\n grad_actual = gradients_impl.gradients(actual, x_pl)[0]\n [actual_, grad_actual_] = sess.run([actual, grad_actual],\n feed_dict={x_pl: x_})\n expected = self._fill_triangular(x_, **kwargs)\n if use_deferred_shape:\n self.assertEqual(None, actual.shape)\n else:\n self.assertAllEqual(expected.shape, actual.shape)\n self.assertAllClose(expected, actual_, rtol=1e-8, atol=1e-9)\n self.assertAllClose(x_, grad_actual_, rtol=1e-8, atol=1e-9)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakes1x1TriLower(self):\n self._run_test(self._rng.randn(3, int(1*2/2)))\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesNoBatchTriLower(self):\n self._run_test(self._rng.randn(int(4*5/2)))\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatchTriLower(self):\n self._run_test(self._rng.randn(2, 3, int(3*4/2)))\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatchTriLowerUnknownShape(self):\n self._run_test(self._rng.randn(2, 3, int(3*4/2)), use_deferred_shape=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatch7x7TriLowerUnknownShape(self):\n self._run_test(self._rng.randn(2, 3, int(7*8/2)), use_deferred_shape=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatch7x7TriLower(self):\n self._run_test(self._rng.randn(2, 3, int(7*8/2)))\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakes1x1TriUpper(self):\n self._run_test(self._rng.randn(3, int(1*2/2)), upper=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesNoBatchTriUpper(self):\n self._run_test(self._rng.randn(int(4*5/2)), upper=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatchTriUpper(self):\n self._run_test(self._rng.randn(2, 2, int(3*4/2)), upper=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatchTriUpperUnknownShape(self):\n self._run_test(self._rng.randn(2, 2, int(3*4/2)),\n use_deferred_shape=True,\n upper=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatch7x7TriUpperUnknownShape(self):\n self._run_test(self._rng.randn(2, 3, int(7*8/2)),\n use_deferred_shape=True,\n upper=True)\n\n @test_util.run_deprecated_v1\n def testCorrectlyMakesBatch7x7TriUpper(self):\n self._run_test(self._rng.randn(2, 3, int(7*8/2)), upper=True)\n\n\nclass FillTriangularInverseTest(FillTriangularTest):\n\n def _run_test(self, x_, use_deferred_shape=False, **kwargs):\n x_ = np.asarray(x_)\n with self.cached_session() as sess:\n static_shape = None if use_deferred_shape else x_.shape\n x_pl = array_ops.placeholder_with_default(x_, shape=static_shape)\n zeros_like_x_pl = (x_pl * array_ops.stop_gradient(x_pl - 1.)\n - array_ops.stop_gradient(x_pl * (x_pl - 1.)))\n x = x_pl + zeros_like_x_pl\n actual = du.fill_triangular(x, **kwargs)\n inverse_actual = du.fill_triangular_inverse(actual, **kwargs)\n\n inverse_actual_ = sess.run(\n inverse_actual,\n feed_dict={x_pl: x_})\n\n if use_deferred_shape:\n self.assertEqual(None, inverse_actual.shape)\n else:\n self.assertAllEqual(x_.shape, inverse_actual.shape)\n self.assertAllEqual(x_, inverse_actual_)\n\n\nclass ReduceWeightedLogSumExp(test.TestCase):\n\n def _reduce_weighted_logsumexp(self, logx, w, axis, keep_dims=False):\n m = np.max(logx, axis=axis, keepdims=True)\n sum_ = np.sum(w * np.exp(logx - m), axis=axis, keepdims=keep_dims)\n sgn = np.sign(sum_)\n if not keep_dims:\n m = np.squeeze(m, axis=axis)\n return m + np.log(sgn * sum_), sgn\n\n @test_util.run_deprecated_v1\n def testNoWeights(self):\n logx_ = np.array([[0., -1, 1000.],\n [0, 1, -1000.],\n [-5, 0, 5]])\n with self.cached_session() as sess:\n logx = constant_op.constant(logx_)\n expected = math_ops.reduce_logsumexp(logx, axis=-1)\n grad_expected = gradients_impl.gradients(expected, logx)[0]\n actual, actual_sgn = du.reduce_weighted_logsumexp(\n logx, axis=-1, return_sign=True)\n grad_actual = gradients_impl.gradients(actual, logx)[0]\n [actual_, actual_sgn_, grad_actual_,\n expected_, grad_expected_] = sess.run([\n actual, actual_sgn, grad_actual,\n expected, grad_expected])\n self.assertAllEqual(expected_, actual_)\n self.assertAllEqual(grad_expected_, grad_actual_)\n self.assertAllEqual([1., 1, 1], actual_sgn_)\n\n def testNegativeWeights(self):\n logx_ = np.array([[0., -1, 1000.],\n [0, 1, -1000.],\n [-5, 0, 5]])\n w_ = np.array([[1., 1, -1],\n [1, -2, 1],\n [1, 0, 1]])\n expected, _ = self._reduce_weighted_logsumexp(logx_, w_, axis=-1)\n with self.cached_session() as sess:\n logx = constant_op.constant(logx_)\n w = constant_op.constant(w_)\n actual, actual_sgn = du.reduce_weighted_logsumexp(\n logx, w, axis=-1, return_sign=True)\n [actual_, actual_sgn_] = self.evaluate([actual, actual_sgn])\n self.assertAllEqual(expected, actual_)\n self.assertAllEqual([-1., -1, 1], actual_sgn_)\n\n def testKeepDims(self):\n logx_ = np.array([[0., -1, 1000.],\n [0, 1, -1000.],\n [-5, 0, 5]])\n w_ = np.array([[1., 1, -1],\n [1, -2, 1],\n [1, 0, 1]])\n expected, _ = self._reduce_weighted_logsumexp(\n logx_, w_, axis=-1, keep_dims=True)\n with self.cached_session() as sess:\n logx = constant_op.constant(logx_)\n w = constant_op.constant(w_)\n actual, actual_sgn = du.reduce_weighted_logsumexp(\n logx, w, axis=-1, return_sign=True, keep_dims=True)\n [actual_, actual_sgn_] = self.evaluate([actual, actual_sgn])\n self.assertAllEqual(expected, actual_)\n self.assertAllEqual([[-1.], [-1], [1]], actual_sgn_)\n\n def testDocString(self):\n \"\"\"This test verifies the correctness of the docstring examples.\"\"\"\n\n with self.cached_session():\n x = constant_op.constant([[0., 0, 0],\n [0, 0, 0]])\n\n w = constant_op.constant([[-1., 1, 1],\n [1, 1, 1]])\n\n self.assertAllClose(\n np.log(4), self.evaluate(du.reduce_weighted_logsumexp(x, w)))\n\n with np.errstate(divide=\"ignore\"):\n self.assertAllClose(\n np.log([0, 2, 2]),\n self.evaluate(du.reduce_weighted_logsumexp(x, w, axis=0)))\n\n self.assertAllClose(\n np.log([1, 3]),\n self.evaluate(du.reduce_weighted_logsumexp(x, w, axis=1)))\n\n self.assertAllClose(\n np.log([[1], [3]]),\n self.evaluate(\n du.reduce_weighted_logsumexp(x, w, axis=1, keep_dims=True)))\n\n self.assertAllClose(\n np.log(4),\n self.evaluate(du.reduce_weighted_logsumexp(x, w, axis=[0, 1])))\n\n\nclass GenNewSeedTest(test.TestCase):\n\n def testOnlyNoneReturnsNone(self):\n self.assertFalse(du.gen_new_seed(0, \"salt\") is None)\n self.assertTrue(du.gen_new_seed(None, \"salt\") is None)\n\n\n# TODO(jvdillon): Merge this test back into:\n# tensorflow/python/kernel_tests/softplus_op_test.py\n# once TF core is accepting new ops.\nclass SoftplusTest(test.TestCase):\n\n def _npSoftplus(self, np_features):\n np_features = np.asarray(np_features)\n zero = np.asarray(0).astype(np_features.dtype)\n return np.logaddexp(zero, np_features)\n\n def _testSoftplus(self, np_features, use_gpu=False):\n np_features = np.asarray(np_features)\n np_softplus = self._npSoftplus(np_features)\n with self.session(use_gpu=use_gpu) as sess:\n softplus = nn_ops.softplus(np_features)\n softplus_inverse = du.softplus_inverse(softplus)\n [tf_softplus, tf_softplus_inverse] = sess.run([\n softplus, softplus_inverse])\n self.assertAllCloseAccordingToType(np_softplus, tf_softplus)\n rtol = {\"float16\": 0.07, \"float32\": 0.003, \"float64\": 0.002}.get(\n str(np_features.dtype), 1e-6)\n # This will test that we correctly computed the inverse by verifying we\n # recovered the original input.\n self.assertAllCloseAccordingToType(\n np_features, tf_softplus_inverse,\n atol=0., rtol=rtol)\n self.assertAllEqual(np.ones_like(tf_softplus).astype(np.bool),\n tf_softplus > 0)\n\n self.assertShapeEqual(np_softplus, softplus)\n self.assertShapeEqual(np_softplus, softplus_inverse)\n\n self.assertAllEqual(np.ones_like(tf_softplus).astype(np.bool),\n np.isfinite(tf_softplus))\n self.assertAllEqual(np.ones_like(tf_softplus_inverse).astype(np.bool),\n np.isfinite(tf_softplus_inverse))\n\n @test_util.run_deprecated_v1\n def testNumbers(self):\n for t in [np.float16, np.float32, np.float64]:\n lower = {np.float16: -15, np.float32: -50, np.float64: -50}.get(t, -100)\n upper = {np.float16: 50, np.float32: 50, np.float64: 50}.get(t, 100)\n self._testSoftplus(\n np.array(np.linspace(lower, upper, int(1e3)).astype(t)).reshape(\n [2, -1]),\n use_gpu=False)\n self._testSoftplus(\n np.array(np.linspace(lower, upper, int(1e3)).astype(t)).reshape(\n [2, -1]),\n use_gpu=True)\n log_eps = np.log(np.finfo(t).eps)\n one = t(1)\n ten = t(10)\n self._testSoftplus(\n [\n log_eps, log_eps - one, log_eps + one, log_eps - ten,\n log_eps + ten, -log_eps, -log_eps - one, -log_eps + one,\n -log_eps - ten, -log_eps + ten\n ],\n use_gpu=False)\n self._testSoftplus(\n [\n log_eps, log_eps - one, log_eps + one, log_eps - ten,\n log_eps + ten - log_eps, -log_eps - one, -log_eps + one,\n -log_eps - ten, -log_eps + ten\n ],\n use_gpu=True)\n\n @test_util.run_deprecated_v1\n def testGradient(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.softplus(x, name=\"softplus\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n tf_logging.vlog(2, \"softplus (float) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n @test_util.run_deprecated_v1\n def testInverseSoftplusGradientNeverNan(self):\n with self.cached_session():\n # Note that this range contains both zero and inf.\n x = constant_op.constant(np.logspace(-8, 6).astype(np.float16))\n y = du.softplus_inverse(x)\n grads = self.evaluate(gradients_impl.gradients(y, x)[0])\n # Equivalent to `assertAllFalse` (if it existed).\n self.assertAllEqual(np.zeros_like(grads).astype(np.bool), np.isnan(grads))\n\n @test_util.run_deprecated_v1\n def testInverseSoftplusGradientFinite(self):\n with self.cached_session():\n # This range of x is all finite, and so is 1 / x. So the\n # gradient and its approximations should be finite as well.\n x = constant_op.constant(np.logspace(-4.8, 4.5).astype(np.float16))\n y = du.softplus_inverse(x)\n grads = self.evaluate(gradients_impl.gradients(y, x)[0])\n # Equivalent to `assertAllTrue` (if it existed).\n self.assertAllEqual(\n np.ones_like(grads).astype(np.bool), np.isfinite(grads))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass ArgumentsTest(test.TestCase):\n\n def testNoArguments(self):\n def foo():\n return du.parent_frame_arguments()\n\n self.assertEqual({}, foo())\n\n def testPositionalArguments(self):\n def foo(a, b, c, d): # pylint: disable=unused-argument\n return du.parent_frame_arguments()\n\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}, foo(1, 2, 3, 4))\n\n # Tests that it does not matter where this function is called, and\n # no other local variables are returned back.\n def bar(a, b, c):\n unused_x = a * b\n unused_y = c * 3\n return du.parent_frame_arguments()\n\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3}, bar(1, 2, 3))\n\n def testOverloadedArgumentValues(self):\n def foo(a, b, c): # pylint: disable=unused-argument\n a = 42\n b = 31\n c = 42\n return du.parent_frame_arguments()\n self.assertEqual({\"a\": 42, \"b\": 31, \"c\": 42}, foo(1, 2, 3))\n\n def testKeywordArguments(self):\n def foo(**kwargs): # pylint: disable=unused-argument\n return du.parent_frame_arguments()\n\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}, foo(a=1, b=2, c=3, d=4))\n\n def testPositionalKeywordArgs(self):\n def foo(a, b, c, **kwargs): # pylint: disable=unused-argument\n return du.parent_frame_arguments()\n\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3}, foo(a=1, b=2, c=3))\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3, \"unicorn\": None},\n foo(a=1, b=2, c=3, unicorn=None))\n\n def testNoVarargs(self):\n def foo(a, b, c, *varargs, **kwargs): # pylint: disable=unused-argument\n return du.parent_frame_arguments()\n\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3}, foo(a=1, b=2, c=3))\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3}, foo(1, 2, 3, *[1, 2, 3]))\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3, \"unicorn\": None},\n foo(1, 2, 3, unicorn=None))\n self.assertEqual({\"a\": 1, \"b\": 2, \"c\": 3, \"unicorn\": None},\n foo(1, 2, 3, *[1, 2, 3], unicorn=None))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Utilities for calculating gradients.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport enum\n\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(\"UnconnectedGradients\")\nclass UnconnectedGradients(enum.Enum):\n \"\"\"Controls how gradient computation behaves when y does not depend on x.\n\n The gradient of y with respect to x can be zero in two different ways: there\n could be no differentiable path in the graph connecting x to y (and so we can\n statically prove that the gradient is zero) or it could be that runtime values\n of tensors in a particular execution lead to a gradient of zero (say, if a\n relu unit happens to not be activated). To allow you to distinguish between\n these two cases you can choose what value gets returned for the gradient when\n there is no path in the graph from x to y:\n\n * `NONE`: Indicates that [None] will be returned if there is no path from x\n to y\n * `ZERO`: Indicates that a zero tensor will be returned in the shape of x.\n \"\"\"\n NONE = \"none\"\n ZERO = \"zero\"\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for SoftmaxCrossEntropyWithLogits op.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\nimport sys\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\n\n\nclass XentTest(test.TestCase):\n\n def _npXent(self, features, labels, dim=-1):\n if dim == -1:\n dim = len(features.shape) - 1\n one_only_on_dim = list(features.shape)\n one_only_on_dim[dim] = 1\n e = np.exp(\n features - np.reshape(np.amax(features, axis=dim), one_only_on_dim))\n probs = e / np.reshape(np.sum(e, axis=dim), one_only_on_dim)\n bp = (probs - labels)\n l = -np.sum(labels * np.log(probs + 1.0e-20), axis=dim)\n return l, bp\n\n # TODO(b/123860949): The values are constant folded for XLA, so placeholders\n # are needed.\n def _testXent(self,\n np_features,\n np_labels,\n use_gpu=False,\n with_placeholders=False):\n np_loss, np_backprop = self._npXent(np_features, np_labels)\n with self.cached_session(use_gpu=use_gpu) as sess:\n if with_placeholders:\n features_placeholder = array_ops.placeholder(np_features.dtype)\n labels_placeholder = array_ops.placeholder(np_labels.dtype)\n loss, backprop = gen_nn_ops.softmax_cross_entropy_with_logits(\n labels=labels_placeholder, features=features_placeholder)\n tf_loss, tf_backprop = sess.run([loss, backprop],\n feed_dict={\n labels_placeholder: np_labels,\n features_placeholder: np_features\n })\n else:\n loss, backprop = gen_nn_ops.softmax_cross_entropy_with_logits(\n np_features, np_labels)\n tf_loss, tf_backprop = self.evaluate([loss, backprop])\n self.assertAllCloseAccordingToType(np_loss, tf_loss)\n self.assertAllCloseAccordingToType(np_backprop, tf_backprop)\n\n def _testXentWrapper(self, np_features, np_labels, dim=-1, use_gpu=False):\n np_loss, _ = self._npXent(np_features, np_labels, dim=dim)\n with self.cached_session(use_gpu=use_gpu) as sess:\n loss = nn_ops.softmax_cross_entropy_with_logits(\n labels=np_labels, logits=np_features, dim=dim)\n tf_loss = self.evaluate(loss)\n print(\"np_loss:\", np_loss)\n print(\"tf_loss:\", tf_loss)\n self.assertAllCloseAccordingToType(np_loss, tf_loss)\n\n # TODO(b/123860949): The values are constant folded for XLA, so placeholders\n # are needed.\n def _testAll(self, features, labels, with_placeholders=False):\n self._testXent(\n features, labels, use_gpu=False, with_placeholders=with_placeholders)\n self._testXent(\n features, labels, use_gpu=True, with_placeholders=with_placeholders)\n\n def _testSingleClass(self, use_gpu=False):\n for dtype in np.float16, np.float32:\n with self.cached_session(use_gpu=use_gpu) as sess:\n loss, backprop = gen_nn_ops.softmax_cross_entropy_with_logits(\n np.array([[1.], [-1.], [0.]]).astype(dtype),\n np.array([[-1.], [0.], [1.]]).astype(dtype))\n tf_loss, tf_backprop = self.evaluate([loss, backprop])\n self.assertAllClose([0.0, 0.0, 0.0], tf_loss)\n self.assertAllClose([[2.0], [1.0], [0.0]], tf_backprop)\n\n def testSingleClass(self):\n self._testSingleClass(True)\n self._testSingleClass(False)\n\n @test_util.run_deprecated_v1\n def testRankTooLarge(self):\n for dtype in np.float16, np.float32:\n np_features = np.array([[[1., 1., 1., 1.]], [[1., 2., 3.,\n 4.]]]).astype(dtype)\n np_labels = np.array([[[0., 0., 0., 1.]], [[0., .5, .5,\n 0.]]]).astype(dtype)\n self.assertRaisesRegexp(ValueError, \"rank 2, but is rank 3\",\n gen_nn_ops.softmax_cross_entropy_with_logits,\n np_features, np_labels)\n\n def testNpXent(self):\n # We create 2 batches of logits for testing.\n # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3.\n # batch 1 has a bit of difference: 1, 2, 3, 4, with soft targets (1, 2).\n features = [[1., 1., 1., 1.], [1., 2., 3., 4.]]\n labels = [[0., 0., 0., 1.], [0., .5, .5, 0.]]\n\n # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25\n # With a hard target 3, the backprop is [0.25, 0.25, 0.25, -0.75]\n # The loss for this batch is -log(0.25) = 1.386\n #\n # For batch 1, we have:\n # exp(0) = 1\n # exp(1) = 2.718\n # exp(2) = 7.389\n # exp(3) = 20.085\n # SUM = 31.192\n # So we have as probabilities:\n # exp(0) / SUM = 0.032\n # exp(1) / SUM = 0.087\n # exp(2) / SUM = 0.237\n # exp(3) / SUM = 0.644\n # With a soft target (1, 2), the backprop is\n # [0.032, 0.087 - 0.5 = -0.413, 0.237 - 0.5 = -0.263, 0.644]\n # The loss for this batch is [0.5 * -log(0.087), 0.5 * -log(0.237)]\n # = [1.3862, 1.9401]\n np_loss, np_backprop = self._npXent(np.array(features), np.array(labels))\n self.assertAllClose(\n np.array([[0.25, 0.25, 0.25, -0.75], [0.0321, -0.4129, -0.2632,\n 0.6439]]),\n np_backprop,\n rtol=1.e-3,\n atol=1.e-3)\n self.assertAllClose(\n np.array([1.3862, 1.9401]), np_loss, rtol=1.e-3, atol=1.e-3)\n\n def testShapeBroadcast(self):\n np_f = np.array([[1., 2., 3., 4.],\n [1., 2., 3., 4.]]).astype(np.float32)\n np_l = np.array([[0., 0., 0., 1.],\n [0., .5, .5, 0.]]).astype(np.float32)\n np_loss, np_backprop = self._npXent(np_f, np_l)\n tf_f = constant_op.constant(\n np.array([[1., 2., 3., 4.]]).astype(np.float32))\n tf_l = constant_op.constant(\n np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32))\n for use_gpu in [False, True]:\n with self.cached_session(use_gpu=use_gpu) as sess:\n loss, backprop = gen_nn_ops.softmax_cross_entropy_with_logits(\n tf_f, tf_l)\n tf_loss, tf_backprop = self.evaluate([loss, backprop])\n self.assertAllCloseAccordingToType(np_loss, tf_loss)\n self.assertAllCloseAccordingToType(np_backprop, tf_backprop)\n\n # TODO(b/123860949): The values are constant folded for XLA, so placeholders\n # are needed.\n @test_util.run_deprecated_v1\n def testFeatureBroadcast(self):\n self._testAll(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16),\n np.array([[0., 0., 0., 1.]]).astype(np.float16),\n with_placeholders=True)\n self._testAll(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16),\n np.array([[0.], [2.]]).astype(np.float16),\n with_placeholders=True)\n\n @test_util.run_deprecated_v1\n def testShapeMismatch(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n gen_nn_ops.softmax_cross_entropy_with_logits(\n [[0., 1.], [2., 3.]], [[0., 1., 0.], [1., 0., 0.]])\n\n @test_util.run_deprecated_v1\n def testNotMatrix(self):\n with self.cached_session():\n with self.assertRaises(ValueError):\n gen_nn_ops.softmax_cross_entropy_with_logits([0., 1., 2., 3.],\n [0., 1., 0., 1.])\n\n def testHalf(self):\n self._testAll(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16),\n np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float16))\n\n def testFloat(self):\n self._testAll(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32),\n np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32))\n\n def testDouble(self):\n self._testAll(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64),\n np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float64))\n\n @test_util.run_deprecated_v1\n def testGradient(self):\n with self.cached_session() as sess:\n l = constant_op.constant(\n [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"l\")\n f = constant_op.constant(\n [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"f\")\n x = nn_ops.softmax_cross_entropy_with_logits(\n labels=l, logits=f, name=\"xent\")\n err = gradient_checker.compute_gradient_error(f, [3, 4], x, [3])\n\n # Check that no extra computation performed. When only first derivative is requested,\n # second derivative must not be computed. So when there is no second derivative,\n # there is no `BatchMatMul` op in the graph.\n op_names = [\n op.op_def.name for op in sess.graph.get_operations() if op.op_def\n ]\n self.assertNotIn(\"BatchMatMul\", op_names)\n\n print(\"cross entropy gradient err = \", err)\n self.assertLess(err, 5e-8)\n\n @test_util.run_deprecated_v1\n def testGradientLabelWithV2(self):\n with self.cached_session():\n l = constant_op.constant(\n [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"l\")\n f = constant_op.constant(\n [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"f\")\n x = nn_ops.softmax_cross_entropy_with_logits_v2(\n labels=l, logits=f, name=\"xent\")\n err = gradient_checker.compute_gradient_error(l, [3, 4], x, [3])\n\n self.assertLess(err, 5e-8)\n\n @test_util.run_deprecated_v1\n def testSecondGradient(self):\n with self.cached_session() as sess:\n l = constant_op.constant(\n [\n 0.0, 0.0, 1.0 / 3, 0.0, 1.0 / 3, 0.0, 0.0, 0.0, 0.0, 0.5 / 3, 0.0,\n 0.5 / 3\n ],\n shape=[12],\n dtype=dtypes.float64,\n name=\"l\")\n f = constant_op.constant(\n [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],\n shape=[12],\n dtype=dtypes.float64,\n name=\"f\")\n x = nn_ops.softmax_cross_entropy_with_logits(\n labels=l, logits=f, name=\"xent\")\n loss = math_ops.reduce_sum(x)\n\n gradients = gradients_impl.gradients(loss, [f])[0]\n\n err = gradient_checker.compute_gradient_error(f, [12], gradients, [12])\n\n # Check that second derivative is calculated.\n # (it is equivalent to being `BatchMatMul` op in the graph because of implementation of xentropy grad)\n op_names = [\n op.op_def.name for op in sess.graph.get_operations() if op.op_def\n ]\n if compat.forward_compatible(2019, 4, 25):\n self.assertIn(\"BatchMatMulV2\", op_names)\n else:\n self.assertIn(\"BatchMatMul\", op_names)\n\n print(\"cross entropy hessian err = \", err)\n self.assertLess(err, 5e-8)\n\n def testWrapper(self):\n features = np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]],\n [[2., 3., 4., 5.], [6., 7., 8., 9.]],\n [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(\n np.float32)\n labels = np.array([[[0., 0., 0., 1.], [0., 1., 0., 0.]],\n [[0., 0.5, 0.5, 0.], [0.5, 0.5, 0., 0.]],\n [[0., 1., 0., 0.], [0., 0., 1., 0.]]]).astype(\n np.float32)\n self._testXentWrapper(features, labels, dim=0, use_gpu=False)\n self._testXentWrapper(features, labels, dim=0, use_gpu=True)\n self._testXentWrapper(features, labels, dim=1, use_gpu=False)\n self._testXentWrapper(features, labels, dim=1, use_gpu=True)\n self._testXentWrapper(features, labels, dim=-1, use_gpu=False)\n self._testXentWrapper(features, labels, dim=-1, use_gpu=True)\n\n def testZeroDimension(self):\n features = np.zeros([0, 2, 4]).astype(np.float32)\n labels = np.zeros([0, 2, 4]).astype(np.float32)\n np_loss, _ = self._npXent(features, labels)\n with self.session(use_gpu=True) as sess:\n loss = nn_ops.softmax_cross_entropy_with_logits(\n labels=labels, logits=features)\n tf_loss = self.evaluate(loss)\n self.assertAllEqual(np_loss, tf_loss)\n\n\nclass XentBenchmark(test.Benchmark):\n\n def benchmarkZeroDimension(self):\n for (m, n, p, use_gpu) in itertools.product(\n [128],\n [10, 100, 1000, 10000, 100000],\n [0.001, 0.01, 0.5, 0.99, 1.0],\n [False]):\n k = int(p * n)\n if k == 0:\n continue\n name = \"zero_dimension_m_%d_n_%d_k_%g_use_gpu_%s\" % (m, n, k, use_gpu)\n device = \"/%s:0\" % (\"gpu\" if use_gpu else \"cpu\")\n with ops.Graph().as_default():\n with ops.device(device):\n labels = array_ops.zeros([0, 2, 4], dtype=dtypes.float32)\n logits = array_ops.zeros([0, 2, 4], dtype=dtypes.float32)\n op = nn_ops.softmax_cross_entropy_with_logits(\n labels=labels, logits=logits)\n with session.Session() as sess:\n r = self.run_op_benchmark(sess, op, min_iters=100, name=name)\n gb_processed_input = m * n / 1.0e9\n throughput = gb_processed_input / r[\"wall_time\"]\n print(\"Benchmark: %s \\t wall_time: %0.03g s \\t \"\n \"Throughput: %0.03g GB/s\" % (name, r[\"wall_time\"], throughput))\n sys.stdout.flush()\n\n def benchmarkSingleClass(self):\n for (m, n, p, use_gpu) in itertools.product(\n [128],\n [10, 100, 1000, 10000, 100000],\n [0.001, 0.01, 0.5, 0.99, 1.0],\n [False]):\n k = int(p * n)\n if k == 0:\n continue\n name = \"single_class_m_%d_n_%d_k_%g_use_gpu_%s\" % (m, n, k, use_gpu)\n device = \"/%s:0\" % (\"gpu\" if use_gpu else \"cpu\")\n with ops.Graph().as_default():\n with ops.device(device):\n labels = constant_op.constant([[1.], [-1.], [0.]],\n dtype=dtypes.float32)\n logits = constant_op.constant([[-1.], [0.], [1.]],\n dtype=dtypes.float32)\n op = nn_ops.softmax_cross_entropy_with_logits(\n labels=labels, logits=logits)\n with session.Session() as sess:\n r = self.run_op_benchmark(sess, op, min_iters=100, name=name)\n gb_processed_input = m * n / 1.0e9\n throughput = gb_processed_input / r[\"wall_time\"]\n print(\"Benchmark: %s \\t wall_time: %0.03g s \\t \"\n \"Throughput: %0.03g GB/s\" % (name, r[\"wall_time\"], throughput))\n sys.stdout.flush()\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# python3\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for liveness module, that only run in Python 3.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.autograph.pyct.static_analysis import annos\nfrom tensorflow.python.autograph.pyct.static_analysis import liveness_test\nfrom tensorflow.python.platform import test\n\n\nNodeAnno = annos.NodeAnno\n\n\nclass LivenessAnalyzerTest(liveness_test.LivenessAnalyzerTestBase):\n \"\"\"Tests which can only run in Python 3.\"\"\"\n\n def test_nonlocal_symbol(self):\n\n nonlocal_a = 3\n nonlocal_b = 13\n\n def test_fn(c):\n nonlocal nonlocal_a\n nonlocal nonlocal_b\n if nonlocal_a:\n nonlocal_b = c\n else:\n nonlocal_b = c\n return nonlocal_b\n\n node = self._parse_and_analyze(test_fn)\n fn_body = node.body\n self.assertHasLiveOut(fn_body[2], ('nonlocal_b',))\n self.assertHasLiveIn(fn_body[2], ('nonlocal_a', 'c'))\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `tf.data.Iterator` using distributed sessions.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.platform import test\n\n\nclass IteratorClusterTest(test.TestCase):\n\n @test_util.run_v1_only(\"b/120545219\")\n def testRemoteIteratorWithoutRemoteCallFail(self):\n worker_config = config_pb2.ConfigProto()\n worker_config.device_count[\"CPU\"] = 2\n worker, _ = test_util.create_local_cluster(\n 1, 1, worker_config=worker_config)\n\n with ops.device(\"/job:worker/replica:0/task:0/cpu:1\"):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_3_handle = iterator_3.string_handle()\n\n with ops.device(\"/job:worker/replica:0/task:0/cpu:0\"):\n remote_it = iterator_ops.Iterator.from_string_handle(\n iterator_3_handle, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n get_next_op = remote_it.get_next()\n\n with session.Session(worker[0].target) as sess:\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(get_next_op)\n\n def _testRemoteIteratorHelper(self, device0, device1, target):\n with ops.device(device1):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_3_handle = iterator_3.string_handle()\n\n @function.Defun(dtypes.string)\n def _remote_fn(h):\n remote_iterator = iterator_ops.Iterator.from_string_handle(\n h, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n return remote_iterator.get_next()\n\n with ops.device(device0):\n target_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n remote_op = functional_ops.remote_call(\n args=[iterator_3_handle],\n Tout=[dtypes.int32],\n f=_remote_fn,\n target=target_placeholder)\n\n with session.Session(target) as sess:\n elem = sess.run(remote_op, feed_dict={target_placeholder: device1})\n self.assertEqual(elem, [1])\n # Fails when target is cpu:0 where the resource is not located.\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(remote_op, feed_dict={target_placeholder: device0})\n elem = sess.run(iterator_3.get_next())\n self.assertEqual(elem, [2])\n elem = sess.run(remote_op, feed_dict={target_placeholder: device1})\n self.assertEqual(elem, [3])\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(remote_op, feed_dict={target_placeholder: device1})\n\n @test_util.run_v1_only(\"b/120545219\")\n def testRemoteIteratorUsingRemoteCallOp(self):\n worker_config = config_pb2.ConfigProto()\n worker_config.device_count[\"CPU\"] = 2\n worker, _ = test_util.create_local_cluster(\n 1, 1, worker_config=worker_config)\n\n self._testRemoteIteratorHelper(\"/job:worker/replica:0/task:0/cpu:0\",\n \"/job:worker/replica:0/task:0/cpu:1\",\n worker[0].target)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testRemoteIteratorUsingRemoteCallOpCrossProcess(self):\n workers, _ = test_util.create_local_cluster(2, 1)\n\n self._testRemoteIteratorHelper(\"/job:worker/replica:0/task:0/cpu:0\",\n \"/job:worker/replica:0/task:1/cpu:0\",\n workers[0].target)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testCaptureHashTableInSharedIterator(self):\n worker, _ = test_util.create_local_cluster(1, 1)\n\n # NOTE(mrry): We must use the V2 variants of `HashTable`\n # etc. because these produce a `tf.resource`-typed output that is\n # compatible with the in-graph function implementation.\n default_val = -1\n keys = constant_op.constant([\"brain\", \"salad\", \"surgery\"])\n values = constant_op.constant([0, 1, 2], dtypes.int64)\n table = lookup_ops.StaticHashTableV1(\n lookup_ops.KeyValueTensorInitializer(keys, values),\n default_val)\n\n input_sentences = dataset_ops.Dataset.from_tensor_slices(\n [\"brain brain tank salad surgery\", \"surgery brain\"])\n\n iterator = (\n input_sentences.map(lambda x: string_ops.string_split([x]).values).map(\n table.lookup)\n .make_initializable_iterator(shared_name=\"shared_iterator\"))\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with session.Session(worker[0].target) as sess:\n sess.run(table.initializer)\n sess.run(init_op)\n self.assertAllEqual([0, 0, -1, 1, 2], sess.run(get_next))\n\n with session.Session(worker[0].target) as sess:\n self.assertAllEqual([2, 0], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testImplicitDisposeParallelMapDataset(self):\n # Tests whether a parallel map dataset will be cleaned up correctly when\n # the pipeline does not run it until exhaustion.\n # The pipeline is TensorSliceDataset -> MapDataset(square_3) ->\n # RepeatDataset(None) -> PrefetchDataset(100).\n worker, _ = test_util.create_local_cluster(1, 1)\n\n components = (np.arange(1000),\n np.array([[1, 2, 3]]) * np.arange(1000)[:, np.newaxis],\n np.array(37.0) * np.arange(1000))\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(components).map(_map_fn)\n .repeat(None).prefetch(10000))\n\n iterator = dataset_ops.make_initializable_iterator(dataset)\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with session.Session(worker[0].target) as sess:\n sess.run(init_op)\n for _ in range(3):\n sess.run(get_next)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# =============================================================================\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Tests for decode_proto op.\"\"\"\n\n# Python3 preparedness imports.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\n\nfrom google.protobuf import text_format\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.kernel_tests.proto import proto_op_test_base as test_base\nfrom tensorflow.python.kernel_tests.proto import test_example_pb2\n\n\nclass DecodeProtoOpTestBase(test_base.ProtoOpTestBase, parameterized.TestCase):\n \"\"\"Base class for testing proto decoding ops.\"\"\"\n\n def __init__(self, decode_module, methodName='runTest'): # pylint: disable=invalid-name\n \"\"\"DecodeProtoOpTestBase initializer.\n\n Args:\n decode_module: a module containing the `decode_proto_op` method\n methodName: the name of the test method (same as for test.TestCase)\n \"\"\"\n\n super(DecodeProtoOpTestBase, self).__init__(methodName)\n self._decode_module = decode_module\n\n def _compareValues(self, fd, vs, evs):\n \"\"\"Compare lists/arrays of field values.\"\"\"\n\n if len(vs) != len(evs):\n self.fail('Field %s decoded %d outputs, expected %d' %\n (fd.name, len(vs), len(evs)))\n for i, ev in enumerate(evs):\n # Special case fuzzy match for float32. TensorFlow seems to mess with\n # MAX_FLT slightly and the test doesn't work otherwise.\n # TODO(nix): ask on TF list about why MAX_FLT doesn't pass through.\n if fd.cpp_type == fd.CPPTYPE_FLOAT:\n # Numpy isclose() is better than assertIsClose() which uses an absolute\n # value comparison.\n self.assertTrue(\n np.isclose(vs[i], ev), 'expected %r, actual %r' % (ev, vs[i]))\n elif fd.cpp_type == fd.CPPTYPE_STRING:\n # In Python3 string tensor values will be represented as bytes, so we\n # reencode the proto values to match that.\n self.assertEqual(vs[i], ev.encode('ascii'))\n else:\n # Doubles and other types pass through unscathed.\n self.assertEqual(vs[i], ev)\n\n def _compareProtos(self, batch_shape, sizes, fields, field_dict):\n \"\"\"Compare protos of type TestValue.\n\n Args:\n batch_shape: the shape of the input tensor of serialized messages.\n sizes: int matrix of repeat counts returned by decode_proto\n fields: list of test_example_pb2.FieldSpec (types and expected values)\n field_dict: map from field names to decoded numpy tensors of values\n \"\"\"\n\n # Check that expected values match.\n for field in fields:\n values = field_dict[field.name]\n self.assertEqual(dtypes.as_dtype(values.dtype), field.dtype)\n\n if 'ext_value' in field.name:\n fd = test_example_pb2.PrimitiveValue()\n else:\n fd = field.value.DESCRIPTOR.fields_by_name[field.name]\n\n # Values has the same shape as the input plus an extra\n # dimension for repeats.\n self.assertEqual(list(values.shape)[:-1], batch_shape)\n\n # Nested messages are represented as TF strings, requiring\n # some special handling.\n if field.name == 'message_value' or 'ext_value' in field.name:\n vs = []\n for buf in values.flat:\n msg = test_example_pb2.PrimitiveValue()\n msg.ParseFromString(buf)\n vs.append(msg)\n if 'ext_value' in field.name:\n evs = field.value.Extensions[test_example_pb2.ext_value]\n else:\n evs = getattr(field.value, field.name)\n if len(vs) != len(evs):\n self.fail('Field %s decoded %d outputs, expected %d' %\n (fd.name, len(vs), len(evs)))\n for v, ev in zip(vs, evs):\n self.assertEqual(v, ev)\n continue\n\n tf_type_to_primitive_value_field = {\n dtypes.bool:\n 'bool_value',\n dtypes.float32:\n 'float_value',\n dtypes.float64:\n 'double_value',\n dtypes.int8:\n 'int8_value',\n dtypes.int32:\n 'int32_value',\n dtypes.int64:\n 'int64_value',\n dtypes.string:\n 'string_value',\n dtypes.uint8:\n 'uint8_value',\n dtypes.uint32:\n 'uint32_value',\n dtypes.uint64:\n 'uint64_value',\n }\n if field.name in ['enum_value', 'enum_value_with_default']:\n tf_field_name = 'enum_value'\n else:\n tf_field_name = tf_type_to_primitive_value_field.get(field.dtype)\n if tf_field_name is None:\n self.fail('Unhandled tensorflow type %d' % field.dtype)\n\n self._compareValues(fd, values.flat,\n getattr(field.value, tf_field_name))\n\n def _runDecodeProtoTests(self, fields, case_sizes, batch_shape, batch,\n message_type, message_format, sanitize,\n force_disordered=False):\n \"\"\"Run decode tests on a batch of messages.\n\n Args:\n fields: list of test_example_pb2.FieldSpec (types and expected values)\n case_sizes: expected sizes array\n batch_shape: the shape of the input tensor of serialized messages\n batch: list of serialized messages\n message_type: descriptor name for messages\n message_format: format of messages, 'text' or 'binary'\n sanitize: whether to sanitize binary protobuf inputs\n force_disordered: whether to force fields encoded out of order.\n \"\"\"\n\n if force_disordered:\n # Exercise code path that handles out-of-order fields by prepending extra\n # fields with tag numbers higher than any real field. Note that this won't\n # work with sanitization because that forces reserialization using a\n # trusted decoder and encoder.\n assert not sanitize\n extra_fields = test_example_pb2.ExtraFields()\n extra_fields.string_value = 'IGNORE ME'\n extra_fields.bool_value = False\n extra_msg = extra_fields.SerializeToString()\n batch = [extra_msg + msg for msg in batch]\n\n # Numpy silently truncates the strings if you don't specify dtype=object.\n batch = np.array(batch, dtype=object)\n batch = np.reshape(batch, batch_shape)\n\n field_names = [f.name for f in fields]\n output_types = [f.dtype for f in fields]\n\n with self.cached_session() as sess:\n sizes, vtensor = self._decode_module.decode_proto(\n batch,\n message_type=message_type,\n field_names=field_names,\n output_types=output_types,\n message_format=message_format,\n sanitize=sanitize)\n\n vlist = sess.run([sizes] + vtensor)\n sizes = vlist[0]\n # Values is a list of tensors, one for each field.\n value_tensors = vlist[1:]\n\n # Check that the repeat sizes are correct.\n self.assertTrue(\n np.all(np.array(sizes.shape) == batch_shape + [len(field_names)]))\n\n # Check that the decoded sizes match the expected sizes.\n self.assertEqual(len(sizes.flat), len(case_sizes))\n self.assertTrue(\n np.all(sizes.flat == np.array(\n case_sizes, dtype=np.int32)))\n\n field_dict = dict(zip(field_names, value_tensors))\n\n self._compareProtos(batch_shape, sizes, fields, field_dict)\n\n @parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())\n def testBinary(self, case):\n batch = [value.SerializeToString() for value in case.values]\n self._runDecodeProtoTests(\n case.fields,\n case.sizes,\n list(case.shapes),\n batch,\n 'tensorflow.contrib.proto.TestValue',\n 'binary',\n sanitize=False)\n\n @parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())\n def testBinaryDisordered(self, case):\n batch = [value.SerializeToString() for value in case.values]\n self._runDecodeProtoTests(\n case.fields,\n case.sizes,\n list(case.shapes),\n batch,\n 'tensorflow.contrib.proto.TestValue',\n 'binary',\n sanitize=False,\n force_disordered=True)\n\n @parameterized.named_parameters(\n *test_base.ProtoOpTestBase.named_parameters(extension=False))\n def testPacked(self, case):\n # Now try with the packed serialization.\n #\n # We test the packed representations by loading the same test case using\n # PackedTestValue instead of TestValue. To do this we rely on the text\n # format being the same for packed and unpacked fields, and reparse the\n # test message using the packed version of the proto.\n packed_batch = [\n # Note: float_format='.17g' is necessary to ensure preservation of\n # doubles and floats in text format.\n text_format.Parse(\n text_format.MessageToString(value, float_format='.17g'),\n test_example_pb2.PackedTestValue()).SerializeToString()\n for value in case.values\n ]\n\n self._runDecodeProtoTests(\n case.fields,\n case.sizes,\n list(case.shapes),\n packed_batch,\n 'tensorflow.contrib.proto.PackedTestValue',\n 'binary',\n sanitize=False)\n\n @parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())\n def testText(self, case):\n # Note: float_format='.17g' is necessary to ensure preservation of\n # doubles and floats in text format.\n text_batch = [\n text_format.MessageToString(\n value, float_format='.17g') for value in case.values\n ]\n\n self._runDecodeProtoTests(\n case.fields,\n case.sizes,\n list(case.shapes),\n text_batch,\n 'tensorflow.contrib.proto.TestValue',\n 'text',\n sanitize=False)\n\n @parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())\n def testSanitizerGood(self, case):\n batch = [value.SerializeToString() for value in case.values]\n self._runDecodeProtoTests(\n case.fields,\n case.sizes,\n list(case.shapes),\n batch,\n 'tensorflow.contrib.proto.TestValue',\n 'binary',\n sanitize=True)\n\n @parameterized.parameters((False), (True))\n def testCorruptProtobuf(self, sanitize):\n corrupt_proto = 'This is not a binary protobuf'\n\n # Numpy silently truncates the strings if you don't specify dtype=object.\n batch = np.array(corrupt_proto, dtype=object)\n msg_type = 'tensorflow.contrib.proto.TestCase'\n field_names = ['sizes']\n field_types = [dtypes.int32]\n\n with self.assertRaisesRegexp(\n errors.DataLossError, 'Unable to parse binary protobuf'\n '|Failed to consume entire buffer'):\n self.evaluate(\n self._decode_module.decode_proto(\n batch,\n message_type=msg_type,\n field_names=field_names,\n output_types=field_types,\n sanitize=sanitize))\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for ragged.rank op.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom absl.testing import parameterized\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops.ragged import ragged_array_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import googletest\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass RaggedRankOpTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n @parameterized.parameters([\n # Rank 0\n dict(\n test_input=1,\n expected_rank=0,\n ),\n # Rank 1\n dict(\n test_input=[1],\n expected_rank=1,\n ),\n dict(\n test_input=[1, 2, 3, 4],\n expected_rank=1,\n ),\n # Rank 2\n dict(\n test_input=[[1], [2], [3]],\n expected_rank=2,\n ),\n # Rank 3\n dict(\n test_input=[[[1], [2, 3]], [[4], [5, 6, 7]]],\n expected_rank=3,\n ),\n # Rank 3, ragged_rank=2\n dict(\n test_input=[[[1], [2, 3], [10, 20]],\n [[4], [5, 6, 7]]],\n expected_rank=3,\n ragged_rank=2,\n ),\n # Rank 4, ragged_rank=3 with dimensions: {2, (1, 2), (2), (1, 2)}\n dict(\n test_input=[[[[1], [2]]],\n [[[3, 4], [5, 6]], [[7, 8], [9, 10]]]],\n expected_rank=4,\n ),\n # Rank 4, ragged_rank=2 with dimensions: {2, (1, 2), (1, 2), 2}\n dict(\n test_input=[\n [[[1, 2]]],\n [[[5, 6], [7, 8]],\n [[9, 10], [11, 12]]]],\n expected_rank=4,\n ragged_rank=2,\n ),\n\n ])\n def testRaggedRank(self, test_input, expected_rank, ragged_rank=None):\n test_input = ragged_factory_ops.constant(\n test_input, ragged_rank=ragged_rank)\n self.assertAllEqual(ragged_array_ops.rank(\n test_input), expected_rank)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the InterleaveDataset serialization.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.kernel_tests.serialization import dataset_serialization_test_base\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import test\n\n\nclass InterleaveDatasetSerializationTest(\n dataset_serialization_test_base.DatasetSerializationTestBase,\n parameterized.TestCase):\n\n def _build_iterator_graph(self, input_values, cycle_length, block_length,\n num_parallel_calls):\n repeat_count = 2\n return dataset_ops.Dataset.from_tensor_slices(input_values).repeat(\n repeat_count).interleave(\n lambda x: dataset_ops.Dataset.from_tensors(x).repeat(x),\n cycle_length, block_length, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n cycle_length=2,\n block_length=[1, 3],\n num_parallel_calls=[None, 1, 2])))\n def testSerializationCore(self, cycle_length, block_length,\n num_parallel_calls):\n input_values = np.array([4, 5, 6], dtype=np.int64)\n num_outputs = np.sum(input_values) * 2\n # pylint: disable=g-long-lambda\n self.run_core_tests(\n lambda: self._build_iterator_graph(\n input_values, cycle_length, block_length, num_parallel_calls),\n num_outputs)\n # pylint: enable=g-long-lambda\n\n @combinations.generate(test_base.default_test_combinations())\n def testSparseCore(self):\n\n def _map_fn(i):\n return sparse_tensor.SparseTensorValue(\n indices=[[0, 0], [1, 1]], values=(i * [1, -1]), dense_shape=[2, 2])\n\n def _interleave_fn(x):\n return dataset_ops.Dataset.from_tensor_slices(\n sparse_ops.sparse_to_dense(x.indices, x.dense_shape, x.values))\n\n def _build_dataset():\n return dataset_ops.Dataset.range(10).map(_map_fn).interleave(\n _interleave_fn, cycle_length=1)\n\n self.run_core_tests(_build_dataset, 20)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Experimental API for manually injecting delays into `tf.data` pipelines.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.ops import gen_experimental_dataset_ops\n\n\nclass _SleepDataset(dataset_ops.UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that sleeps before producing each upstream element.\"\"\"\n\n def __init__(self, input_dataset, sleep_microseconds):\n self._input_dataset = input_dataset\n self._sleep_microseconds = sleep_microseconds\n variant_tensor = gen_experimental_dataset_ops.sleep_dataset(\n self._input_dataset._variant_tensor, # pylint: disable=protected-access\n self._sleep_microseconds,\n **self._flat_structure)\n super(_SleepDataset, self).__init__(input_dataset, variant_tensor)\n\n\ndef sleep(sleep_microseconds):\n \"\"\"Sleeps for `sleep_microseconds` before producing each input element.\n\n Args:\n sleep_microseconds: The number of microseconds to sleep before producing an\n input element.\n\n Returns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.\n \"\"\"\n\n def _apply_fn(dataset):\n return _SleepDataset(dataset, sleep_microseconds)\n\n return _apply_fn\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Public Python API of TensorFlow Debugger (tfdbg).\n\nSee the [TFDBG](https://www.tensorflow.org/guide/debugger) guide.\n\n@@add_debug_tensor_watch\n@@watch_graph\n@@watch_graph_with_blacklists\n@@DebugTensorDatum\n@@DebugDumpDir\n@@load_tensor_from_event\n@@load_tensor_from_event_file\n@@has_inf_or_nan\n@@DumpingDebugHook\n@@DumpingDebugWrapperSession\n@@GrpcDebugHook\n@@GrpcDebugWrapperSession\n@@LocalCLIDebugHook\n@@LocalCLIDebugWrapperSession\n@@TensorBoardDebugHook\n@@TensorBoardDebugWrapperSession\n@@WatchOptions\n\n@@reconstruct_non_debug_graph_def\n\n@@GradientsDebugger\n@@clear_gradient_debuggers\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint: disable=unused-imports\nfrom tensorflow.python.debug.lib.debug_data import DebugDumpDir\nfrom tensorflow.python.debug.lib.debug_data import DebugTensorDatum\nfrom tensorflow.python.debug.lib.debug_data import has_inf_or_nan\nfrom tensorflow.python.debug.lib.debug_data import load_tensor_from_event\nfrom tensorflow.python.debug.lib.debug_data import load_tensor_from_event_file\n\nfrom tensorflow.python.debug.lib.debug_gradients import GradientsDebugger\n\nfrom tensorflow.python.debug.lib.debug_graphs import reconstruct_non_debug_graph_def\n\nfrom tensorflow.python.debug.lib.debug_utils import add_debug_tensor_watch\nfrom tensorflow.python.debug.lib.debug_utils import watch_graph\nfrom tensorflow.python.debug.lib.debug_utils import watch_graph_with_blacklists\n\nfrom tensorflow.python.debug.wrappers.dumping_wrapper import DumpingDebugWrapperSession\nfrom tensorflow.python.debug.wrappers.framework import WatchOptions\nfrom tensorflow.python.debug.wrappers.grpc_wrapper import GrpcDebugWrapperSession\nfrom tensorflow.python.debug.wrappers.grpc_wrapper import TensorBoardDebugWrapperSession\nfrom tensorflow.python.debug.wrappers.hooks import DumpingDebugHook\nfrom tensorflow.python.debug.wrappers.hooks import GrpcDebugHook\nfrom tensorflow.python.debug.wrappers.hooks import LocalCLIDebugHook\nfrom tensorflow.python.debug.wrappers.hooks import TensorBoardDebugHook\nfrom tensorflow.python.debug.wrappers.local_cli_wrapper import LocalCLIDebugWrapperSession\n\nfrom tensorflow.python.util import all_util as _all_util\n\n\n_all_util.remove_undocumented(__name__)\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"tfdbg example: debugging tf.keras models training on tf.data.Dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\nimport tempfile\n\nimport numpy as np\nimport tensorflow\n\nfrom tensorflow.python import debug as tf_debug\n\ntf = tensorflow.compat.v1\n\n\ndef main(_):\n # Create a dummy dataset.\n num_examples = 8\n steps_per_epoch = 2\n input_dims = 3\n output_dims = 1\n xs = np.zeros([num_examples, input_dims])\n ys = np.zeros([num_examples, output_dims])\n dataset = tf.data.Dataset.from_tensor_slices(\n (xs, ys)).repeat(num_examples).batch(int(num_examples / steps_per_epoch))\n\n sess = tf.Session()\n if FLAGS.debug:\n # Use the command-line interface (CLI) of tfdbg.\n config_file_path = (\n tempfile.mktemp(\".tfdbg_config\")\n if FLAGS.use_random_config_path else None)\n sess = tf_debug.LocalCLIDebugWrapperSession(\n sess, ui_type=FLAGS.ui_type, config_file_path=config_file_path)\n elif FLAGS.tensorboard_debug_address:\n # Use the TensorBoard Debugger Plugin (GUI of tfdbg).\n sess = tf_debug.TensorBoardDebugWrapperSession(\n sess, FLAGS.tensorboard_debug_address)\n tf.keras.backend.set_session(sess)\n\n # Create a dummy model.\n model = tf.keras.Sequential(\n [tf.keras.layers.Dense(1, input_shape=[input_dims])])\n model.compile(loss=\"mse\", optimizer=\"sgd\")\n\n # Train the model using the dummy dataset created above.\n model.fit(dataset, epochs=FLAGS.epochs, steps_per_epoch=steps_per_epoch)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.register(\"type\", \"bool\", lambda v: v.lower() == \"true\")\n parser.add_argument(\n \"--debug\",\n type=\"bool\",\n nargs=\"?\",\n const=True,\n default=False,\n help=\"Use debugger to track down bad values during training. \"\n \"Mutually exclusive with the --tensorboard_debug_address flag.\")\n parser.add_argument(\n \"--ui_type\",\n type=str,\n default=\"curses\",\n help=\"Command-line user interface type (curses | readline).\")\n parser.add_argument(\n \"--use_random_config_path\",\n type=\"bool\",\n nargs=\"?\",\n const=True,\n default=False,\n help=\"\"\"If set, set config file path to a random file in the temporary\n directory.\"\"\")\n parser.add_argument(\n \"--tensorboard_debug_address\",\n type=str,\n default=None,\n help=\"Connect to the TensorBoard Debugger Plugin backend specified by \"\n \"the gRPC address (e.g., localhost:1234). Mutually exclusive with the \"\n \"--debug flag.\")\n parser.add_argument(\n \"--epochs\",\n type=int,\n default=2,\n help=\"Number of epochs to train the model for.\")\n FLAGS, unparsed = parser.parse_known_args()\n with tf.Graph().as_default():\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.linalg_ops.eig.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes as dtypes_lib\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import test\n\n\ndef _AddTest(test_class, op_name, testcase_name, fn):\n test_name = \"_\".join([\"test\", op_name, testcase_name])\n if hasattr(test_class, test_name):\n raise RuntimeError(\"Test %s defined more than once\" % test_name)\n setattr(test_class, test_name, fn)\n\n\nclass EigTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testWrongDimensions(self):\n # The input to self_adjoint_eig should be a tensor of\n # at least rank 2.\n scalar = constant_op.constant(1.)\n with self.assertRaises(ValueError):\n linalg_ops.eig(scalar)\n vector = constant_op.constant([1., 2.])\n with self.assertRaises(ValueError):\n linalg_ops.eig(vector)\n\n @test_util.run_deprecated_v1\n def testConcurrentExecutesWithoutError(self):\n all_ops = []\n with self.session(use_gpu=True) as sess:\n for compute_v_ in True, False:\n matrix1 = random_ops.random_normal([5, 5], seed=42)\n matrix2 = random_ops.random_normal([5, 5], seed=42)\n if compute_v_:\n e1, v1 = linalg_ops.eig(matrix1)\n e2, v2 = linalg_ops.eig(matrix2)\n all_ops += [e1, v1, e2, v2]\n else:\n e1 = linalg_ops.eigvals(matrix1)\n e2 = linalg_ops.eigvals(matrix2)\n all_ops += [e1, e2]\n val = self.evaluate(all_ops)\n self.assertAllEqual(val[0], val[2])\n # The algorithm is slightly different for compute_v being True and False,\n # so require approximate equality only here.\n self.assertAllClose(val[2], val[4])\n self.assertAllEqual(val[4], val[5])\n self.assertAllEqual(val[1], val[3])\n\n def testMatrixThatFailsWhenFlushingDenormsToZero(self):\n # Test a 32x32 matrix which is known to fail if denorm floats are flushed to\n # zero.\n matrix = np.genfromtxt(\n test.test_src_dir_path(\n \"python/kernel_tests/testdata/\"\n \"self_adjoint_eig_fail_if_denorms_flushed.txt\")).astype(np.float32)\n self.assertEqual(matrix.shape, (32, 32))\n matrix_tensor = constant_op.constant(matrix)\n with self.session(use_gpu=True) as sess:\n (e, v) = self.evaluate(linalg_ops.self_adjoint_eig(matrix_tensor))\n self.assertEqual(e.size, 32)\n self.assertAllClose(\n np.matmul(v, v.transpose()), np.eye(32, dtype=np.float32), atol=2e-3)\n self.assertAllClose(matrix,\n np.matmul(np.matmul(v, np.diag(e)), v.transpose()))\n\n\ndef SortEigenValues(e):\n perm = np.argsort(e.real + e.imag, -1)\n return np.take(e, perm, -1)\n\n\ndef SortEigenDecomposition(e, v):\n if v.ndim < 2:\n return e, v\n else:\n perm = np.argsort(e.real + e.imag, -1)\n return np.take(e, perm, -1), np.take(v, perm, -1)\n\n\ndef EquilibrateEigenVectorPhases(x, y):\n \"\"\"Equilibrate the phase of the Eigenvectors in the columns of `x` and `y`.\n\n Eigenvectors are only unique up to an arbitrary phase. This function rotates x\n such that it matches y. Precondition: The coluns of x and y differ by a\n multiplicative complex phase factor only.\n\n Args:\n x: `np.ndarray` with Eigenvectors\n y: `np.ndarray` with Eigenvectors\n\n Returns:\n `np.ndarray` containing an equilibrated version of x.\n \"\"\"\n phases = np.sum(np.conj(x) * y, -2, keepdims=True)\n phases /= np.abs(phases)\n return phases * x\n\n\ndef _GetEigTest(dtype_, shape_, compute_v_):\n\n def CompareEigenVectors(self, x, y, tol):\n x = EquilibrateEigenVectorPhases(x, y)\n self.assertAllClose(x, y, atol=tol)\n\n def CompareEigenDecompositions(self, x_e, x_v, y_e, y_v, tol):\n num_batches = int(np.prod(x_e.shape[:-1]))\n n = x_e.shape[-1]\n x_e = np.reshape(x_e, [num_batches] + [n])\n x_v = np.reshape(x_v, [num_batches] + [n, n])\n y_e = np.reshape(y_e, [num_batches] + [n])\n y_v = np.reshape(y_v, [num_batches] + [n, n])\n for i in range(num_batches):\n x_ei, x_vi = SortEigenDecomposition(x_e[i, :], x_v[i, :, :])\n y_ei, y_vi = SortEigenDecomposition(y_e[i, :], y_v[i, :, :])\n self.assertAllClose(x_ei, y_ei, atol=tol, rtol=tol)\n CompareEigenVectors(self, x_vi, y_vi, tol)\n\n def Test(self):\n np.random.seed(1)\n n = shape_[-1]\n batch_shape = shape_[:-2]\n np_dtype = dtype_.as_numpy_dtype\n # most of matrices are diagonalizable # TODO\n a = np.random.uniform(\n low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)\n if dtype_.is_complex:\n a += 1j * np.random.uniform(\n low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)\n a = np.tile(a, batch_shape + (1, 1))\n if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):\n atol = 1e-4\n else:\n atol = 1e-12\n np_e, np_v = np.linalg.eig(a)\n with self.session(use_gpu=True):\n if compute_v_:\n tf_e, tf_v = linalg_ops.eig(constant_op.constant(a))\n\n # Check that V*diag(E)*V^(-1) is close to A.\n a_ev = math_ops.matmul(\n math_ops.matmul(tf_v, array_ops.matrix_diag(tf_e)),\n linalg_ops.matrix_inverse(tf_v))\n self.assertAllClose(self.evaluate(a_ev), a, atol=atol)\n\n # Compare to numpy.linalg.eig.\n CompareEigenDecompositions(self, np_e, np_v, self.evaluate(tf_e),\n self.evaluate(tf_v), atol)\n else:\n tf_e = linalg_ops.eigvals(constant_op.constant(a))\n self.assertAllClose(\n SortEigenValues(np_e),\n SortEigenValues(self.evaluate(tf_e)),\n atol=atol)\n\n return Test\n\n\nif __name__ == \"__main__\":\n dtypes_to_test = [dtypes_lib.float32, dtypes_lib.float64]\n if not test.is_built_with_rocm():\n # ROCm does not support BLAS operations for complex types\n dtypes_to_test += [dtypes_lib.complex64, dtypes_lib.complex128]\n for compute_v in True, False:\n for dtype in dtypes_to_test:\n for size in 1, 2, 5, 10:\n for batch_dims in [(), (3,)] + [(3, 2)] * (max(size, size) < 10):\n shape = batch_dims + (size, size)\n name = \"%s_%s_%s\" % (dtype.name, \"_\".join(map(str, shape)), compute_v)\n _AddTest(EigTest, \"Eig\", name, _GetEigTest(dtype, shape, compute_v))\n # No gradient yet\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.python.framework.tensorboard_logging.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport os\nimport shutil\nimport tempfile\nimport time\n\nfrom tensorflow.core.util import event_pb2\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.summary import summary_iterator\nfrom tensorflow.python.summary.writer import writer\nfrom tensorflow.python.training import tensorboard_logging\n\n\n@test_util.run_deprecated_v1\nclass EventLoggingTest(test.TestCase):\n\n def setUp(self):\n self._work_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n self._sw = writer.FileWriter(self._work_dir)\n tensorboard_logging.set_summary_writer(self._sw)\n self.addCleanup(shutil.rmtree, self._work_dir)\n\n # Stop the clock to avoid test flakiness.\n now = time.time()\n time._real_time = time.time\n time.time = lambda: now\n\n # Mock out logging calls so we can verify that the right number of messages\n # get logged.\n self.logged_message_count = 0\n self._actual_log = logging.log\n\n def mockLog(*args, **kwargs):\n self.logged_message_count += 1\n self._actual_log(*args, **kwargs)\n\n logging.log = mockLog\n\n def tearDown(self):\n time.time = time._real_time\n logging.log = self._actual_log\n\n def assertLoggedMessagesAre(self, expected_messages):\n self._sw.close()\n event_paths = glob.glob(os.path.join(self._work_dir, \"event*\"))\n # If the tests runs multiple time in the same directory we can have\n # more than one matching event file. We only want to read the last one.\n self.assertTrue(event_paths)\n event_reader = summary_iterator.summary_iterator(event_paths[-1])\n # Skip over the version event.\n next(event_reader)\n\n for level, message in expected_messages:\n event = next(event_reader)\n self.assertEqual(event.wall_time, time.time())\n self.assertEqual(event.log_message.level, level)\n self.assertEqual(event.log_message.message, message)\n\n def testBasic(self):\n tensorboard_logging.set_summary_writer(self._sw)\n tensorboard_logging.error(\"oh no!\")\n tensorboard_logging.error(\"for%s\", \"mat\")\n\n self.assertLoggedMessagesAre([(event_pb2.LogMessage.ERROR, \"oh no!\"),\n (event_pb2.LogMessage.ERROR, \"format\")])\n self.assertEqual(2, self.logged_message_count)\n\n def testVerbosity(self):\n tensorboard_logging.set_summary_writer(self._sw)\n tensorboard_logging.set_verbosity(tensorboard_logging.ERROR)\n tensorboard_logging.warn(\"warn\")\n tensorboard_logging.error(\"error\")\n tensorboard_logging.set_verbosity(tensorboard_logging.DEBUG)\n tensorboard_logging.debug(\"debug\")\n\n self.assertLoggedMessagesAre([(event_pb2.LogMessage.ERROR, \"error\"),\n (event_pb2.LogMessage.DEBUGGING, \"debug\")])\n # All message should be logged because tensorboard_logging verbosity doesn't\n # affect logging verbosity.\n self.assertEqual(3, self.logged_message_count)\n\n def testBadVerbosity(self):\n with self.assertRaises(ValueError):\n tensorboard_logging.set_verbosity(\"failure\")\n\n with self.assertRaises(ValueError):\n tensorboard_logging.log(\"bad\", \"dead\")\n\n def testNoSummaryWriter(self):\n \"\"\"Test that logging without a SummaryWriter succeeds.\"\"\"\n tensorboard_logging.set_summary_writer(None)\n tensorboard_logging.warn(\"this should work\")\n self.assertEqual(1, self.logged_message_count)\n\n def testSummaryWriterFailsAfterClear(self):\n tensorboard_logging._clear_summary_writer()\n with self.assertRaises(RuntimeError):\n tensorboard_logging.log(tensorboard_logging.ERROR, \"failure\")\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Raw ops tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import gen_math_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass RawOpsTest(test.TestCase):\n\n def testSimple(self):\n x = constant_op.constant(1)\n self.assertEqual([2], self.evaluate(gen_math_ops.Add(x=x, y=x)))\n\n def testRequiresKwargs(self):\n with self.assertRaisesRegexp(TypeError, \"only takes keyword args\"):\n gen_math_ops.Add(1., 1.)\n\n def testRequiresKwargs_providesSuggestion(self):\n msg = \"possible keys: \\\\['x', 'y', 'name'\\\\]\"\n with self.assertRaisesRegexp(TypeError, msg):\n gen_math_ops.Add(1., y=2.)\n\n def testName(self):\n x = constant_op.constant(1)\n op = gen_math_ops.Add(x=x, y=x, name=\"double\")\n if not context.executing_eagerly():\n # `Tensor.name` is not available in eager.\n self.assertEqual(op.name, \"double:0\")\n\n def testDoc(self):\n self.assertEqual(gen_math_ops.add.__doc__, gen_math_ops.Add.__doc__)\n\n def testDefaults(self):\n x = constant_op.constant([[True]])\n self.assertAllClose(\n gen_math_ops.Any(input=x, axis=0),\n gen_math_ops.Any(input=x, axis=0, keep_dims=False))\n\n\nif __name__ == \"__main__\":\n ops.enable_eager_execution()\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for a little bit of strategy_combinations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.distribute import combinations\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.distribute import strategy_combinations\nfrom tensorflow.python.framework import config\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.platform import test\n\n\nclass StrategyCombinationsTest(test.TestCase, parameterized.TestCase):\n\n def setUp(self):\n # Need to call set_virtual_cpus_to_at_least() in setUp with the maximum\n # value needed in any test.\n strategy_combinations.set_virtual_cpus_to_at_least(3)\n super(StrategyCombinationsTest, self).setUp()\n\n def test3VirtualCPUs(self):\n cpu_device = config.list_physical_devices(\"CPU\")[0]\n self.assertLen(config.get_virtual_device_configuration(cpu_device), 3)\n\n def testSetVirtualCPUsAgain(self):\n strategy_combinations.set_virtual_cpus_to_at_least(2)\n cpu_device = config.list_physical_devices(\"CPU\")[0]\n self.assertLen(config.get_virtual_device_configuration(cpu_device), 3)\n\n def testSetVirtualCPUsErrors(self):\n with self.assertRaises(ValueError):\n strategy_combinations.set_virtual_cpus_to_at_least(0)\n with self.assertRaisesRegexp(RuntimeError, \"with 3 < 5 virtual CPUs\"):\n strategy_combinations.set_virtual_cpus_to_at_least(5)\n\n @combinations.generate(combinations.combine(\n distribution=[strategy_combinations.mirrored_strategy_with_cpu_1_and_2],\n mode=[\"graph\", \"eager\"]))\n def testMirrored2CPUs(self, distribution):\n with distribution.scope():\n one_per_replica = distribution.experimental_run_v2(\n lambda: constant_op.constant(1))\n num_replicas = distribution.reduce(\n reduce_util.ReduceOp.SUM, one_per_replica, axis=None)\n self.assertEqual(2, self.evaluate(num_replicas))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Benchmark for accumulate_n() in math_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport random\nimport time\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import gen_control_flow_ops\nfrom tensorflow.python.ops import gen_state_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.platform import test\n\n\nclass AccumulateNBenchmark(test.Benchmark):\n\n def _AccumulateNTemplate(self, inputs, init, shape, validate_shape):\n var = gen_state_ops.temporary_variable(\n shape=shape, dtype=inputs[0].dtype.base_dtype)\n ref = state_ops.assign(var, init, validate_shape=validate_shape)\n update_ops = [\n state_ops.assign_add(\n ref, tensor, use_locking=True).op for tensor in inputs\n ]\n with ops.control_dependencies(update_ops):\n return gen_state_ops.destroy_temporary_variable(ref, var_name=var.op.name)\n\n def _AccumulateNInitializedWithFirst(self, inputs):\n return self._AccumulateNTemplate(\n inputs,\n init=array_ops.zeros_like(inputs[0]),\n shape=inputs[0].get_shape(),\n validate_shape=True)\n\n def _AccumulateNInitializedWithMerge(self, inputs):\n return self._AccumulateNTemplate(\n inputs,\n init=array_ops.zeros_like(gen_control_flow_ops.merge(inputs)[0]),\n shape=tensor_shape.TensorShape([0]),\n validate_shape=False)\n\n def _AccumulateNInitializedWithShape(self, inputs):\n return self._AccumulateNTemplate(\n inputs,\n init=array_ops.zeros(\n shape=inputs[0].get_shape(), dtype=inputs[0].dtype.base_dtype),\n shape=inputs[0].get_shape(),\n validate_shape=True)\n\n def _GenerateUnorderedInputs(self, size, n):\n inputs = [random_ops.random_uniform(shape=[size]) for _ in xrange(n)]\n random.shuffle(inputs)\n return inputs\n\n def _GenerateReplicatedInputs(self, size, n):\n return n * self._GenerateUnorderedInputs(size, 1)\n\n def _GenerateOrderedInputs(self, size, n):\n inputs = self._GenerateUnorderedInputs(size, 1)\n queue = data_flow_ops.FIFOQueue(\n capacity=1, dtypes=[inputs[0].dtype], shapes=[inputs[0].get_shape()])\n for _ in xrange(n - 1):\n op = queue.enqueue(inputs[-1])\n with ops.control_dependencies([op]):\n inputs.append(math_ops.tanh(1.0 + queue.dequeue()))\n return inputs\n\n def _GenerateReversedInputs(self, size, n):\n inputs = self._GenerateOrderedInputs(size, n)\n inputs.reverse()\n return inputs\n\n def _SetupAndRunBenchmark(self, graph, inputs, repeats, format_args):\n with graph.as_default():\n add_n = math_ops.add_n(inputs)\n acc_n_first = self._AccumulateNInitializedWithFirst(inputs)\n acc_n_merge = self._AccumulateNInitializedWithMerge(inputs)\n acc_n_shape = self._AccumulateNInitializedWithShape(inputs)\n\n test_ops = ((\"AddN\", add_n.op),\n (\"AccNFirst\", acc_n_first.op),\n (\"AccNMerge\", acc_n_merge.op),\n (\"AccNShape\", acc_n_shape.op))\n\n with session.Session(graph=graph):\n for tag, op in test_ops:\n for _ in xrange(100):\n op.run() # Run for warm up.\n start = time.time()\n for _ in xrange(repeats):\n op.run()\n duration = time.time() - start\n args = format_args + (tag, duration)\n print(self._template.format(*args))\n\n def _RunBenchmark(self, tag, input_fn, sizes, ninputs, repeats):\n for size in sizes:\n for ninput in ninputs:\n graph = ops.Graph()\n with graph.as_default():\n inputs = input_fn(size, ninput)\n\n format_args = (tag, size, ninput, repeats)\n self._SetupAndRunBenchmark(graph, inputs, repeats, format_args)\n\n def benchmarkAccumulateN(self):\n self._template = \"{:<15}\" * 6\n args = {\n \"sizes\": (128, 128**2),\n \"ninputs\": (1, 10, 100, 300),\n \"repeats\": 100\n }\n benchmarks = ((\"Replicated\", self._GenerateReplicatedInputs),\n (\"Unordered\", self._GenerateUnorderedInputs),\n (\"Ordered\", self._GenerateOrderedInputs),\n (\"Reversed\", self._GenerateReversedInputs))\n\n print(self._template.format(\"\", \"Size\", \"#Inputs\", \"#Repeat\", \"Method\",\n \"Duration\"))\n print(\"-\" * 90)\n for benchmark in benchmarks:\n self._RunBenchmark(*benchmark, **args)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variables as variables_module\nfrom tensorflow.python.ops.linalg import linalg as linalg_lib\nfrom tensorflow.python.ops.linalg import linear_operator_test_util\nfrom tensorflow.python.platform import test\n\n\nrng = np.random.RandomState(2016)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass LinearOperatorZerosTest(\n linear_operator_test_util.SquareLinearOperatorDerivedClassTest):\n \"\"\"Most tests done in the base class LinearOperatorDerivedClassTest.\"\"\"\n\n @staticmethod\n def skip_these_tests():\n return [\n \"cholesky\", \"log_abs_det\", \"inverse\", \"solve\", \"solve_with_broadcast\"]\n\n @staticmethod\n def operator_shapes_infos():\n shapes_info = linear_operator_test_util.OperatorShapesInfo\n return [\n shapes_info((1, 1)),\n shapes_info((1, 3, 3)),\n shapes_info((3, 4, 4)),\n shapes_info((2, 1, 4, 4))]\n\n def operator_and_matrix(\n self, build_info, dtype, use_placeholder,\n ensure_self_adjoint_and_pd=False):\n del ensure_self_adjoint_and_pd\n del use_placeholder\n shape = list(build_info.shape)\n assert shape[-1] == shape[-2]\n\n batch_shape = shape[:-2]\n num_rows = shape[-1]\n\n operator = linalg_lib.LinearOperatorZeros(\n num_rows, batch_shape=batch_shape, dtype=dtype)\n matrix = array_ops.zeros(shape=shape, dtype=dtype)\n\n return operator, matrix\n\n def test_assert_positive_definite(self):\n operator = linalg_lib.LinearOperatorZeros(num_rows=2)\n with self.assertRaisesOpError(\"non-positive definite\"):\n operator.assert_positive_definite()\n\n def test_assert_non_singular(self):\n with self.assertRaisesOpError(\"non-invertible\"):\n operator = linalg_lib.LinearOperatorZeros(num_rows=2)\n operator.assert_non_singular()\n\n def test_assert_self_adjoint(self):\n with self.cached_session():\n operator = linalg_lib.LinearOperatorZeros(num_rows=2)\n self.evaluate(operator.assert_self_adjoint()) # Should not fail\n\n def test_non_scalar_num_rows_raises_static(self):\n with self.assertRaisesRegexp(ValueError, \"must be a 0-D Tensor\"):\n linalg_lib.LinearOperatorZeros(num_rows=[2])\n with self.assertRaisesRegexp(ValueError, \"must be a 0-D Tensor\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, num_columns=[2])\n\n def test_non_integer_num_rows_raises_static(self):\n with self.assertRaisesRegexp(TypeError, \"must be integer\"):\n linalg_lib.LinearOperatorZeros(num_rows=2.)\n with self.assertRaisesRegexp(TypeError, \"must be integer\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, num_columns=2.)\n\n def test_negative_num_rows_raises_static(self):\n with self.assertRaisesRegexp(ValueError, \"must be non-negative\"):\n linalg_lib.LinearOperatorZeros(num_rows=-2)\n with self.assertRaisesRegexp(ValueError, \"must be non-negative\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, num_columns=-2)\n\n def test_non_1d_batch_shape_raises_static(self):\n with self.assertRaisesRegexp(ValueError, \"must be a 1-D\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, batch_shape=2)\n\n def test_non_integer_batch_shape_raises_static(self):\n with self.assertRaisesRegexp(TypeError, \"must be integer\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, batch_shape=[2.])\n\n def test_negative_batch_shape_raises_static(self):\n with self.assertRaisesRegexp(ValueError, \"must be non-negative\"):\n linalg_lib.LinearOperatorZeros(num_rows=2, batch_shape=[-2])\n\n def test_non_scalar_num_rows_raises_dynamic(self):\n with self.cached_session():\n num_rows = array_ops.placeholder_with_default([2], shape=None)\n with self.assertRaisesError(\"must be a 0-D Tensor\"):\n operator = linalg_lib.LinearOperatorZeros(\n num_rows, assert_proper_shapes=True)\n self.evaluate(operator.to_dense())\n\n def test_negative_num_rows_raises_dynamic(self):\n with self.cached_session():\n n = array_ops.placeholder_with_default(-2, shape=None)\n with self.assertRaisesError(\"must be non-negative\"):\n operator = linalg_lib.LinearOperatorZeros(\n num_rows=n, assert_proper_shapes=True)\n self.evaluate(operator.to_dense())\n\n def test_non_1d_batch_shape_raises_dynamic(self):\n with self.cached_session():\n batch_shape = array_ops.placeholder_with_default(2, shape=None)\n with self.assertRaisesError(\"must be a 1-D\"):\n operator = linalg_lib.LinearOperatorZeros(\n num_rows=2, batch_shape=batch_shape, assert_proper_shapes=True)\n self.evaluate(operator.to_dense())\n\n def test_negative_batch_shape_raises_dynamic(self):\n with self.cached_session():\n batch_shape = array_ops.placeholder_with_default([-2], shape=None)\n with self.assertRaisesError(\"must be non-negative\"):\n operator = linalg_lib.LinearOperatorZeros(\n num_rows=2, batch_shape=batch_shape, assert_proper_shapes=True)\n self.evaluate(operator.to_dense())\n\n def test_wrong_matrix_dimensions_raises_static(self):\n operator = linalg_lib.LinearOperatorZeros(num_rows=2)\n x = rng.randn(3, 3).astype(np.float32)\n with self.assertRaisesRegexp(ValueError, \"Dimensions.*not compatible\"):\n operator.matmul(x)\n\n def test_wrong_matrix_dimensions_raises_dynamic(self):\n num_rows = array_ops.placeholder_with_default(2, shape=None)\n x = array_ops.placeholder_with_default(rng.rand(3, 3), shape=None)\n\n with self.cached_session():\n with self.assertRaisesError(\"Dimensions.*not.compatible\"):\n operator = linalg_lib.LinearOperatorZeros(\n num_rows, assert_proper_shapes=True, dtype=dtypes.float64)\n self.evaluate(operator.matmul(x))\n\n def test_is_x_flags(self):\n # The is_x flags are by default all True.\n operator = linalg_lib.LinearOperatorZeros(num_rows=2)\n self.assertFalse(operator.is_positive_definite)\n self.assertFalse(operator.is_non_singular)\n self.assertTrue(operator.is_self_adjoint)\n\n def test_zeros_matmul(self):\n operator1 = linalg_lib.LinearOperatorIdentity(num_rows=2)\n operator2 = linalg_lib.LinearOperatorZeros(num_rows=2)\n self.assertTrue(isinstance(\n operator1.matmul(operator2),\n linalg_lib.LinearOperatorZeros))\n\n self.assertTrue(isinstance(\n operator2.matmul(operator1),\n linalg_lib.LinearOperatorZeros))\n\n def test_ref_type_shape_args_raises(self):\n with self.assertRaisesRegexp(TypeError, \"num_rows.cannot.be.reference\"):\n linalg_lib.LinearOperatorZeros(num_rows=variables_module.Variable(2))\n\n with self.assertRaisesRegexp(TypeError, \"num_columns.cannot.be.reference\"):\n linalg_lib.LinearOperatorZeros(\n num_rows=2, num_columns=variables_module.Variable(3))\n\n with self.assertRaisesRegexp(TypeError, \"batch_shape.cannot.be.reference\"):\n linalg_lib.LinearOperatorZeros(\n num_rows=2, batch_shape=variables_module.Variable([2]))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass LinearOperatorZerosNotSquareTest(\n linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):\n\n def operator_and_matrix(self, build_info, dtype, use_placeholder):\n del use_placeholder\n shape = list(build_info.shape)\n\n batch_shape = shape[:-2]\n num_rows = shape[-2]\n num_columns = shape[-1]\n\n operator = linalg_lib.LinearOperatorZeros(\n num_rows, num_columns, is_square=False, is_self_adjoint=False,\n batch_shape=batch_shape, dtype=dtype)\n matrix = array_ops.zeros(shape=shape, dtype=dtype)\n\n return operator, matrix\n\n\nif __name__ == \"__main__\":\n linear_operator_test_util.add_tests(LinearOperatorZerosTest)\n linear_operator_test_util.add_tests(LinearOperatorZerosNotSquareTest)\n test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Smoke test for reading records from GCS to TensorFlow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport random\nimport sys\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.python.lib.io import file_io\n\nflags = tf.compat.v1.app.flags\nflags.DEFINE_string(\"gcs_bucket_url\", \"\",\n \"The URL to the GCS bucket in which the temporary \"\n \"tfrecord file is to be written and read, e.g., \"\n \"gs://my-gcs-bucket/test-directory\")\nflags.DEFINE_integer(\"num_examples\", 10, \"Number of examples to generate\")\n\nFLAGS = flags.FLAGS\n\n\ndef create_examples(num_examples, input_mean):\n \"\"\"Create ExampleProto's containing data.\"\"\"\n ids = np.arange(num_examples).reshape([num_examples, 1])\n inputs = np.random.randn(num_examples, 1) + input_mean\n target = inputs - input_mean\n examples = []\n for row in range(num_examples):\n ex = example_pb2.Example()\n ex.features.feature[\"id\"].bytes_list.value.append(str(ids[row, 0]))\n ex.features.feature[\"target\"].float_list.value.append(target[row, 0])\n ex.features.feature[\"inputs\"].float_list.value.append(inputs[row, 0])\n examples.append(ex)\n return examples\n\n\ndef create_dir_test():\n \"\"\"Verifies file_io directory handling methods.\"\"\"\n\n # Test directory creation.\n starttime_ms = int(round(time.time() * 1000))\n dir_name = \"%s/tf_gcs_test_%s\" % (FLAGS.gcs_bucket_url, starttime_ms)\n print(\"Creating dir %s\" % dir_name)\n file_io.create_dir(dir_name)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Created directory in: %d milliseconds\" % elapsed_ms)\n\n # Check that the directory exists.\n dir_exists = file_io.is_directory(dir_name)\n assert dir_exists\n print(\"%s directory exists: %s\" % (dir_name, dir_exists))\n\n # Test recursive directory creation.\n starttime_ms = int(round(time.time() * 1000))\n recursive_dir_name = \"%s/%s/%s\" % (dir_name,\n \"nested_dir1\",\n \"nested_dir2\")\n print(\"Creating recursive dir %s\" % recursive_dir_name)\n file_io.recursive_create_dir(recursive_dir_name)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Created directory recursively in: %d milliseconds\" % elapsed_ms)\n\n # Check that the directory exists.\n recursive_dir_exists = file_io.is_directory(recursive_dir_name)\n assert recursive_dir_exists\n print(\"%s directory exists: %s\" % (recursive_dir_name, recursive_dir_exists))\n\n # Create some contents in the just created directory and list the contents.\n num_files = 10\n files_to_create = [\"file_%d.txt\" % n for n in range(num_files)]\n for file_num in files_to_create:\n file_name = \"%s/%s\" % (dir_name, file_num)\n print(\"Creating file %s.\" % file_name)\n file_io.write_string_to_file(file_name, \"test file.\")\n\n print(\"Listing directory %s.\" % dir_name)\n starttime_ms = int(round(time.time() * 1000))\n directory_contents = file_io.list_directory(dir_name)\n print(directory_contents)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Listed directory %s in %s milliseconds\" % (dir_name, elapsed_ms))\n assert set(directory_contents) == set(files_to_create + [\"nested_dir1/\"])\n\n # Test directory renaming.\n dir_to_rename = \"%s/old_dir\" % dir_name\n new_dir_name = \"%s/new_dir\" % dir_name\n file_io.create_dir(dir_to_rename)\n assert file_io.is_directory(dir_to_rename)\n assert not file_io.is_directory(new_dir_name)\n\n starttime_ms = int(round(time.time() * 1000))\n print(\"Will try renaming directory %s to %s\" % (dir_to_rename, new_dir_name))\n file_io.rename(dir_to_rename, new_dir_name)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Renamed directory %s to %s in %s milliseconds\" % (\n dir_to_rename, new_dir_name, elapsed_ms))\n assert not file_io.is_directory(dir_to_rename)\n assert file_io.is_directory(new_dir_name)\n\n # Test Delete directory recursively.\n print(\"Deleting directory recursively %s.\" % dir_name)\n starttime_ms = int(round(time.time() * 1000))\n file_io.delete_recursively(dir_name)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n dir_exists = file_io.is_directory(dir_name)\n assert not dir_exists\n print(\"Deleted directory recursively %s in %s milliseconds\" % (\n dir_name, elapsed_ms))\n\n\ndef create_object_test():\n \"\"\"Verifies file_io's object manipulation methods .\"\"\"\n starttime_ms = int(round(time.time() * 1000))\n dir_name = \"%s/tf_gcs_test_%s\" % (FLAGS.gcs_bucket_url, starttime_ms)\n print(\"Creating dir %s.\" % dir_name)\n file_io.create_dir(dir_name)\n\n num_files = 5\n # Create files of 2 different patterns in this directory.\n files_pattern_1 = [\"%s/test_file_%d.txt\" % (dir_name, n)\n for n in range(num_files)]\n files_pattern_2 = [\"%s/testfile%d.txt\" % (dir_name, n)\n for n in range(num_files)]\n\n starttime_ms = int(round(time.time() * 1000))\n files_to_create = files_pattern_1 + files_pattern_2\n for file_name in files_to_create:\n print(\"Creating file %s.\" % file_name)\n file_io.write_string_to_file(file_name, \"test file creation.\")\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Created %d files in %s milliseconds\" % (\n len(files_to_create), elapsed_ms))\n\n # Listing files of pattern1.\n list_files_pattern = \"%s/test_file*.txt\" % dir_name\n print(\"Getting files matching pattern %s.\" % list_files_pattern)\n starttime_ms = int(round(time.time() * 1000))\n files_list = file_io.get_matching_files(list_files_pattern)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Listed files in %s milliseconds\" % elapsed_ms)\n print(files_list)\n assert set(files_list) == set(files_pattern_1)\n\n # Listing files of pattern2.\n list_files_pattern = \"%s/testfile*.txt\" % dir_name\n print(\"Getting files matching pattern %s.\" % list_files_pattern)\n starttime_ms = int(round(time.time() * 1000))\n files_list = file_io.get_matching_files(list_files_pattern)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"Listed files in %s milliseconds\" % elapsed_ms)\n print(files_list)\n assert set(files_list) == set(files_pattern_2)\n\n # Test renaming file.\n file_to_rename = \"%s/oldname.txt\" % dir_name\n file_new_name = \"%s/newname.txt\" % dir_name\n file_io.write_string_to_file(file_to_rename, \"test file.\")\n assert file_io.file_exists(file_to_rename)\n assert not file_io.file_exists(file_new_name)\n\n print(\"Will try renaming file %s to %s\" % (file_to_rename, file_new_name))\n starttime_ms = int(round(time.time() * 1000))\n file_io.rename(file_to_rename, file_new_name)\n elapsed_ms = int(round(time.time() * 1000)) - starttime_ms\n print(\"File %s renamed to %s in %s milliseconds\" % (\n file_to_rename, file_new_name, elapsed_ms))\n assert not file_io.file_exists(file_to_rename)\n assert file_io.file_exists(file_new_name)\n\n # Delete directory.\n print(\"Deleting directory %s.\" % dir_name)\n file_io.delete_recursively(dir_name)\n\n\ndef main(argv):\n del argv # Unused.\n\n # Sanity check on the GCS bucket URL.\n if not FLAGS.gcs_bucket_url or not FLAGS.gcs_bucket_url.startswith(\"gs://\"):\n print(\"ERROR: Invalid GCS bucket URL: \\\"%s\\\"\" % FLAGS.gcs_bucket_url)\n sys.exit(1)\n\n # Generate random tfrecord path name.\n input_path = FLAGS.gcs_bucket_url + \"/\"\n input_path += \"\".join(random.choice(\"0123456789ABCDEF\") for i in range(8))\n input_path += \".tfrecord\"\n print(\"Using input path: %s\" % input_path)\n\n # Verify that writing to the records file in GCS works.\n print(\"\\n=== Testing writing and reading of GCS record file... ===\")\n example_data = create_examples(FLAGS.num_examples, 5)\n with tf.io.TFRecordWriter(input_path) as hf:\n for e in example_data:\n hf.write(e.SerializeToString())\n\n print(\"Data written to: %s\" % input_path)\n\n # Verify that reading from the tfrecord file works and that\n # tf_record_iterator works.\n record_iter = tf.compat.v1.python_io.tf_record_iterator(input_path)\n read_count = 0\n for _ in record_iter:\n read_count += 1\n print(\"Read %d records using tf_record_iterator\" % read_count)\n\n if read_count != FLAGS.num_examples:\n print(\"FAIL: The number of records read from tf_record_iterator (%d) \"\n \"differs from the expected number (%d)\" % (read_count,\n FLAGS.num_examples))\n sys.exit(1)\n\n # Verify that running the read op in a session works.\n print(\"\\n=== Testing TFRecordReader.read op in a session... ===\")\n with tf.Graph().as_default():\n filename_queue = tf.compat.v1.train.string_input_producer([input_path],\n num_epochs=1)\n reader = tf.compat.v1.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n sess.run(tf.compat.v1.local_variables_initializer())\n tf.compat.v1.train.start_queue_runners()\n index = 0\n for _ in range(FLAGS.num_examples):\n print(\"Read record: %d\" % index)\n sess.run(serialized_example)\n index += 1\n\n # Reading one more record should trigger an exception.\n try:\n sess.run(serialized_example)\n print(\"FAIL: Failed to catch the expected OutOfRangeError while \"\n \"reading one more record than is available\")\n sys.exit(1)\n except tf.errors.OutOfRangeError:\n print(\"Successfully caught the expected OutOfRangeError while \"\n \"reading one more record than is available\")\n\n create_dir_test()\n create_object_test()\n\n\nif __name__ == \"__main__\":\n tf.compat.v1.app.run(main)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for ragged_tensor.convert_to_tensor_or_ragged.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.platform import googletest\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass RaggedConvertToTensorOrRaggedTensorTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n #=============================================================================\n # Tests where the 'value' param is a RaggedTensor\n #=============================================================================\n @parameterized.parameters([\n dict(pylist=[[1, 2], [3]]),\n dict(pylist=[[1, 2], [3]], preferred_dtype=dtypes.float32),\n dict(pylist=[[1, 2], [3]], preferred_dtype=dtypes.string),\n # Note: Conversion of a single np.array is tested below. These tests\n # check nestings consisting of multiple or irregularily-shaped np.arrays.\n dict(\n pylist=[np.array([1, 2]), np.array([3])],\n preferred_dtype=dtypes.string),\n dict(pylist=np.array([[1, 2], [3]]), preferred_dtype=dtypes.float32),\n dict(pylist=np.array([[1, 2], [3]]), preferred_dtype=dtypes.string),\n dict(\n pylist=[np.array([[1], np.array([2])]), [np.array([3])]],\n preferred_dtype=dtypes.float32),\n dict(pylist=[np.array(1)], preferred_dtype=dtypes.string),\n ])\n def testConvertRaggedTensor(self, pylist, dtype=None, preferred_dtype=None):\n rt = ragged_factory_ops.constant(pylist)\n converted = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n rt, dtype, preferred_dtype)\n self.assertIs(converted, rt)\n\n @parameterized.parameters([\n dict(\n pylist=[[1, 2], [3, 4]],\n dtype=dtypes.float32,\n message=('Tensor conversion requested dtype float32 for '\n 'RaggedTensor with dtype int32')),\n dict(\n pylist=np.array([[1, 2], [3, 4]]),\n dtype=dtypes.float32,\n message=('Tensor conversion requested dtype float32 for '\n 'RaggedTensor with dtype int32')),\n dict(\n pylist=[[1, 2], [3, 4]],\n dtype=dtypes.string,\n message=('Tensor conversion requested dtype string for '\n 'RaggedTensor with dtype .*')),\n ])\n def testConvertRaggedTensorError(self,\n pylist,\n message,\n dtype=None,\n preferred_dtype=None):\n rt = ragged_factory_ops.constant(pylist)\n\n with self.assertRaisesRegexp(ValueError, message):\n ragged_tensor.convert_to_tensor_or_ragged_tensor(rt, dtype,\n preferred_dtype)\n\n #=============================================================================\n # Tests where the 'value' param is a RaggedTensorValue\n #=============================================================================\n @parameterized.parameters(\n [\n dict(\n value=ragged_factory_ops.constant_value([[1, 2], [3]],\n dtype=np.int32),\n expected_dtype=dtypes.int32),\n dict(\n value=ragged_factory_ops.constant_value([[b'a', b'b'], [b'c']]),\n expected_dtype=dtypes.string),\n dict(\n value=ragged_factory_ops.constant_value([[1, 2], [3]],\n dtype=np.int32),\n dtype=dtypes.float32,\n expected_dtype=dtypes.float32),\n dict(\n value=ragged_factory_ops.constant_value([[1, 2], [3]],\n dtype=np.int32),\n preferred_dtype=dtypes.float32,\n expected_dtype=dtypes.float32),\n dict(\n value=ragged_factory_ops.constant_value([[1, 2], [3]],\n dtype=np.int32),\n preferred_dtype=dtypes.string,\n expected_dtype=dtypes.int32),\n ])\n def testConvertRaggedTensorValue(self,\n value,\n dtype=None,\n preferred_dtype=None,\n expected_dtype=None):\n if expected_dtype is None:\n expected_dtype = value.dtype if dtype is None else dtype\n converted = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n value, dtype, preferred_dtype)\n self.assertEqual(value.ragged_rank, converted.ragged_rank)\n self.assertEqual(dtypes.as_dtype(expected_dtype), converted.dtype)\n self.assertAllEqual(value, converted)\n\n @parameterized.parameters([\n dict(\n value=ragged_factory_ops.constant_value([['a', 'b'], ['c']],\n dtype=str),\n dtype=dtypes.int32,\n message=r\"invalid literal for int\\(\\) with base 10: 'a'\"),\n ])\n def testConvertRaggedTensorValueError(self,\n value,\n message,\n dtype=None,\n preferred_dtype=None):\n with self.assertRaisesRegexp(ValueError, message):\n ragged_tensor.convert_to_tensor_or_ragged_tensor(value, dtype,\n preferred_dtype)\n\n #=============================================================================\n # Tests where the 'value' param is a Tensor\n #=============================================================================\n @parameterized.parameters([\n dict(pylist=[[1, 2], [3, 4]]),\n dict(pylist=[[1, 2], [3, 4]], preferred_dtype=dtypes.float32),\n dict(pylist=[[1, 2], [3, 4]], preferred_dtype=dtypes.string),\n ])\n def testConvertTensor(self, pylist, dtype=None, preferred_dtype=None):\n tensor = constant_op.constant(pylist)\n converted = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n tensor, dtype, preferred_dtype)\n self.assertIs(tensor, converted)\n\n @parameterized.parameters([\n dict(\n pylist=[[1, 2], [3, 4]],\n dtype=dtypes.float32,\n message=('Tensor conversion requested dtype float32 for '\n 'Tensor with dtype int32')),\n dict(\n pylist=[[1, 2], [3, 4]],\n dtype=dtypes.string,\n message=('Tensor conversion requested dtype string for '\n 'Tensor with dtype int32')),\n ])\n def testConvertTensorError(self,\n pylist,\n message,\n dtype=None,\n preferred_dtype=None):\n tensor = constant_op.constant(pylist)\n with self.assertRaisesRegexp(ValueError, message):\n ragged_tensor.convert_to_tensor_or_ragged_tensor(tensor, dtype,\n preferred_dtype)\n\n #=============================================================================\n # Tests where the 'value' param is a np.array\n #=============================================================================\n @parameterized.parameters([\n dict(\n value=np.array([[1, 2], [3, 4]], dtype=np.int32),\n expected_dtype=dtypes.int32),\n dict(\n value=np.array([[b'a', b'b'], [b'c', b'd']]),\n expected_dtype=dtypes.string),\n dict(\n value=np.array([[1, 2], [3, 4]], dtype=np.int32),\n dtype=dtypes.float32,\n expected_dtype=dtypes.float32),\n dict(\n value=np.array([[1, 2], [3, 4]], dtype=np.int32),\n preferred_dtype=dtypes.float32,\n expected_dtype=dtypes.float32),\n dict(\n value=np.array([[1, 2], [3, 4]], dtype=np.int32),\n preferred_dtype=dtypes.string,\n expected_dtype=dtypes.int32),\n ])\n def testConvertNumpyArray(self,\n value,\n dtype=None,\n preferred_dtype=None,\n expected_dtype=None):\n if expected_dtype is None:\n expected_dtype = value.dtype if dtype is None else dtype\n converted = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n value, dtype, preferred_dtype)\n self.assertEqual(dtypes.as_dtype(expected_dtype), converted.dtype)\n self.assertAllEqual(value, converted)\n\n @parameterized.parameters([\n dict(\n value=np.array([['a', 'b'], ['c', 'd']], dtype=str),\n dtype=dtypes.int32,\n message=r\"invalid literal for int\\(\\) with base 10: 'a'\"),\n ])\n def testConvertNumpyArrayError(self,\n value,\n message,\n dtype=None,\n preferred_dtype=None):\n with self.assertRaisesRegexp(ValueError, message):\n ragged_tensor.convert_to_tensor_or_ragged_tensor(value, dtype,\n preferred_dtype)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=protected-access\n\"\"\"Code for model cloning, plus model-related API entries.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import metrics as metrics_module\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.engine import network\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.engine.base_layer import AddMetric\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_layer import Input\nfrom tensorflow.python.keras.engine.input_layer import InputLayer\nfrom tensorflow.python.keras.engine.network import Network\nfrom tensorflow.python.keras.saving import model_config\nfrom tensorflow.python.keras.saving import save\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.keras.utils.generic_utils import CustomObjectScope\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n# API entries importable from `keras.models`:\nModel = training.Model # pylint: disable=invalid-name\nSequential = sequential.Sequential # pylint: disable=invalid-name\nsave_model = save.save_model\nload_model = save.load_model\nmodel_from_config = model_config.model_from_config\nmodel_from_yaml = model_config.model_from_yaml\nmodel_from_json = model_config.model_from_json\n\n\n# Callable used to clone a layer with weights preserved.\ndef share_weights(layer):\n return layer\n\n\ndef _clone_layer(layer):\n return layer.__class__.from_config(layer.get_config())\n\n\ndef _insert_ancillary_layers(model, ancillary_layers, metrics_names, new_nodes):\n \"\"\"Inserts ancillary layers into the model with the proper order.\"\"\"\n # Sort `AddMetric` layers so they agree with metrics_names.\n metric_layers = [\n layer for layer in ancillary_layers if isinstance(layer, AddMetric)\n ]\n metric_layers.sort(key=lambda layer: metrics_names.index(layer.metric_name))\n ancillary_layers = [\n layer for layer in ancillary_layers if not isinstance(layer, AddMetric)\n ] + metric_layers\n model._insert_layers(ancillary_layers, relevant_nodes=list(new_nodes))\n\n\ndef _make_new_nodes(nodes_by_depth, layer_fn, layer_map, tensor_map):\n \"\"\"Uses the layers in `layer_map` to make new nodes based on `nodes_by_depth`.\n\n Args:\n nodes_by_depth: Provides structure information to create new nodes.\n layer_fn: Function to clone layers.\n layer_map: Map from layers in `model` to new layers.\n tensor_map: Map from tensors in `model` to newly compute tensors.\n\n Returns:\n A set of new nodes. `layer_map` and `tensor_map` are updated.\n \"\"\"\n # Iterated over every node in the reference model, in depth order.\n new_nodes = set()\n depth_keys = list(nodes_by_depth.keys())\n depth_keys.sort(reverse=True)\n for depth in depth_keys:\n nodes = nodes_by_depth[depth]\n for node in nodes:\n # Recover the corresponding layer.\n layer = node.outbound_layer\n\n # Get or create layer.\n if layer not in layer_map:\n new_layer = layer_fn(layer)\n layer_map[layer] = new_layer\n layer = new_layer\n else:\n # Reuse previously cloned layer.\n layer = layer_map[layer]\n # Don't call InputLayer multiple times.\n if isinstance(layer, InputLayer):\n continue\n\n # If all previous input tensors are available in tensor_map,\n # then call node.inbound_layer on them.\n if all(\n tensor in tensor_map for tensor in nest.flatten(node.input_tensors)):\n computed_tensors = nest.map_structure(lambda t: tensor_map[t],\n node.input_tensors)\n # Call layer.\n kwargs = node.arguments or {}\n output_tensors = layer(computed_tensors, **kwargs)\n\n # Thread-safe way to keep track of what node was created.\n first_output_tensor = nest.flatten(output_tensors)[0]\n new_nodes.add(\n layer._inbound_nodes[first_output_tensor._keras_history.node_index])\n\n for x, y in zip(\n nest.flatten(node.output_tensors), nest.flatten(output_tensors)):\n tensor_map[x] = y\n return new_nodes\n\n\ndef _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer):\n \"\"\"Clone a functional `Model` instance.\n\n Model cloning is similar to calling a model on new inputs,\n except that it creates new layers (and thus new weights) instead\n of sharing the weights of the existing layers.\n\n Input layers are always cloned.\n\n Arguments:\n model: Instance of `Model`.\n input_tensors: optional list of input tensors\n to build the model upon. If not provided,\n placeholders will be created.\n layer_fn: callable to be applied on non-input layers in the model. By\n default it clones the layer. Another example is to preserve the layer\n to share the weights. This is required when we create a per-replica\n copy of the model with distribution strategy; we want the weights to\n be shared but still feed inputs separately so we create new input\n layers.\n\n Returns:\n An instance of `Model` reproducing the behavior\n of the original model, on top of new inputs tensors,\n using newly instantiated weights.\n\n Raises:\n ValueError: in case of invalid `model` argument value or `layer_fn`\n argument value.\n \"\"\"\n if not isinstance(model, Model):\n raise ValueError('Expected `model` argument '\n 'to be a `Model` instance, got ', model)\n if isinstance(model, Sequential):\n raise ValueError('Expected `model` argument '\n 'to be a functional `Model` instance, '\n 'got a `Sequential` instance instead:', model)\n if not model._is_graph_network:\n raise ValueError('Expected `model` argument '\n 'to be a functional `Model` instance, '\n 'but got a subclass model instead.')\n\n new_input_layers = {} # Cache for created layers.\n if input_tensors is not None:\n # Make sure that all input tensors come from a Keras layer.\n input_tensors = nest.flatten(input_tensors)\n for i, input_tensor in enumerate(input_tensors):\n original_input_layer = model._input_layers[i]\n\n # Cache input layer. Create a new layer if the tensor is originally not\n # from a Keras layer.\n if not K.is_keras_tensor(input_tensor):\n name = original_input_layer.name\n input_tensor = Input(tensor=input_tensor,\n name='input_wrapper_for_' + name)\n newly_created_input_layer = input_tensor._keras_history.layer\n new_input_layers[original_input_layer] = newly_created_input_layer\n else:\n new_input_layers[original_input_layer] = original_input_layer\n\n if not callable(layer_fn):\n raise ValueError('Expected `layer_fn` argument to be a callable.')\n\n model_config, created_layers = _clone_layers_and_model_config(\n model, new_input_layers, layer_fn)\n # Reconstruct model from the config, using the cloned layers.\n input_tensors, output_tensors, created_layers = (\n network.reconstruct_from_config(model_config,\n created_layers=created_layers))\n metrics_names = model.metrics_names\n model = Model(input_tensors, output_tensors, name=model.name)\n # Layers not directly tied to outputs of the Model, such as loss layers\n # created in `add_loss` and `add_metric`.\n ancillary_layers = [\n layer for layer in created_layers.values() if layer not in model.layers\n ]\n if ancillary_layers:\n new_nodes = nest.flatten([\n layer.inbound_nodes[1:]\n if network._should_skip_first_node(layer) else layer.inbound_nodes\n for layer in created_layers.values()\n ])\n _insert_ancillary_layers(model, ancillary_layers, metrics_names, new_nodes)\n return model\n\n\ndef _clone_layers_and_model_config(model, input_layers, layer_fn):\n \"\"\"Clones all layers, and returns the model config without serializing layers.\n\n This function ensures that only the node graph is retrieved when getting the\n model config. The `layer_fn` used to clone layers might not rely on\n `layer.get_config()`, so some custom layers do not define `get_config`.\n Trying to retrieve the config results in errors.\n\n Args:\n model: A Functional model.\n input_layers: Dictionary mapping input layers in `model` to new input layers\n layer_fn: Function used to clone all non-input layers.\n\n Returns:\n Model config object, and a dictionary of newly created layers.\n \"\"\"\n created_layers = {}\n def _copy_layer(layer):\n # Whenever the network config attempts to get the layer serialization,\n # return a dummy dictionary.\n if layer in input_layers:\n created_layers[layer.name] = input_layers[layer]\n elif layer in model._input_layers:\n created_layers[layer.name] = InputLayer(**layer.get_config())\n else:\n created_layers[layer.name] = layer_fn(layer)\n return {}\n\n config = network.get_network_config(model, serialize_layer_fn=_copy_layer)\n return config, created_layers\n\n\ndef _remove_ancillary_layers(model, layer_map, layers):\n \"\"\"Removes and returns any ancillary layers from `layers` based on `model`.\n\n Ancillary layers are part of the model topology but not used to compute the\n model outputs, e.g., layers from `add_loss` and `add_metric`.\n\n Args:\n model: A Keras Model.\n layer_map: A map to from layers in the `model` to those in `layers`.\n layers: A list of all layers.\n\n Returns:\n Two lists of layers: (1) `layers` with the ancillary layers removed, and (2)\n the ancillary layers.\n \"\"\"\n ancillary_layers = [] # Additional layers for computing losses and metrics.\n if not model._is_graph_network:\n return layers, ancillary_layers\n\n # Ancillary layers are those with depth < 0.\n depths = [depth for depth in model._nodes_by_depth.keys() if depth < 0]\n depths.sort(reverse=True) # Order topologically from inputs to outputs.\n for depth in depths:\n for node in model._nodes_by_depth[depth]:\n ancillary_layers.append(layer_map[node.outbound_layer])\n\n return [l for l in layers if l not in ancillary_layers], ancillary_layers\n\n\ndef _clone_sequential_model(model, input_tensors=None, layer_fn=_clone_layer):\n \"\"\"Clone a `Sequential` model instance.\n\n Model cloning is similar to calling a model on new inputs,\n except that it creates new layers (and thus new weights) instead\n of sharing the weights of the existing layers.\n\n Arguments:\n model: Instance of `Sequential`.\n input_tensors: optional list of input tensors\n to build the model upon. If not provided,\n placeholders will be created.\n layer_fn: callable to be applied on non-input layers in the model. By\n default it clones the layer. Another example is to preserve the layer\n to share the weights. This is required when we create a per-replica\n copy of the model with distribution strategy; we want the weights to\n be shared but still feed inputs separately so we create new input\n layers.\n\n Returns:\n An instance of `Sequential` reproducing the behavior\n of the original model, on top of new inputs tensors,\n using newly instantiated weights.\n\n Raises:\n ValueError: in case of invalid `model` argument value or `layer_fn`\n argument value.\n \"\"\"\n if not isinstance(model, Sequential):\n raise ValueError('Expected `model` argument '\n 'to be a `Sequential` model instance, '\n 'but got:', model)\n\n if not callable(layer_fn):\n raise ValueError('Expected `layer_fn` argument to be a callable.')\n\n layers = [] # Layers needed to compute the model's outputs.\n layer_map = {}\n # Use model._layers to ensure that all layers are cloned. The model's layers\n # property will exclude the initial InputLayer (if it exists) in the model,\n # resulting in a different Sequential model structure.\n for layer in model._layers:\n if isinstance(layer, InputLayer) and input_tensors is not None:\n # If input tensors are provided, the original model's InputLayer is\n # overwritten with a different InputLayer.\n continue\n cloned_layer = (\n _clone_layer(layer)\n if isinstance(layer, InputLayer) else layer_fn(layer))\n layers.append(cloned_layer)\n layer_map[layer] = cloned_layer\n layers, ancillary_layers = _remove_ancillary_layers(model, layer_map, layers)\n\n if input_tensors is None:\n cloned_model = Sequential(layers=layers, name=model.name)\n elif len(generic_utils.to_list(input_tensors)) != 1:\n raise ValueError('To clone a `Sequential` model, we expect '\n ' at most one tensor '\n 'as part of `input_tensors`.')\n else:\n # Overwrite the original model's input layer.\n if isinstance(input_tensors, tuple):\n input_tensors = list(input_tensors)\n x = generic_utils.to_list(input_tensors)[0]\n if K.is_keras_tensor(x):\n origin_layer = x._keras_history.layer\n if isinstance(origin_layer, InputLayer):\n cloned_model = Sequential(\n layers=[origin_layer] + layers, name=model.name)\n else:\n raise ValueError('Cannot clone a `Sequential` model on top '\n 'of a tensor that comes from a Keras layer '\n 'other than an `InputLayer`. '\n 'Use the functional API instead.')\n else:\n input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name))\n input_layer = input_tensor._keras_history.layer\n cloned_model = Sequential(layers=[input_layer] + layers, name=model.name)\n\n if not ancillary_layers:\n return cloned_model\n\n tensor_map = {} # Maps tensors from `model` to those in `cloned_model`.\n for depth, cloned_nodes in cloned_model._nodes_by_depth.items():\n nodes = model._nodes_by_depth[depth]\n # This should be safe in a Sequential model. In an arbitrary network, you\n # need to sort using the outbound layer of the node as a key.\n for cloned_node, node in zip(cloned_nodes, nodes):\n if isinstance(cloned_node.output_tensors, list):\n for j, output_tensor in enumerate(cloned_node.output_tensors):\n tensor_map[node.output_tensors[j]] = output_tensor\n else:\n tensor_map[node.output_tensors] = cloned_node.output_tensors\n # Ancillary nodes have negative depth.\n new_nodes = _make_new_nodes(\n {\n depth: nodes\n for depth, nodes in model._nodes_by_depth.items()\n if depth < 0\n }, layer_fn, layer_map, tensor_map)\n _insert_ancillary_layers(cloned_model, ancillary_layers, model.metrics_names,\n new_nodes)\n return cloned_model\n\n\n@keras_export('keras.models.clone_model')\ndef clone_model(model, input_tensors=None, clone_function=None):\n \"\"\"Clone any `Model` instance.\n\n Model cloning is similar to calling a model on new inputs,\n except that it creates new layers (and thus new weights) instead\n of sharing the weights of the existing layers.\n\n Arguments:\n model: Instance of `Model`\n (could be a functional model or a Sequential model).\n input_tensors: optional list of input tensors or InputLayer objects\n to build the model upon. If not provided,\n placeholders will be created.\n clone_function: Callable to be used to clone each layer in the target\n model (except `InputLayer` instances). It takes as argument the layer\n instance to be cloned, and returns the corresponding layer instance to\n be used in the model copy. If unspecified, this callable defaults to\n the following serialization/deserialization function:\n `lambda layer: layer.__class__.from_config(layer.get_config())`.\n By passing a custom callable, you can customize your copy of the\n model, e.g. by wrapping certain layers of interest (you might want to\n replace all `LSTM` instances with equivalent\n `Bidirectional(LSTM(...))` instances, for example).\n\n Returns:\n An instance of `Model` reproducing the behavior\n of the original model, on top of new inputs tensors,\n using newly instantiated weights. The cloned model might behave\n differently from the original model if a custom clone_function\n modifies the layer.\n\n Raises:\n ValueError: in case of invalid `model` argument value.\n \"\"\"\n if clone_function is None:\n clone_function = _clone_layer\n\n if isinstance(model, Sequential):\n return _clone_sequential_model(\n model, input_tensors=input_tensors, layer_fn=clone_function)\n else:\n return _clone_functional_model(\n model, input_tensors=input_tensors, layer_fn=clone_function)\n\n\n# \"Clone\" a subclassed model by reseting all of the attributes.\ndef _in_place_subclassed_model_reset(model):\n \"\"\"Substitute for model cloning that works for subclassed models.\n\n Subclassed models cannot be cloned because their topology is not serializable.\n To \"instantiate\" an identical model in a new TF graph, we reuse the original\n model object, but we clear its state.\n\n After calling this function on a model instance, you can use the model\n instance as if it were a model clone (in particular you can use it in a new\n graph).\n\n This method clears the state of the input model. It is thus destructive.\n However the original state can be restored fully by calling\n `_in_place_subclassed_model_state_restoration`.\n\n Args:\n model: Instance of a Keras model created via subclassing.\n\n Raises:\n ValueError: In case the model uses a subclassed model as inner layer.\n \"\"\"\n assert not model._is_graph_network # Only makes sense for subclassed networks\n # Retrieve all layers tracked by the model as well as their attribute names\n attributes_cache = {}\n for name in dir(model):\n # Skip the check of methods in tf.Module since they basically\n # recursively query all the other attributes within same module.\n if name == 'submodules':\n continue\n\n try:\n value = getattr(model, name)\n except (AttributeError, ValueError, TypeError):\n continue\n if isinstance(value, Layer):\n attributes_cache[name] = value\n assert value in model.layers\n if hasattr(value, 'layers') and value.layers:\n raise ValueError('We do not support the use of nested layers '\n 'in `model_to_estimator` at this time. Found nested '\n 'layer: %s' % value)\n elif isinstance(\n value, (list, tuple)) and name not in ('layers', '_layers', 'metrics',\n '_compile_metric_functions',\n '_output_loss_metrics'):\n # Handle case: list/tuple of layers (also tracked by the Network API).\n if value and all(isinstance(val, Layer) for val in value):\n raise ValueError('We do not support the use of list-of-layers '\n 'attributes in subclassed models used with '\n '`model_to_estimator` at this time. Found list '\n 'model: %s' % name)\n\n # Replace layers on the model with fresh layers\n layers_to_names = {value: key for key, value in attributes_cache.items()}\n original_layers = model._layers[:]\n setattr_tracking = model._setattr_tracking\n model._setattr_tracking = False\n model._layers = []\n for layer in original_layers: # We preserve layer order.\n config = layer.get_config()\n # This will not work for nested subclassed models used as layers.\n # This would be theoretically possible to support, but would add complexity.\n # Only do it if users complain.\n if isinstance(layer, Network) and not layer._is_graph_network:\n raise ValueError('We do not support the use of nested subclassed models '\n 'in `model_to_estimator` at this time. Found nested '\n 'model: %s' % layer)\n fresh_layer = layer.__class__.from_config(config)\n name = layers_to_names[layer]\n setattr(model, name, fresh_layer)\n model._layers.append(fresh_layer)\n\n # The base Layer __setattr__ will invalidate its attribute cache when\n # `._layers` is assigned, but it has no way to know when the underlying list\n # is mutated so we must explicitly signal the append.\n model._attribute_sentinel.invalidate_all()\n\n # Cache original model build attributes (in addition to layers)\n if (not hasattr(model, '_original_attributes_cache') or\n model._original_attributes_cache is None):\n if model.built:\n attributes_to_cache = [\n 'inputs',\n 'outputs',\n 'total_loss',\n 'optimizer',\n 'train_function',\n 'test_function',\n 'predict_function',\n '_training_endpoints',\n '_collected_trainable_weights',\n '_feed_inputs',\n '_feed_input_names',\n '_feed_input_shapes',\n ]\n for name in attributes_to_cache:\n attributes_cache[name] = getattr(model, name)\n model._original_attributes_cache = attributes_cache\n _reset_build_compile_trackers(model)\n model._setattr_tracking = setattr_tracking\n\n\ndef _reset_build_compile_trackers(model):\n \"\"\"Reset state trackers for model.\n\n Note that we do not actually zero out attributes such as optimizer,\n but instead rely on the expectation that all of the attrs will be\n over-written on calling build/compile/etc. This is somewhat fragile,\n insofar as we check elsewhere for the presence of these attributes as\n evidence of having been built/compiled/etc. Pending a better way to do this,\n we reset key attributes here to allow building and compiling.\n\n Args:\n model: the model that is being reset\n \"\"\"\n # Reset build state\n model.built = False\n model.inputs = None\n model.outputs = None\n # Reset compile state\n model._is_compiled = False # pylint:disable=protected-access\n model.optimizer = None\n\n\ndef in_place_subclassed_model_state_restoration(model):\n \"\"\"Restores the original state of a model after it was \"reset\".\n\n This undoes this action of `_in_place_subclassed_model_reset`, which is called\n in `clone_and_build_model` if `in_place_reset` is set to True.\n\n Args:\n model: Instance of a Keras model created via subclassing, on which\n `_in_place_subclassed_model_reset` was previously called.\n \"\"\"\n assert not model._is_graph_network\n # Restore layers and build attributes\n if (hasattr(model, '_original_attributes_cache') and\n model._original_attributes_cache is not None):\n # Models have sticky attribute assignment, so we want to be careful to add\n # back the previous attributes and track Layers by their original names\n # without adding dependencies on \"utility\" attributes which Models exempt\n # when they're constructed.\n setattr_tracking = model._setattr_tracking\n model._setattr_tracking = False\n model._layers = []\n for name, value in model._original_attributes_cache.items():\n setattr(model, name, value)\n if isinstance(value, Layer):\n model._layers.append(value)\n model._original_attributes_cache = None\n model._setattr_tracking = setattr_tracking\n else:\n # Restore to the state of a never-called model.\n _reset_build_compile_trackers(model)\n\n\ndef clone_and_build_model(\n model, input_tensors=None, target_tensors=None, custom_objects=None,\n compile_clone=True, in_place_reset=False, optimizer_iterations=None,\n optimizer_config=None):\n \"\"\"Clone a `Model` and build/compile it with the same settings used before.\n\n This function can be be run in the same graph or in a separate graph from the\n model. When using a separate graph, `in_place_reset` must be `False`.\n\n Note that, currently, the clone produced from this function may not work with\n TPU DistributionStrategy. Try at your own risk.\n\n Args:\n model: `tf.keras.Model` object. Can be Functional, Sequential, or\n sub-classed.\n input_tensors: Optional list or dictionary of input tensors to build the\n model upon. If not provided, placeholders will be created.\n target_tensors: Optional list of target tensors for compiling the model. If\n not provided, placeholders will be created.\n custom_objects: Optional dictionary mapping string names to custom classes\n or functions.\n compile_clone: Boolean, whether to compile model clone (default `True`).\n in_place_reset: Boolean, whether to reset the model in place. Only used if\n the model is a subclassed model. In the case of a subclassed model,\n this argument must be set to `True` (default `False`). To restore the\n original model, use the function\n `in_place_subclassed_model_state_restoration(model)`.\n optimizer_iterations: An iterations variable that will be incremented by the\n optimizer if the clone is compiled. This argument is used when a Keras\n model is cloned into an Estimator model function, because Estimators\n create their own global step variable.\n optimizer_config: Optimizer config dictionary or list of dictionary\n returned from `get_config()`. This argument should be defined if\n `clone_and_build_model` is called in a different graph or session from\n the original model, and the optimizer is an instance of `OptimizerV2`.\n\n Returns:\n Clone of the model.\n\n Raises:\n ValueError: Cloning fails in the following cases\n - cloning a subclassed model with `in_place_reset` set to False.\n - compiling the clone when the original model has not been compiled.\n \"\"\"\n # Grab optimizer now, as we reset-in-place for subclassed models, but\n # want to maintain access to the original optimizer.\n orig_optimizer = model.optimizer\n if compile_clone and not orig_optimizer:\n raise ValueError(\n 'Error when cloning model: compile_clone was set to True, but the '\n 'original model has not been compiled.')\n\n if model._is_graph_network or isinstance(model, Sequential):\n if custom_objects:\n with CustomObjectScope(custom_objects):\n clone = clone_model(model, input_tensors=input_tensors)\n else:\n clone = clone_model(model, input_tensors=input_tensors)\n\n if all([isinstance(clone, Sequential),\n not clone._is_graph_network,\n getattr(model, '_build_input_shape', None) is not None]):\n # Set model inputs to build the model and add input/output properties.\n # TODO(kathywu): Add multiple placeholders to handle edge case where\n # sequential model has multiple inputs.\n clone._set_inputs(\n K.placeholder(model._build_input_shape, dtype=model.inputs[0].dtype))\n else:\n try:\n # Prefer clonining the model if serial/deserial logic is implemented for\n # subclassed model.\n clone = model.__class__.from_config(model.get_config())\n except NotImplementedError:\n logging.warning('This model is a subclassed model. Please implement '\n '`get_config` and `from_config` to better support '\n 'cloning the model.')\n if not in_place_reset:\n raise ValueError(\n 'This model is a subclassed model. '\n 'Such a model cannot be cloned, but there is a workaround where '\n 'the model is reset in-place. To use this, please set the argument '\n '`in_place_reset` to `True`. This will reset the attributes in the '\n 'original model. To restore the attributes, call '\n '`in_place_subclassed_model_state_restoration(model)`.')\n clone = model\n _in_place_subclassed_model_reset(clone)\n if input_tensors is not None:\n if isinstance(input_tensors, (list, tuple)) and len(input_tensors) == 1:\n input_tensors = input_tensors[0]\n clone._set_inputs(input_tensors)\n\n if compile_clone:\n if isinstance(orig_optimizer, optimizers.TFOptimizer):\n optimizer = optimizers.TFOptimizer(\n orig_optimizer.optimizer, optimizer_iterations)\n K.track_tf_optimizer(optimizer)\n else:\n if not isinstance(orig_optimizer, (tuple, list)):\n orig_optimizer = [orig_optimizer]\n if optimizer_config is None:\n optimizer = [\n opt.__class__.from_config(opt.get_config())\n for opt in orig_optimizer\n ]\n elif isinstance(optimizer_config, dict):\n optimizer = [orig_optimizer[0].__class__.from_config(optimizer_config)]\n else:\n # optimizer config is list of dict, same order as orig_optimizer.\n optimizer = [\n opt.__class__.from_config(opt_config)\n for (opt, opt_config) in zip(orig_optimizer, optimizer_config)\n ]\n if optimizer_iterations is not None:\n for opt in optimizer:\n opt.iterations = optimizer_iterations\n\n if len(optimizer) == 1:\n optimizer = optimizer[0]\n clone.compile(\n optimizer,\n model.loss,\n metrics=metrics_module.clone_metrics(model._compile_metrics),\n loss_weights=model.loss_weights,\n sample_weight_mode=model.sample_weight_mode,\n weighted_metrics=metrics_module.clone_metrics(\n model._compile_weighted_metrics),\n target_tensors=target_tensors)\n\n return clone\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the `HoistRandomUniform` optimization.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.data.experimental.ops import optimization\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import test\n\n\ndef _hoist_random_uniform_test_cases():\n \"\"\"Generates test cases for the HoistRandomUniform optimization.\"\"\"\n\n plus_one = lambda x: x + 1\n\n def random(_):\n return random_ops.random_uniform([],\n minval=1,\n maxval=10,\n dtype=dtypes.float32,\n seed=42)\n\n def random_with_assert(x):\n y = random(x)\n assert_op = control_flow_ops.Assert(math_ops.greater_equal(y, 1), [y])\n with ops.control_dependencies([assert_op]):\n return y\n\n twice_random = lambda x: (random(x) + random(x)) / 2.\n\n tests = [(\"PlusOne\", plus_one, False), (\"RandomUniform\", random, True),\n (\"RandomWithAssert\", random_with_assert, True),\n (\"TwiceRandom\", twice_random, False)]\n return tuple(tests)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass HoistRandomUniformTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n def _testDataset(self, dataset):\n previous_result = 0\n get_next = self.getNext(dataset)\n for _ in range(5):\n result = self.evaluate(get_next())\n self.assertLessEqual(1, result)\n self.assertLessEqual(result, 10)\n # This checks if the result is somehow random by checking if we are not\n # generating the same values.\n self.assertNotEqual(previous_result, result)\n previous_result = result\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @parameterized.named_parameters(*_hoist_random_uniform_test_cases())\n def testHoisting(self, function, will_optimize):\n dataset = dataset_ops.Dataset.range(5).apply(\n optimization.assert_next(\n [\"Zip[0]\", \"Map\"] if will_optimize else [\"Map\"])).map(function)\n\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.hoist_random_uniform = True\n dataset = dataset.with_options(options)\n self._testDataset(dataset)\n\n def testCapturedInputs(self):\n a = constant_op.constant(1, dtype=dtypes.float32)\n b = constant_op.constant(0, dtype=dtypes.float32)\n some_tensor = math_ops.mul(a, b)\n\n def random_with_capture(_):\n return some_tensor + random_ops.random_uniform(\n [], minval=1, maxval=10, dtype=dtypes.float32, seed=42)\n\n dataset = dataset_ops.Dataset.range(5).apply(\n optimization.assert_next([\"Zip[0]\", \"Map\"])).map(random_with_capture)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.hoist_random_uniform = True\n dataset = dataset.with_options(options)\n self._testDataset(dataset)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=invalid-name\n\"\"\"Inception V3 model for Keras.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras_applications import inception_v3\n\nfrom tensorflow.python.keras.applications import keras_modules_injection\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.applications.inception_v3.InceptionV3',\n 'keras.applications.InceptionV3')\n@keras_modules_injection\ndef InceptionV3(*args, **kwargs):\n return inception_v3.InceptionV3(*args, **kwargs)\n\n\n@keras_export('keras.applications.inception_v3.decode_predictions')\n@keras_modules_injection\ndef decode_predictions(*args, **kwargs):\n return inception_v3.decode_predictions(*args, **kwargs)\n\n\n@keras_export('keras.applications.inception_v3.preprocess_input')\n@keras_modules_injection\ndef preprocess_input(*args, **kwargs):\n return inception_v3.preprocess_input(*args, **kwargs)\n", "# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport tempfile\nimport numpy as np\nfrom six.moves import range\nimport tensorflow as tf\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\n\n\n# Number of steps to train model.\nTRAIN_STEPS = 1\n\nCONFIG = tf.ConfigProto(device_count={\"GPU\": 0})\n\n\nclass UnidirectionalSequenceLstmTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n tf.reset_default_graph()\n # Import MNIST dataset\n self.mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n # Define constants\n # Unrolled through 28 time steps\n self.time_steps = 28\n # Rows of 28 pixels\n self.n_input = 28\n # Learning rate for Adam optimizer\n self.learning_rate = 0.001\n # MNIST is meant to be classified in 10 classes(0-9).\n self.n_classes = 10\n # Batch size\n self.batch_size = 16\n # Lstm Units.\n self.num_units = 16\n\n def buildLstmLayer(self):\n return tf.keras.layers.StackedRNNCells([\n tf.lite.experimental.nn.TFLiteLSTMCell(\n self.num_units, use_peepholes=True, forget_bias=1.0, name=\"rnn1\"),\n tf.lite.experimental.nn.TFLiteLSTMCell(\n self.num_units, num_proj=8, forget_bias=1.0, name=\"rnn2\"),\n tf.lite.experimental.nn.TFLiteLSTMCell(\n self.num_units // 2,\n use_peepholes=True,\n num_proj=8,\n forget_bias=0,\n name=\"rnn3\"),\n tf.lite.experimental.nn.TFLiteLSTMCell(\n self.num_units, forget_bias=1.0, name=\"rnn4\")\n ])\n\n def buildModel(self, lstm_layer, is_dynamic_rnn):\n \"\"\"Build Mnist recognition model.\n\n Args:\n lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell.\n is_dynamic_rnn: Use dynamic_rnn or not.\n\n Returns:\n A tuple containing:\n\n - Input tensor of the model.\n - Prediction tensor of the model.\n - Output class tensor of the model.\n \"\"\"\n # Weights and biases for output softmax layer.\n out_weights = tf.Variable(\n tf.random_normal([self.num_units, self.n_classes]))\n out_bias = tf.Variable(tf.random_normal([self.n_classes]))\n\n # input image placeholder\n x = tf.placeholder(\n \"float\", [None, self.time_steps, self.n_input], name=\"INPUT_IMAGE\")\n\n # x is shaped [batch_size,time_steps,num_inputs]\n if is_dynamic_rnn:\n lstm_input = tf.transpose(x, perm=[1, 0, 2])\n outputs, _ = tf.lite.experimental.nn.dynamic_rnn(\n lstm_layer, lstm_input, dtype=\"float32\")\n outputs = tf.unstack(outputs, axis=0)\n else:\n lstm_input = tf.unstack(x, self.time_steps, 1)\n outputs, _ = tf.nn.static_rnn(lstm_layer, lstm_input, dtype=\"float32\")\n\n # Compute logits by multiplying outputs[-1] of shape [batch_size,num_units]\n # by the softmax layer's out_weight of shape [num_units,n_classes]\n # plus out_bias\n prediction = tf.matmul(outputs[-1], out_weights) + out_bias\n output_class = tf.nn.softmax(prediction, name=\"OUTPUT_CLASS\")\n\n return x, prediction, output_class\n\n def trainModel(self, x, prediction, output_class, sess):\n \"\"\"Train the model.\n\n Args:\n x: The input tensor.\n prediction: The prediction class tensor.\n output_class: The output tensor.\n sess: The graph session.\n \"\"\"\n # input label placeholder\n y = tf.placeholder(\"float\", [None, self.n_classes])\n # Loss function\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))\n # Optimization\n opt = tf.train.AdamOptimizer(\n learning_rate=self.learning_rate).minimize(loss)\n\n # Initialize variables\n init = tf.global_variables_initializer()\n sess.run(init)\n for _ in range(TRAIN_STEPS):\n batch_x, batch_y = self.mnist.train.next_batch(\n batch_size=self.batch_size, shuffle=False)\n\n batch_x = batch_x.reshape((self.batch_size, self.time_steps,\n self.n_input))\n sess.run(opt, feed_dict={x: batch_x, y: batch_y})\n\n def saveAndRestoreModel(self, lstm_layer, sess, saver, is_dynamic_rnn):\n \"\"\"Saves and restores the model to mimic the most common use case.\n\n Args:\n lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell.\n sess: Old session.\n saver: Saver created by tf.compat.v1.train.Saver()\n is_dynamic_rnn: Use dynamic_rnn or not.\n\n Returns:\n A tuple containing:\n\n - Input tensor of the restored model.\n - Prediction tensor of the restored model.\n - Output tensor, which is the softwmax result of the prediction tensor.\n - new session of the restored model.\n\n \"\"\"\n model_dir = tempfile.mkdtemp()\n saver.save(sess, model_dir)\n\n # Reset the graph.\n tf.reset_default_graph()\n x, prediction, output_class = self.buildModel(lstm_layer, is_dynamic_rnn)\n\n new_sess = tf.compat.v1.Session(config=CONFIG)\n saver = tf.train.Saver()\n saver.restore(new_sess, model_dir)\n return x, prediction, output_class, new_sess\n\n def getInferenceResult(self, x, output_class, sess):\n \"\"\"Get inference result given input tensor and output tensor.\n\n Args:\n x: The input tensor.\n output_class: The output tensor.\n sess: Current session.\n\n Returns:\n A tuple containing:\n\n - Input of the next batch, batch size is 1.\n - Expected output.\n\n \"\"\"\n b1, _ = self.mnist.train.next_batch(batch_size=1)\n sample_input = np.reshape(b1, (1, self.time_steps, self.n_input))\n\n expected_output = sess.run(output_class, feed_dict={x: sample_input})\n return sample_input, expected_output\n\n def tfliteInvoke(self,\n sess,\n test_inputs,\n input_tensor,\n output_tensor,\n use_mlir_converter=False):\n \"\"\"Get tflite inference result.\n\n This method will convert tensorflow from session to tflite model then based\n on the inputs, run tflite inference and return the results.\n\n Args:\n sess: Current tensorflow session.\n test_inputs: The test inputs for tflite.\n input_tensor: The input tensor of tensorflow graph.\n output_tensor: The output tensor of tensorflow graph.\n use_mlir_converter: Whether or not to use MLIRConverter to convert the\n model.\n\n Returns:\n The tflite inference result.\n \"\"\"\n converter = tf.lite.TFLiteConverter.from_session(sess, [input_tensor],\n [output_tensor])\n tflite = converter.convert()\n converter.experimental_enable_mlir_converter = use_mlir_converter\n\n interpreter = tf.lite.Interpreter(model_content=tflite)\n\n try:\n interpreter.allocate_tensors()\n except ValueError:\n assert False\n\n input_index = (interpreter.get_input_details()[0][\"index\"])\n interpreter.set_tensor(input_index, test_inputs)\n interpreter.invoke()\n output_index = (interpreter.get_output_details()[0][\"index\"])\n result = interpreter.get_tensor(output_index)\n # Reset all variables so it will not pollute other inferences.\n interpreter.reset_all_variables()\n return result\n\n def testStaticRnnMultiRnnCell(self):\n sess = tf.compat.v1.Session(config=CONFIG)\n\n x, prediction, output_class = self.buildModel(\n self.buildLstmLayer(), is_dynamic_rnn=False)\n self.trainModel(x, prediction, output_class, sess)\n\n saver = tf.train.Saver()\n x, prediction, output_class, new_sess = self.saveAndRestoreModel(\n self.buildLstmLayer(), sess, saver, is_dynamic_rnn=False)\n\n test_inputs, expected_output = self.getInferenceResult(\n x, output_class, new_sess)\n\n # Test Toco-converted model.\n result = self.tfliteInvoke(new_sess, test_inputs, x, output_class, False)\n self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2))\n\n @test_util.enable_control_flow_v2\n def testDynamicRnnMultiRnnCell(self):\n sess = tf.compat.v1.Session(config=CONFIG)\n\n x, prediction, output_class = self.buildModel(\n self.buildLstmLayer(), is_dynamic_rnn=True)\n self.trainModel(x, prediction, output_class, sess)\n\n saver = tf.train.Saver()\n\n x, prediction, output_class, new_sess = self.saveAndRestoreModel(\n self.buildLstmLayer(), sess, saver, is_dynamic_rnn=True)\n\n test_inputs, expected_output = self.getInferenceResult(\n x, output_class, new_sess)\n\n # Test Toco-converted model.\n result = self.tfliteInvoke(new_sess, test_inputs, x, output_class, False)\n self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.python.ops.control_flow_util_v2.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import control_flow_util_v2\nfrom tensorflow.python.platform import test\n\n\nclass ControlFlowUtilV2Test(test.TestCase):\n\n def setUp(self):\n self._enable_control_flow_v2_old = control_flow_util.ENABLE_CONTROL_FLOW_V2\n control_flow_util.ENABLE_CONTROL_FLOW_V2 = True\n\n def tearDown(self):\n control_flow_util.ENABLE_CONTROL_FLOW_V2 = self._enable_control_flow_v2_old\n\n def _create_control_flow(self, expect_in_defun):\n \"\"\"Helper method for testInDefun.\"\"\"\n def body(i):\n def branch():\n self.assertEqual(control_flow_util_v2.in_defun(), expect_in_defun)\n return i + 1\n return control_flow_ops.cond(constant_op.constant(True),\n branch, lambda: 0)\n return control_flow_ops.while_loop(lambda i: i < 4, body,\n [constant_op.constant(0)])\n\n @test_util.run_in_graph_and_eager_modes\n def testInDefun(self):\n self._create_control_flow(False)\n\n @function.defun\n def defun():\n self._create_control_flow(True)\n\n defun()\n self.assertFalse(control_flow_util_v2.in_defun())\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for MirroredFunctionStrategy.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import mirrored_function_strategy\nfrom tensorflow.python.distribute import strategy_combinations\nfrom tensorflow.python.distribute import values\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import test\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\n\n\nclass MirroredFunctionStrategyTest(test.TestCase):\n\n def setUp(self):\n super(MirroredFunctionStrategyTest, self).setUp()\n strategy_combinations.set_virtual_cpus_to_at_least(3)\n self._strategy = mirrored_function_strategy.MirroredFunctionStrategy(\n devices=(\"/cpu:1\", \"/cpu:2\"))\n\n def testReplicaId(self):\n f_traces = []\n\n @def_function.function\n def f(x):\n f_traces.append(None) # Only happens on trace.\n replica_context = distribution_strategy_context.get_replica_context()\n # This is a non-constant tensor.\n replica_id = replica_context.replica_id_in_sync_group\n self.assertIsInstance(replica_id, ops.Tensor)\n self.assertIsNone(tensor_util.constant_value(replica_id))\n return x + replica_id\n\n one = constant_op.constant(1)\n self.assertLen(f_traces, 0)\n result1 = self._strategy.experimental_run_v2(f, args=(one,))\n self.assertLen(f_traces, 1) # Function traced once, not for each replica.\n # Returns a per-replica value.\n self.assertIsInstance(result1, values.PerReplica)\n self.assertAllEqual([1, 2], result1.values)\n self.assertAllEqual([1, 2],\n self._strategy.experimental_local_results(result1))\n\n # Try passing a per-replica value as an argument.\n result2 = self._strategy.experimental_run_v2(f, args=(result1,))\n self.assertLen(f_traces, 1)\n self.assertIsInstance(result2, values.PerReplica)\n self.assertAllEqual([1, 3], result2.values)\n\n def testMergeCall(self):\n f_traces = []\n g_traces = []\n\n def g(strategy, z):\n g_traces.append(None) # Only happens on trace.\n self.assertIs(strategy, self._strategy)\n self.assertTrue(distribution_strategy_context.in_cross_replica_context())\n self.assertIsInstance(z, mirrored_function_strategy.FnMergedValue)\n return z\n\n @def_function.function\n def f(x):\n f_traces.append(None) # Only happens on trace.\n replica_context = distribution_strategy_context.get_replica_context()\n y = replica_context.merge_call(g, args=(x,))\n self.assertIsInstance(y, ops.Tensor)\n return y\n\n one = constant_op.constant(1)\n self.assertLen(f_traces, 0)\n self.assertLen(g_traces, 0)\n result = self._strategy.experimental_run_v2(f, args=(one,))\n # Functions traced once, not for each replica.\n self.assertLen(f_traces, 1)\n self.assertLen(g_traces, 1)\n # Returns a per-replica value.\n self.assertIsInstance(result, values.PerReplica)\n self.assertAllEqual([1, 1], result.values)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tools.docs.doc_generator_visitor.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport types\n\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.tools.docs import doc_generator_visitor\nfrom tensorflow.tools.docs import generate_lib\n\n\nclass NoDunderVisitor(doc_generator_visitor.DocGeneratorVisitor):\n\n def __call__(self, parent_name, parent, children):\n \"\"\"Drop all the dunder methods to make testing easier.\"\"\"\n children = [\n (name, obj) for (name, obj) in children if not name.startswith('_')\n ]\n super(NoDunderVisitor, self).__call__(parent_name, parent, children)\n\n\nclass DocGeneratorVisitorTest(googletest.TestCase):\n\n def test_call_module(self):\n visitor = doc_generator_visitor.DocGeneratorVisitor()\n visitor(\n 'doc_generator_visitor', doc_generator_visitor,\n [('DocGeneratorVisitor', doc_generator_visitor.DocGeneratorVisitor)])\n\n self.assertEqual({'doc_generator_visitor': ['DocGeneratorVisitor']},\n visitor.tree)\n self.assertEqual({\n 'doc_generator_visitor': doc_generator_visitor,\n 'doc_generator_visitor.DocGeneratorVisitor':\n doc_generator_visitor.DocGeneratorVisitor,\n }, visitor.index)\n\n def test_call_class(self):\n visitor = doc_generator_visitor.DocGeneratorVisitor()\n visitor(\n 'DocGeneratorVisitor', doc_generator_visitor.DocGeneratorVisitor,\n [('index', doc_generator_visitor.DocGeneratorVisitor.index)])\n\n self.assertEqual({'DocGeneratorVisitor': ['index']},\n visitor.tree)\n self.assertEqual({\n 'DocGeneratorVisitor': doc_generator_visitor.DocGeneratorVisitor,\n 'DocGeneratorVisitor.index':\n doc_generator_visitor.DocGeneratorVisitor.index\n }, visitor.index)\n\n def test_call_raises(self):\n visitor = doc_generator_visitor.DocGeneratorVisitor()\n with self.assertRaises(RuntimeError):\n visitor('non_class_or_module', 'non_class_or_module_object', [])\n\n def test_duplicates_module_class_depth(self):\n\n class Parent(object):\n\n class Nested(object):\n pass\n\n tf = types.ModuleType('tf')\n tf.Parent = Parent\n tf.submodule = types.ModuleType('submodule')\n tf.submodule.Parent = Parent\n\n visitor = generate_lib.extract(\n [('tf', tf)],\n private_map={},\n do_not_descend_map={},\n visitor_cls=NoDunderVisitor)\n\n self.assertEqual({\n 'tf.submodule.Parent':\n sorted([\n 'tf.Parent',\n 'tf.submodule.Parent',\n ]),\n 'tf.submodule.Parent.Nested':\n sorted([\n 'tf.Parent.Nested',\n 'tf.submodule.Parent.Nested',\n ]),\n }, visitor.duplicates)\n\n self.assertEqual({\n 'tf.Parent.Nested': 'tf.submodule.Parent.Nested',\n 'tf.Parent': 'tf.submodule.Parent',\n }, visitor.duplicate_of)\n\n self.assertEqual({\n id(Parent): 'tf.submodule.Parent',\n id(Parent.Nested): 'tf.submodule.Parent.Nested',\n id(tf): 'tf',\n id(tf.submodule): 'tf.submodule',\n }, visitor.reverse_index)\n\n def test_duplicates_contrib(self):\n\n class Parent(object):\n pass\n\n tf = types.ModuleType('tf')\n tf.contrib = types.ModuleType('contrib')\n tf.submodule = types.ModuleType('submodule')\n tf.contrib.Parent = Parent\n tf.submodule.Parent = Parent\n\n visitor = generate_lib.extract(\n [('tf', tf)],\n private_map={},\n do_not_descend_map={},\n visitor_cls=NoDunderVisitor)\n\n self.assertEqual({\n 'tf.submodule.Parent':\n sorted(['tf.contrib.Parent', 'tf.submodule.Parent']),\n }, visitor.duplicates)\n\n self.assertEqual({\n 'tf.contrib.Parent': 'tf.submodule.Parent',\n }, visitor.duplicate_of)\n\n self.assertEqual({\n id(tf): 'tf',\n id(tf.submodule): 'tf.submodule',\n id(Parent): 'tf.submodule.Parent',\n id(tf.contrib): 'tf.contrib',\n }, visitor.reverse_index)\n\n def test_duplicates_defining_class(self):\n\n class Parent(object):\n obj1 = object()\n\n class Child(Parent):\n pass\n\n tf = types.ModuleType('tf')\n tf.Parent = Parent\n tf.Child = Child\n\n visitor = generate_lib.extract(\n [('tf', tf)],\n private_map={},\n do_not_descend_map={},\n visitor_cls=NoDunderVisitor)\n\n self.assertEqual({\n 'tf.Parent.obj1': sorted([\n 'tf.Parent.obj1',\n 'tf.Child.obj1',\n ]),\n }, visitor.duplicates)\n\n self.assertEqual({\n 'tf.Child.obj1': 'tf.Parent.obj1',\n }, visitor.duplicate_of)\n\n self.assertEqual({\n id(tf): 'tf',\n id(Parent): 'tf.Parent',\n id(Child): 'tf.Child',\n id(Parent.obj1): 'tf.Parent.obj1',\n }, visitor.reverse_index)\n\n def test_duplicates_module_depth(self):\n\n class Parent(object):\n pass\n\n tf = types.ModuleType('tf')\n tf.submodule = types.ModuleType('submodule')\n tf.submodule.submodule2 = types.ModuleType('submodule2')\n tf.Parent = Parent\n tf.submodule.submodule2.Parent = Parent\n\n visitor = generate_lib.extract(\n [('tf', tf)],\n private_map={},\n do_not_descend_map={},\n visitor_cls=NoDunderVisitor)\n\n self.assertEqual({\n 'tf.Parent': sorted(['tf.Parent', 'tf.submodule.submodule2.Parent']),\n }, visitor.duplicates)\n\n self.assertEqual({\n 'tf.submodule.submodule2.Parent': 'tf.Parent'\n }, visitor.duplicate_of)\n\n self.assertEqual({\n id(tf): 'tf',\n id(tf.submodule): 'tf.submodule',\n id(tf.submodule.submodule2): 'tf.submodule.submodule2',\n id(Parent): 'tf.Parent',\n }, visitor.reverse_index)\n\n def test_duplicates_name(self):\n\n class Parent(object):\n obj1 = object()\n\n Parent.obj2 = Parent.obj1\n\n tf = types.ModuleType('tf')\n tf.submodule = types.ModuleType('submodule')\n tf.submodule.Parent = Parent\n\n visitor = generate_lib.extract(\n [('tf', tf)],\n private_map={},\n do_not_descend_map={},\n visitor_cls=NoDunderVisitor)\n\n self.assertEqual({\n 'tf.submodule.Parent.obj1':\n sorted([\n 'tf.submodule.Parent.obj1',\n 'tf.submodule.Parent.obj2',\n ]),\n }, visitor.duplicates)\n\n self.assertEqual({\n 'tf.submodule.Parent.obj2': 'tf.submodule.Parent.obj1',\n }, visitor.duplicate_of)\n\n self.assertEqual({\n id(tf): 'tf',\n id(tf.submodule): 'tf.submodule',\n id(Parent): 'tf.submodule.Parent',\n id(Parent.obj1): 'tf.submodule.Parent.obj1',\n }, visitor.reverse_index)\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#==============================================================================\n\"\"\"Contains utility functions used by summary ops in distribution strategy.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\n\n\ndef skip_summary():\n \"\"\"Determines if summary should be skipped.\n\n If using multiple replicas in distributed strategy, skip summaries on all\n replicas except the first one (replica_id=0).\n\n Returns:\n True if the summary is skipped; False otherwise.\n \"\"\"\n\n # TODO(priyag): Add a new optional argument that will provide multiple\n # alternatives to override default behavior. (e.g. run on last replica,\n # compute sum or mean across replicas).\n replica_context = distribution_strategy_context.get_replica_context()\n if not replica_context:\n return False\n # TODO(b/118385803): when replica_id of _TPUReplicaContext is properly\n # initialized, remember to change here as well.\n replica_id = replica_context.replica_id_in_sync_group\n if isinstance(replica_id, ops.Tensor):\n replica_id = tensor_util.constant_value(replica_id)\n return replica_id and replica_id > 0\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport os\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.distribute import combinations\nfrom tensorflow.python.distribute import strategy_combinations\nfrom tensorflow.python.distribute import tpu_strategy\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import test\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.optimizer_v2 import adam\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables as variables_lib\nfrom tensorflow.python.training import adam as adam_v1\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.training.tracking import util as trackable_utils\n\n\nclass NonLayerTrackable(tracking.AutoTrackable):\n\n def __init__(self):\n super(NonLayerTrackable, self).__init__()\n self.a_variable = trackable_utils.add_variable(\n self, name=\"a_variable\", shape=[])\n\n\nclass Subclassed(training.Model):\n \"\"\"A concrete Model for testing.\"\"\"\n\n def __init__(self):\n super(Subclassed, self).__init__()\n self._named_dense = core.Dense(1, use_bias=True)\n self._second = core.Dense(1, use_bias=False)\n # We can still track Trackables which aren't Layers.\n self._non_layer = NonLayerTrackable()\n\n def call(self, values):\n ret = self._second(self._named_dense(values))\n return ret\n\n\nclass TrainingCheckpointTests(test.TestCase, parameterized.TestCase):\n\n def testEagerTPUDistributionStrategy(self):\n self.skipTest(\"b/121387144\")\n num_training_steps = 10\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n\n def _train_fn(optimizer, model):\n input_value = constant_op.constant([[3.]])\n optimizer.minimize(\n functools.partial(model, input_value),\n global_step=root.optimizer_step)\n\n for training_continuation in range(3):\n strategy = tpu_strategy.TPUStrategy()\n with strategy.scope():\n model = Subclassed()\n optimizer = adam_v1.AdamOptimizer(0.001)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model,\n optimizer_step=training_util.get_or_create_global_step())\n root.restore(checkpoint_management.latest_checkpoint(\n checkpoint_directory))\n\n for _ in range(num_training_steps):\n strategy.extended.call_for_each_replica(\n functools.partial(_train_fn, optimizer, model))\n root.save(file_prefix=checkpoint_prefix)\n self.assertEqual((training_continuation + 1) * num_training_steps,\n root.optimizer_step.numpy())\n\n @combinations.generate(\n combinations.combine(\n distribution=[\n strategy_combinations.mirrored_strategy_with_one_cpu,\n strategy_combinations.mirrored_strategy_with_gpu_and_cpu,\n strategy_combinations.tpu_strategy,\n strategy_combinations.central_storage_strategy_with_two_gpus,\n ],\n mode=[\"eager\"]))\n def testCheckpointRestoreOptimizerSlots(self, distribution):\n def state():\n with distribution.scope():\n v = variables_lib.Variable(random_ops.random_normal([]))\n opt = adam.Adam(0.001)\n\n @def_function.function\n def step():\n def f():\n with backprop.GradientTape() as tape:\n loss = v + v\n gradients = tape.gradient(loss, [v])\n opt.apply_gradients(zip(gradients, [v]))\n distribution.experimental_run_v2(f)\n\n return v, opt, step\n\n def checkpoint():\n v, opt, step = state()\n step()\n\n # Save random weights into checkpoint.\n checkpoint = trackable_utils.Checkpoint(v=v, opt=opt)\n prefix = os.path.join(self.get_temp_dir(), \"ckpt\")\n with self.test_session():\n save_path = checkpoint.save(prefix)\n return save_path\n\n save_path = checkpoint()\n\n v, opt, step = state()\n checkpoint = trackable_utils.Checkpoint(v=v, opt=opt)\n # Restore from the checkpoint inside a distribution.scope().\n with self.test_session():\n with distribution.scope():\n checkpoint.restore(save_path)\n step()\n slot = opt.get_slot(v, \"m\")\n self.assertEqual(v._distribute_strategy, slot._distribute_strategy)\n\n v, opt, step = state()\n checkpoint = trackable_utils.Checkpoint(v=v, opt=opt)\n # Restore from the checkpoint outside a distribution.scope().\n with self.test_session():\n with self.assertRaisesRegex(\n ValueError, \"optimizer slot variable under the scope\"):\n checkpoint.restore(save_path)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Benchmark for split and grad of split.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\nimport random\nimport time\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\ndef build_graph(device, input_shape, variable, num_inputs, axis, grad):\n \"\"\"Build a graph containing a sequence of concat operations.\n\n Args:\n device: string, the device to run on.\n input_shape: shape of the input tensors.\n variable: whether or not to randomize the input shape\n num_inputs: the number of inputs to concat\n axis: axis to be concat'ed\n grad: if True compute the gradient\n\n Returns:\n An array of tensors to run()\n \"\"\"\n with ops.device(\"/%s:0\" % device):\n if not variable:\n inputs = [array_ops.zeros(input_shape) for _ in range(num_inputs)]\n else:\n if axis == 1:\n inputs = [\n array_ops.zeros([\n input_shape[0],\n random.randint(max(1, input_shape[1] - 5), input_shape[1] + 5)\n ]) for _ in range(num_inputs)\n ]\n else:\n inputs = [\n array_ops.zeros([\n random.randint(max(1, input_shape[0] - 5), input_shape[0] + 5),\n input_shape[1]\n ]) for _ in range(num_inputs)\n ]\n\n outputs = [array_ops.concat(inputs, axis) for _ in range(100)]\n if grad:\n return control_flow_ops.group(*list(\n itertools.chain.from_iterable([\n gradients_impl.gradients(output, inputs) for output in outputs\n ])))\n else:\n return control_flow_ops.group(*outputs)\n\n\nclass ConcatBenchmark(test.Benchmark):\n \"\"\"Benchmark concat.\"\"\"\n\n def _run_graph(self, device, input_shape, variable, num_inputs, axis, grad,\n num_iters):\n \"\"\"Run the graph and print its execution time.\n\n Args:\n device: string, the device to run on.\n input_shape: shape of the input tensors.\n variable: whether or not the input shape should be fixed\n num_inputs: the number of inputs to concat\n axis: axis to be concat'ed\n grad: if True compute the gradient\n num_iters: number of steps to run.\n\n Returns:\n The duration of the run in seconds.\n \"\"\"\n graph = ops.Graph()\n with graph.as_default():\n outputs = build_graph(device, input_shape, variable, num_inputs, axis,\n grad)\n config = config_pb2.ConfigProto(graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L0)))\n with session_lib.Session(graph=graph, config=config) as session:\n variables.global_variables_initializer().run()\n _ = session.run(outputs) # warm up.\n start_time = time.time()\n for _ in range(num_iters):\n _ = session.run(outputs)\n duration = time.time() - start_time\n print(\"%s shape:%d/%d var: %r #inputs:%d axis:%d grad:%r - %f secs - %f \"\n \"GB/sec\" % (device, input_shape[0], input_shape[1], variable,\n num_inputs, axis, grad, duration / num_iters,\n num_inputs * input_shape[0] * input_shape[1] * 4 * 2 *\n 100 / (duration / num_iters) / 1e9))\n\n name_template = (\n \"concat_bench_{device}_input_shape_{shape}_variable_{variable}\"\n \"_num_inputs_{num_inputs}_axis_{axis}_grad_{grad}\")\n\n self.report_benchmark(name=name_template.format(\n device=device,\n num_inputs=num_inputs,\n variable=variable,\n grad=grad,\n shape=str(input_shape).replace(\" \", \"\"),\n axis=str(axis),\n iters=num_iters))\n\n return duration\n\n def benchmark_concat(self):\n print(\"Forward vs backward concat\")\n shapes = [[2000, 8], [8, 2000], [100, 18], [1000, 18], [100, 97],\n [1000, 97], [10000, 1], [1, 10000]]\n axis_ = [0, 1]\n num_inputs = 20\n num_iters = [10] * len(shapes)\n variable = [False, True] # fixed input size or not\n for shape, iters in zip(shapes, num_iters):\n for axis in axis_:\n for v in variable:\n self._run_graph(\"cpu\", shape, v, num_inputs, axis, True, iters)\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "tensorflow.python.ops.state_ops.batch_scatter_update", "numpy.random.seed", "tensorflow.python.framework.ops.IndexedSlices", "tensorflow.python.ops.variables.Variable", "tensorflow.python.platform.test.main", "numpy.random.randint", "numpy.random.randn", "numpy.ndenumerate", "numpy.array", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.backend.image_data_format", "tensorflow.python.util.tf_export.keras_export", "tensorflow.python.keras.datasets.cifar.load_batch", "numpy.empty", "tensorflow.python.keras.utils.data_utils.get_file" ], [ "tensorflow.python.pywrap_tensorflow.TF_GetBuffer", "tensorflow.python.pywrap_tensorflow.TF_GetRegisteredKernelsForOp", "tensorflow.core.framework.kernel_def_pb2.KernelList", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.pywrap_tensorflow.TF_GetAllRegisteredKernels" ], [ "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.is_built_with_rocm", "tensorflow.python.framework.ops.device", "numpy.swapaxes", "numpy.matmul", "numpy.finfo", "tensorflow.python.platform.test.main", "tensorflow.python.platform.benchmark.benchmark_config", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.gradient_checker_v2.compute_gradient", "numpy.zeros", "tensorflow.python.framework.test_util.xla_allow_fallback", "tensorflow.python.compat.compat.forward_compatibility_horizon", "tensorflow.python.ops.array_ops.broadcast_to", "numpy.random.seed", "tensorflow.python.framework.ops.Graph", "tensorflow.python.tf2.enabled", "numpy.prod", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.ops.array_ops.broadcast_static_shape" ], [ "tensorflow.python.keras.engine.input_spec.InputSpec", "tensorflow.python.platform.test.main", "tensorflow.python.keras.engine.input_spec.to_tensor_shape" ], [ "tensorflow.python.eager.tape.record_operation", "tensorflow.python.ops.gen_state_ops.resource_count_up_to", "tensorflow.python.ops.state_ops.batch_scatter_update", "tensorflow.python.ops.variables.Variable.SaveSliceInfo", "tensorflow.python._pywrap_utils.RegisterType", "tensorflow.python.ops.gen_resource_variable_ops.assign_variable_op", "tensorflow.python.framework.ops.add_to_collection", "tensorflow.python.ops.variables._try_guard_against_uninitialized_dependencies", "tensorflow.python.framework.ops.register_dense_tensor_like_type", "tensorflow.python.framework.ops.name_from_scope_name", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.gen_resource_variable_ops.resource_gather_nd", "tensorflow.python.eager.context.context", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.framework.ops.register_proto_function", "tensorflow.python.framework.ops.NotDifferentiable", "tensorflow.python.ops.gen_resource_variable_ops.var_handle_op", "tensorflow.python.ops.math_ops.logical_not", "tensorflow.python.framework.ops.RegisterGradient", "tensorflow.python.ops.variables.Variable.from_proto", "tensorflow.python.framework.ops.IndexedSlices", "tensorflow.python.ops.array_ops.size", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.framework.ops.register_tensor_conversion_function", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.ops.gen_resource_variable_ops.var_is_initialized_op", "tensorflow.python.framework.ops.init_scope", "tensorflow.python.framework.cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.framework.ops.prepend_name_scope", "tensorflow.python.eager.tape.variable_accessed", "tensorflow.python.util.deprecation.deprecated_args", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.framework.ops.has_default_graph", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.framework.ops.strip_name_scope", "tensorflow.python.ops.gen_resource_variable_ops.variable_shape", "tensorflow.python.ops.gen_resource_variable_ops.resource_gather", "tensorflow.python.framework.ops.add_to_collections", "tensorflow.python.ops.gen_resource_variable_ops.read_variable_op", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.framework.ops.uid", "tensorflow.python.ops.variables.validate_synchronization_aggregation_trainable", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.eager.context.shared_name", "tensorflow.python.framework.tensor_shape.as_shape", "tensorflow.core.framework.variable_pb2.VariableDef", "tensorflow.python.ops.gen_resource_variable_ops.destroy_resource_op", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.core.framework.step_stats_pb2.NodeExecStats", "tensorflow.python.debug.lib.profiling.AggregateProfile", "tensorflow.python.debug.lib.profiling.ProfileDatum", "tensorflow.python.platform.googletest.main" ], [ "tensorflow.python.keras.preprocessing.image.ImageDataGenerator", "tensorflow.python.keras.preprocessing.image.random_zoom", "numpy.random.random", "tensorflow.python.keras.preprocessing.image.apply_affine_transform", "numpy.arange", "numpy.vstack", "tensorflow.python.keras.preprocessing.image.random_shear", "tensorflow.python.keras.preprocessing.image.apply_channel_shift", "tensorflow.python.keras.preprocessing.image.random_rotation", "tensorflow.python.keras.preprocessing.image.img_to_array", "tensorflow.python.keras.preprocessing.image.load_img", "numpy.copy", "tensorflow.python.platform.test.main", "numpy.random.rand", "numpy.zeros_like", "tensorflow.python.keras.preprocessing.image.random_channel_shift", "tensorflow.python.keras.preprocessing.image.random_shift", "tensorflow.python.keras.preprocessing.image.array_to_img" ], [ "tensorflow.python.keras.optimizer_v2.ftrl.Ftrl", "tensorflow.python.ops.resource_variable_ops.ResourceVariable", "tensorflow.python.training.adagrad.AdagradOptimizer", "tensorflow.python.ops.embedding_ops.embedding_lookup", "tensorflow.python.ops.variables.Variable", "tensorflow.python.platform.test.main", "tensorflow.python.ops.variables.global_variables_initializer", "numpy.array", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.engine.sequential.Sequential", "numpy.asarray", "tensorflow.python.ops.array_ops.split", "numpy.zeros_like", "numpy.where", "tensorflow.python.feature_column.feature_column_v2.categorical_column_with_vocabulary_list", "tensorflow.python.feature_column.dense_features_v2.DenseFeatures", "tensorflow.python.platform.test.main", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.keras.keras_parameterized.run_all_keras_modes", "tensorflow.python.keras.optimizer_v2.gradient_descent.SGD", "numpy.random.choice", "tensorflow.python.feature_column.feature_column_v2.embedding_column", "tensorflow.python.keras.testing_utils.should_run_tf_function", "tensorflow.python.keras.engine.input_layer.Input", "tensorflow.python.keras.premade.wide_deep.WideDeepModel.from_config", "tensorflow.python.keras.layers.core.Dense", "numpy.array", "tensorflow.python.keras.premade.linear.LinearModel", "tensorflow.python.keras.premade.wide_deep.WideDeepModel", "tensorflow.python.keras.testing_utils.should_run_eagerly", "tensorflow.python.feature_column.feature_column_v2.indicator_column", "numpy.random.uniform", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.keras.engine.training.Model" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.variable_scope.variable_creator_scope", "tensorflow.python.framework.ops.name_from_scope_name", "tensorflow.python.eager.context.context", "tensorflow.python.framework.ops.get_collection_ref", "tensorflow.python.framework.ops.get_collection", "tensorflow.core.protobuf.struct_pb2.StructuredValue", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.util.nest.map_structure", "tensorflow.python.framework.func_graph.func_graph_from_py_func", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.framework.func_graph.FuncGraph", "tensorflow.python.framework.tensor_util.is_tensor", "tensorflow.python.saved_model.nested_structure_coder.StructureCoder", "tensorflow.python.util.nest.pack_sequence_as", "tensorflow.python.framework.ops.add_to_collections", "tensorflow.python.training.tracking.data_structures.Mapping", "tensorflow.python.ops.resource_variable_ops.UninitializedVariable", "tensorflow.python.eager.lift_to_graph.lift_to_graph", "tensorflow.python.ops.resource_variable_ops.is_resource_variable", "tensorflow.python.util.nest.flatten" ], [ "tensorflow.python.framework.ops.Graph", "tensorflow.python.data.ops.dataset_ops.Options", "tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator", "tensorflow.python.client.session.Session", "tensorflow.python.data.experimental.ops.sleep.sleep", "tensorflow.python.platform.test.main", "numpy.mean", "tensorflow.python.data.ops.dataset_ops.Dataset.range" ], [ "tensorflow.python.ops.ragged.ragged_array_ops.stack_dynamic_partitions", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.data_flow_ops.dynamic_partition", "tensorflow.python.eager.context.executing_eagerly" ], [ "tensorflow.core.example.feature_pb2.BytesList", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "numpy.asarray", "tensorflow.core.example.feature_pb2.Features", "tensorflow.python.ops.parsing_ops.RaggedFeature.RowSplits", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.core.example.feature_pb2.FeatureLists", "tensorflow.python.data.experimental.ops.parsing_ops.parse_example_dataset", "tensorflow.python.platform.test.main", "tensorflow.python.ops.parsing_ops.RaggedFeature.RowLengths", "tensorflow.python.ops.parsing_ops.RaggedFeature.UniformRowLength", "tensorflow.python.ops.parsing_ops.FixedLenFeature", "tensorflow.python.ops.parsing_ops.RaggedFeature.ValueRowIds", "tensorflow.python.ops.parsing_ops.RaggedFeature.RowLimits", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.core.example.feature_pb2.Int64List", "tensorflow.python.framework.ops.convert_to_tensor", "numpy.random.rand", "tensorflow.core.example.feature_pb2.FeatureList", "numpy.array", "tensorflow.python.ops.ragged.ragged_factory_ops.constant_value", "numpy.random.seed", "tensorflow.core.example.feature_pb2.FloatList", "tensorflow.python.ops.parsing_ops.VarLenFeature", "tensorflow.python.ops.parsing_ops.RaggedFeature.RowStarts", "tensorflow.python.ops.parsing_ops.SparseFeature", "tensorflow.python.ops.parsing_ops.FixedLenSequenceFeature", "tensorflow.python.ops.parsing_ops.RaggedFeature", "numpy.empty" ], [ "tensorflow.python.data.experimental.ops.counter.Counter", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.platform.test.main", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_types" ], [ "tensorflow.python.framework.sparse_tensor.SparseTensorValue", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.data.kernel_tests.test_base.default_test_combinations", "numpy.arange", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.platform.test.main", "tensorflow.python.ops.sparse_ops.sparse_to_dense", "tensorflow.python.data.experimental.ops.interleave_ops.parallel_interleave", "numpy.array", "numpy.sum" ], [ "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.test.main", "tensorflow.python.framework.constant_op.constant" ], [ "numpy.sqrt", "numpy.asarray", "numpy.squeeze", "tensorflow.python.ops.array_ops.placeholder", "numpy.concatenate", "numpy.max", "tensorflow.python.ops.array_ops.zeros", "numpy.zeros_like", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.gradients_impl.gradients", "numpy.exp", "numpy.tril", "tensorflow.python.ops.array_ops.stop_gradient", "tensorflow.python.ops.nn_ops.softplus", "numpy.roll", "tensorflow.python.ops.array_ops.identity", "numpy.ones_like", "tensorflow.python.ops.math_ops.reduce_logsumexp", "numpy.arange", "tensorflow.python.ops.math_ops.less", "numpy.finfo", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.ones", "numpy.log1p", "numpy.triu", "numpy.zeros", "tensorflow.python.platform.tf_logging.vlog", "numpy.log", "tensorflow.python.ops.gradient_checker.compute_gradient_error", "numpy.isnan", "numpy.logspace", "numpy.floor", "numpy.errstate", "numpy.array", "numpy.random.RandomState", "numpy.logaddexp", "numpy.isfinite", "numpy.int32", "numpy.ones", "numpy.sign", "tensorflow.python.ops.array_ops.placeholder_with_default", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.util.tf_export.tf_export" ], [ "numpy.amax", "tensorflow.python.compat.compat.forward_compatible", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.nn_ops.softmax_cross_entropy_with_logits_v2", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.ops.nn_ops.softmax_cross_entropy_with_logits", "tensorflow.python.platform.test.main", "numpy.zeros", "numpy.log", "tensorflow.python.ops.gradient_checker.compute_gradient_error", "tensorflow.python.ops.gen_nn_ops.softmax_cross_entropy_with_logits", "tensorflow.python.client.session.Session", "numpy.array", "numpy.sum", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.platform.test.main" ], [ "tensorflow.python.ops.functional_ops.remote_call", "tensorflow.python.framework.test_util.create_local_cluster", "tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.framework.ops.device", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_types", "tensorflow.python.framework.test_util.run_v1_only", "numpy.arange", "tensorflow.python.framework.function.Defun", "tensorflow.python.ops.string_ops.string_split", "tensorflow.python.platform.test.main", "tensorflow.python.ops.lookup_ops.KeyValueTensorInitializer", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.data.ops.dataset_ops.make_initializable_iterator", "tensorflow.python.ops.math_ops.square", "tensorflow.python.client.session.Session", "numpy.array", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.kernel_tests.proto.test_example_pb2.PackedTestValue", "tensorflow.python.kernel_tests.proto.test_example_pb2.PrimitiveValue", "numpy.reshape", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.kernel_tests.proto.proto_op_test_base.ProtoOpTestBase.named_parameters", "numpy.array", "tensorflow.python.kernel_tests.proto.test_example_pb2.ExtraFields", "numpy.isclose" ], [ "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.ragged.ragged_array_ops.rank" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.framework.sparse_tensor.SparseTensorValue", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.data.kernel_tests.test_base.default_test_combinations", "tensorflow.python.platform.test.main", "tensorflow.python.ops.sparse_ops.sparse_to_dense", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "numpy.array", "numpy.sum", "tensorflow.python.framework.combinations.combine" ], [ "tensorflow.python.ops.gen_experimental_dataset_ops.sleep_dataset" ], [ "tensorflow.python.util.all_util.remove_undocumented" ], [ "numpy.zeros", "tensorflow.python.debug.TensorBoardDebugWrapperSession", "tensorflow.python.debug.LocalCLIDebugWrapperSession" ], [ "numpy.diag", "numpy.take", "tensorflow.python.platform.test.test_src_dir_path", "tensorflow.python.platform.test.is_built_with_rocm", "tensorflow.python.ops.linalg_ops.self_adjoint_eig", "numpy.reshape", "numpy.linalg.eig", "numpy.eye", "tensorflow.python.ops.linalg_ops.eig", "tensorflow.python.platform.test.main", "tensorflow.python.ops.linalg_ops.matrix_inverse", "tensorflow.python.ops.linalg_ops.eigvals", "numpy.argsort", "numpy.abs", "numpy.random.seed", "numpy.conj", "numpy.tile", "tensorflow.python.ops.array_ops.matrix_diag", "numpy.prod", "tensorflow.python.ops.random_ops.random_normal", "numpy.random.uniform", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.summary.summary_iterator.summary_iterator", "tensorflow.python.training.tensorboard_logging._clear_summary_writer", "tensorflow.python.training.tensorboard_logging.warn", "tensorflow.python.training.tensorboard_logging.error", "tensorflow.python.training.tensorboard_logging.debug", "tensorflow.python.platform.test.main", "tensorflow.python.summary.writer.writer.FileWriter", "tensorflow.python.training.tensorboard_logging.set_verbosity", "tensorflow.python.training.tensorboard_logging.set_summary_writer", "tensorflow.python.training.tensorboard_logging.log" ], [ "tensorflow.python.framework.ops.enable_eager_execution", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.gen_math_ops.Any", "tensorflow.python.platform.test.main", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.gen_math_ops.Add" ], [ "tensorflow.python.framework.config.list_physical_devices", "tensorflow.python.distribute.combinations.combine", "tensorflow.python.framework.config.get_virtual_device_configuration", "tensorflow.python.platform.test.main", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.distribute.strategy_combinations.set_virtual_cpus_to_at_least" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.math_ops.add_n", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.gen_state_ops.destroy_temporary_variable", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.client.session.Session", "tensorflow.python.platform.test.main", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.gen_control_flow_ops.merge", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.ops.gen_state_ops.temporary_variable" ], [ "tensorflow.python.ops.linalg.linalg.LinearOperatorIdentity", "tensorflow.python.ops.linalg.linear_operator_test_util.add_tests", "tensorflow.python.ops.linalg.linalg.LinearOperatorZeros", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.placeholder_with_default", "numpy.random.RandomState" ], [ "tensorflow.python.lib.io.file_io.is_directory", "tensorflow.io.TFRecordWriter", "tensorflow.python.lib.io.file_io.recursive_create_dir", "tensorflow.compat.v1.TFRecordReader", "numpy.random.randn", "tensorflow.compat.v1.python_io.tf_record_iterator", "tensorflow.compat.v1.app.run", "tensorflow.Graph", "tensorflow.compat.v1.train.start_queue_runners", "numpy.arange", "tensorflow.python.lib.io.file_io.delete_recursively", "tensorflow.python.lib.io.file_io.rename", "tensorflow.compat.v1.local_variables_initializer", "tensorflow.compat.v1.train.string_input_producer", "tensorflow.python.lib.io.file_io.create_dir", "tensorflow.python.lib.io.file_io.file_exists", "tensorflow.python.lib.io.file_io.list_directory", "tensorflow.python.lib.io.file_io.get_matching_files", "tensorflow.core.example.example_pb2.Example", "tensorflow.python.lib.io.file_io.write_string_to_file", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.Session" ], [ "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.platform.googletest.main", "numpy.array", "tensorflow.python.ops.ragged.ragged_factory_ops.constant_value", "tensorflow.python.ops.ragged.ragged_tensor.convert_to_tensor_or_ragged_tensor", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.engine.network.get_network_config", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.keras.backend.track_tf_optimizer", "tensorflow.python.keras.engine.network._should_skip_first_node", "tensorflow.python.keras.utils.generic_utils.to_list", "tensorflow.python.util.tf_export.keras_export", "tensorflow.python.keras.backend.is_keras_tensor", "tensorflow.python.keras.engine.network.reconstruct_from_config", "tensorflow.python.keras.engine.input_layer.Input", "tensorflow.python.keras.utils.generic_utils.CustomObjectScope", "tensorflow.python.keras.backend.placeholder", "tensorflow.python.keras.optimizers.TFOptimizer", "tensorflow.python.util.nest.map_structure", "tensorflow.python.util.nest.flatten", "tensorflow.python.keras.metrics.clone_metrics" ], [ "tensorflow.python.ops.math_ops.greater_equal", "tensorflow.python.data.ops.dataset_ops.Options", "tensorflow.python.ops.math_ops.mul", "tensorflow.python.platform.test.main", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.data.experimental.ops.optimization.assert_next", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.util.tf_export.keras_export" ], [ "tensorflow.lite.experimental.nn.TFLiteLSTMCell", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.nn.static_rnn", "tensorflow.lite.TFLiteConverter.from_session", "tensorflow.lite.experimental.nn.dynamic_rnn", "tensorflow.train.AdamOptimizer", "numpy.allclose", "numpy.reshape", "tensorflow.lite.Interpreter", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.python.platform.test.main", "tensorflow.train.Saver", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.matmul", "tensorflow.unstack", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.nn.softmax", "tensorflow.transpose", "tensorflow.compat.v1.Session", "tensorflow.random_normal" ], [ "tensorflow.python.platform.test.main", "tensorflow.python.ops.control_flow_util_v2.in_defun", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context", "tensorflow.python.eager.test.main", "tensorflow.python.distribute.strategy_combinations.set_virtual_cpus_to_at_least", "tensorflow.python.distribute.mirrored_function_strategy.MirroredFunctionStrategy", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.tools.docs.generate_lib.extract", "tensorflow.tools.docs.doc_generator_visitor.DocGeneratorVisitor", "tensorflow.python.platform.googletest.main" ], [ "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context" ], [ "tensorflow.python.eager.test.main", "tensorflow.python.training.training_util.get_or_create_global_step", "tensorflow.python.distribute.combinations.combine", "tensorflow.python.training.checkpoint_management.latest_checkpoint", "tensorflow.python.keras.layers.core.Dense", "tensorflow.python.training.adam.AdamOptimizer", "tensorflow.python.ops.random_ops.random_normal", "tensorflow.python.eager.backprop.GradientTape", "tensorflow.python.keras.optimizer_v2.adam.Adam", "tensorflow.python.training.tracking.util.add_variable", "tensorflow.python.training.tracking.util.Checkpoint", "tensorflow.python.distribute.tpu_strategy.TPUStrategy", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.framework.ops.Graph", "tensorflow.python.client.session.Session", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.zeros", "tensorflow.core.protobuf.config_pb2.OptimizerOptions", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.ops.gradients_impl.gradients" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13", "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13", "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "1.4", "1.13", "2.3", "2.4", "2.2", "2.9", "1.5", "1.7", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.10", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "2.5", "2.2", "2.10" ] }, { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "2.3", "2.4", "1.5", "1.7", "0.12", "1.0", "2.2", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13", "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.3", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] } ]
wenlianglaw/Tetris-in-Python
[ "d4f0a22c4827e7eeb44c55def3f024e0c6932ebe" ]
[ "game_client.py" ]
[ "# This file defines the back end of the Tetris game\n#\n# GameState is the base class of GameClient.\n#\n# GameClient.Run() will start two threads:\n# - _ProcessActions: Process the action list every x seconds\n# - _AutoDrop: Auto drops the current piece.\n#\n# GameClient:\n# - current piece\n# - held piece\n# - piece list\n# - color_map: game board\n# - InputActions(...): Inputs a list of actions.\n# - ProcessActions(...): Lets the game client process a list of actions\n# directly\n# - ProcessAction(...): Lets the game client process one actions directly\n# - PutPiece(...): Puts the current piece if the position is valid.\n# - GetState(...): Gets game state, useful to AI\n# - CheckValidity(...): Checks if a move is valid\n# - SpawnPiece(...): Sets the current piece.\n# - Restart(...): Restarts the game.\n# - Rotate(...): Alternatively, callers can directly call Rotate to rotate\n# current_piece\n# - Move(...): Alternatively, callers can directly call Move to move the\n# current_piece\n#\nimport copy\nimport queue\nimport threading\nimport time\nfrom threading import Lock\nfrom typing import Tuple, List\n\nimport numpy as np\n\nimport actions\nimport shape\n\n# Some global settings\nDEFAULT_LENGTH = 20\nDEFAULT_WIDTH = 10\nMAP_PADDING_SIZE = 4\n# When there are less than threshold pieces, spawn a new bag.\nREFILL_THRESHOLD = 5\n\n# Disable the auto drop in next few seconds\nMAXIMUM_LOCK_TIME = 4\nINCREMENTAL_LOCK_TIME = 1\n\n# Scores\nSINGLE = 5\nDOUBLE = 10\nTSS = 20\nTRIPLE = 40\nQUAD = 50\nTSD = 60\nTST = 80\nPC = 120\n\n# ATTACKS\nATTACK_DOUBLE = 1\nATTACK_TSS = 2\nATTACK_TRIPLE = 2\nATTACK_QUAD = 4\nATTACK_TSD = 4\nATTACK_TST = 6\nATTACK_PC = 10\n\n\nclass InternalError(Exception):\n \"\"\"Any internal errors.\"\"\"\n\n\nclass GameState:\n def __init__(self):\n self.height = 0\n self.width = 0\n self.color_map = np.array([])\n self.current_piece = None\n self.held_piece = None\n self.score = 0\n self.piece_list = []\n self.is_gameover = False\n self.can_swap = True\n self.accumulated_lines_eliminated = 0\n self.piece_dropped = 0\n self.blevel_increase = False\n self.level = 0\n self.line_sent = 0\n self.line_received = 0\n\n def __deepcopy__(self, memodict=None):\n if memodict is None:\n memodict = dict()\n another = copy.copy(self)\n another.color_map = self.color_map.copy()\n if self.current_piece is not None:\n another.current_piece = self.current_piece.copy()\n if self.held_piece is not None:\n another.held_piece = self.held_piece.copy()\n another.piece_list = copy.deepcopy(self.piece_list.copy())\n return another\n\n def copy(self):\n return self.__deepcopy__()\n\n def __str__(self):\n ret = \"\"\n ret += f\"\"\"height: {self.height}\nwidth: {self.width}\ncolor_map: {self.color_map}\ncurrent_piece: {self.current_piece}\nheld_piece: {self.held_piece}\nscore: {self.score}\npiece_list: {self.piece_list}\nis_gameover: {self.is_gameover}\ncan_swap: {self.can_swap}\npiece_dropped: {self.piece_dropped}\nlevel: {self.level}\n \"\"\"\n\n\nclass GameClient(GameState):\n def __init__(self, height: int = DEFAULT_LENGTH, width: int = DEFAULT_WIDTH, map_height_padding=MAP_PADDING_SIZE,\n map_side_padding=MAP_PADDING_SIZE):\n super().__init__()\n\n self.height = height\n self.width = width\n self.map_height_padding = map_height_padding\n self.map_side_padding = map_side_padding\n\n self.dtype = np.uint8\n self.dtype_length = 8\n if self.width + 2 * map_side_padding > 8:\n self.dtype = np.uint16\n self.dtype_length = 16\n if self.width + 2 * map_side_padding > 16:\n self.dtype = np.uint32\n self.dtype_length = 32\n if self.width + 2 * map_side_padding > 32:\n self.dtype = np.uint64\n self.dtype_length = 64\n if self.width + 2 * map_side_padding > 64:\n self.dtype = np.uint128\n self.dtype_length = 128\n if self.width + 2 * map_side_padding > 128:\n raise InternalError(\n \"width too long to support bit map. Consider chaning it to a smaller value.\")\n\n # Lock time settings\n # When the lock is enabled, count the lock time.\n # When the accumulated lock time is greater than the current maximum lock time,\n # force to perform the auto drop. Otherwise autodop is disabled for this turn.\n # When current locktime is reached but an refresh lock time request is genertaed.\n # increase the current maximum lock time by incremental lock time.\n self.maximum_lock_time = MAXIMUM_LOCK_TIME\n self.current_maximum_lock_time = 0\n self.incremental_lock_time = INCREMENTAL_LOCK_TIME\n self.accumulate_lock_time = 0\n # Only when move or rotate at bottom locks the auto drop\n self._enable_lock_time = False\n\n # Color map marks the color for each cell.\n self.color_map = np.array([[]], dtype=self.dtype)\n\n # Bit map for a better performance in some calculation.\n self.bit_map = np.array([], dtype=self.dtype)\n\n # Lock for current_piece\n self.mutex_current_piece = Lock()\n self.last_put_piece = None\n # List of actions to process\n self.action_list = queue.Queue()\n self._init_spawn_interval = 500 # 500 ms at level 0\n self._current_spawn_interval = 500\n # actions.Action\n self.last_action = None\n self.disable_autodrop = False\n self.line_tobesent = 0\n\n # Used when calculate the auto drop interval decrease based on current level.\n # Generated from the sigmoid function\n # x = np.linspace(0, 40, 40)\n # interval_decrease = 110 / (1 + np.exp(0.16 * x))\n # interval_decrease = np.cumsum(interval_decrease)\n # print(repr(np.cumsum(interval_decrease)))\n self.interval_decrease = np.array(\n [55., 100.49727968, 150.55179446, 190.28030383,\n 230.85041422, 260.47244367, 290.38990828, 320.86947489,\n 345.19115272, 350.63934095, 380.49515164, 400.03022699,\n 410.5020957, 420.15098155, 430.19789113, 440.8437644,\n 450.26946046, 455.63636342, 461.08741849, 465.74844074,\n 469.72957119, 473.12678557, 476.02338748, 478.4914391,\n 480.59310001, 482.38185737, 483.90364044, 485.19781892,\n 486.29808909, 487.23325451, 488.02790975, 488.70303602,\n 489.27651798, 489.76359062, 490.17722443, 490.52845671,\n 490.82667585, 491.07986489, 491.2948099, 491.47727802])\n\n self._RefillPieces()\n self._TakePieceFromList()\n self.accumulated_lines_eliminated = 0\n\n # When soft-dropping, temporarily disable auto-drop\n self.soft_drop = False\n self.piece_dropped = 0\n\n # Must be put after the initializations above\n self._InitMap()\n\n def _InitMap(self):\n side_padding = (1 << self.map_side_padding) - 1\n init_row = (side_padding << (self.map_side_padding + self.width)) | side_padding\n bottom_padding = (1 << (self.width + 2 * self.map_side_padding)) - 1\n self.bit_map = np.concatenate((\n np.array((self.map_height_padding + self.height) * [init_row], dtype=self.dtype),\n np.array(self.map_height_padding * [bottom_padding], dtype=self.dtype)), dtype=self.dtype)\n\n self.color_map = np.array([[0 for i in range(self.width)] for x in range(self.height + self.map_height_padding)],\n dtype=self.dtype)\n\n def Restart(self):\n self._InitMap()\n self.piece_list = []\n self.held_piece = None\n self.current_piece = None\n # Lock of the game state\n self.mutex_current_piece = Lock()\n self.is_gameover = False\n self.last_put_piece = None\n # List of actions to process\n self.action_list = queue.Queue()\n self._init_spawn_interval = 500.0\n self._current_spawn_interval = 500.0\n # actions.Action\n self.last_action = []\n self.can_swap = True\n self.score = 0\n self.accumulate_lock_time = 0\n self.accumulated_lines_eliminated = 0\n self.soft_drop = False\n self.piece_dropped = 0\n self.line_sent = 0\n self.line_received = 0\n self.line_tobesent = 0\n\n self._enable_lock_time = False\n\n self._RefillPieces()\n self._TakePieceFromList()\n\n def Run(self):\n auto_drop_th = threading.Thread(target=self.AutoDrop, name=\"auto_drop\", daemon=True)\n process_input_th = threading.Thread(target=self._ProcessActionsThread, daemon=True)\n if not self.disable_autodrop:\n auto_drop_th.start()\n process_input_th.start()\n\n if not self.disable_autodrop:\n auto_drop_th.join()\n process_input_th.join()\n print(\"game ends\")\n\n def GetState(self) -> GameState:\n \"\"\"Gets game state.\n Returns the objects ref instead of copy For better performance.\n \"\"\"\n return copy.deepcopy(super())\n\n def GetCell(self, i: int, j: int) -> int:\n \"\"\"Gets cell at [i,j].\n Notes: This function doesn't check the index out of boundary error.\n \"\"\"\n return self.color_map[i, j]\n\n def GetMap(self):\n \"\"\"Gets whole color_map.\"\"\"\n return self.color_map\n\n def GetMapArea(self, corner: Tuple[int, int],\n size: Tuple[int, int]) -> np.array:\n \"\"\"Gets an area of\n :param top_left:\n :param bottom_right:\n :return: The area of the color_map.\n \"\"\"\n size = (np.min([size[0], self.color_map.shape[0] - corner[0]]),\n np.min([size[1], self.color_map.shape[1] - corner[1]]))\n\n return self.color_map[corner[0]: corner[0] + size[0],\n corner[1]: corner[1] + size[1]]\n\n def SetMap(self, pos: Tuple[int, int], v: int, map: np.array = None):\n \"\"\"Sets the cell at [i,j] to value v.\"\"\"\n (i, j) = pos\n bit_map = self.bit_map.copy()\n if map is None or map is self.color_map:\n map = self.color_map\n bit_map = self.bit_map\n map[i, j] = v\n\n # Set a bit to value: Clear to bit to 0 and then set to value\n bit_v = 0 if v == 0 else 1\n bit_j_pos = self.width + self.map_side_padding - 1 - j\n bit_map[i] = (bit_map[i] & ~(1 << bit_j_pos)) | (bit_v << bit_j_pos)\n\n def SetWholeMap(self, map: np.array):\n if map.shape != self.color_map.shape:\n raise InternalError(\n f\"Map shape {map.shape}\"\n f\" must match the color_map shape: {self.color_map.shape}\")\n\n self.color_map = map\n\n # Convert the map to Bollean map\n bit_color_map = map != 0\n\n # Revert the order and padding, then call the packbits(..., order=\"little\") fn\n bit_color_map = bit_color_map[:, ::-1]\n bit_color_map = np.pad(\n bit_color_map,\n ((0, 0), (self.map_side_padding, self.map_side_padding)),\n \"constant\", constant_values=(1,))\n\n padding0_len = self.dtype_length - bit_color_map.shape[1]\n bit_color_map = np.pad(bit_color_map, ((0, 0), (0, padding0_len)),\n \"constant\", constant_values=(0,))\n\n int_color_map = np.packbits(bit_color_map, bitorder=\"little\").view(self.dtype)\n self.bit_map[0:self.map_height_padding + self.height] = int_color_map\n print(int_color_map)\n print(self.bit_map)\n\n def copy(self):\n another = copy.copy(self)\n another.last_action = copy.copy(self.last_action)\n if self.last_put_piece is not None:\n another.last_put_piece = self.last_put_piece.copy()\n another.color_map = np.copy(self.color_map)\n another.bit_map = np.copy(self.bit_map)\n another.action_list = copy.copy(self.action_list)\n another.piece_list = self.piece_list.copy()\n another.current_piece = self.current_piece.copy()\n if self.held_piece is None:\n another.held_piece = None\n else:\n another.held_piece = self.held_piece.copy()\n return another\n\n def AutoDrop(self):\n while True:\n if self.soft_drop:\n # If it is soft dropping, we don't perform auto drop.\n self.soft_drop = False\n else:\n if self.CheckValidity(self.current_piece, offset=(1, 0)):\n self.Move(actions.Action(down=True, source_user_or_ai=False))\n else:\n if (not self._enable_lock_time or\n self.accumulate_lock_time >= self.current_maximum_lock_time):\n self.PutPiece()\n else:\n self.accumulate_lock_time += self._current_spawn_interval / 1000\n\n time.sleep(self._current_spawn_interval / 1000)\n\n def InputActions(self, acts: List[actions.Action]):\n if self.is_gameover:\n return\n\n if len(acts) > 30:\n print(\"len:\", len(acts))\n acts = acts[-30:]\n\n for act in acts:\n if self.action_list.qsize() > 50:\n break\n self.action_list.put(act)\n\n def ProcessActions(self, actions: List[actions.Action], post_processing=True):\n for a in actions:\n self.ProcessAction(a, post_processing=post_processing)\n\n def ProcessAction(self, action: actions.Action, post_processing=True):\n if self.is_gameover:\n return\n # print(f\"Processed action: {action.direction}, {action.rotation}, {action.swap}\")\n # self.test += 1\n # print(self.test)\n if action.swap:\n self.Swap()\n self.Rotate(action.rotation)\n self.Move(action, post_processing=post_processing)\n\n def _ProcessActionsThread(self):\n while True:\n while not self.action_list.empty():\n act = self.action_list.get()\n self.ProcessAction(act)\n self.action_list.task_done()\n time.sleep(0.001)\n\n def SetLevel(self, level: int = 0):\n \"\"\"Let the front end set!\"\"\"\n self.level = level\n\n i = min(len(self.interval_decrease), self.level)\n self._current_spawn_interval = max(\n 10, self._init_spawn_interval - self.interval_decrease[i])\n\n def IncreaseLevel(self, inc: int = 1):\n \"\"\"Let the front end decide!\"\"\"\n self.level += inc\n self.SetLevel(self.level)\n\n def Move(self, action: actions.Action, post_processing=True) -> bool:\n \"\"\"Moves the current piece.\n :param direction: Direction to move\n :param post_processing: if True, put the piece to color_map and\n apply line eliminate. Otherwise just update the current_piece's states.\n :return True if moved; False otherwise\n \"\"\"\n if (action.direction == actions.NONE and\n not action.down):\n return False\n\n moved = False\n if action.down:\n try:\n self.mutex_current_piece.acquire()\n if self.CheckValidity(self.current_piece, (1, 0)):\n self.current_piece.x += 1\n moved = True\n self.soft_drop = True\n finally:\n self.mutex_current_piece.release()\n\n if action.direction == actions.LEFT:\n try:\n self.mutex_current_piece.acquire()\n if self.CheckValidity(self.current_piece, (0, -1)):\n self.current_piece.y += -1\n moved = True\n finally:\n self.mutex_current_piece.release()\n\n if action.direction == actions.RIGHT:\n try:\n self.mutex_current_piece.acquire()\n if self.CheckValidity(self.current_piece, (0, 1)):\n self.current_piece.y += 1\n moved = True\n finally:\n self.mutex_current_piece.release()\n if action.direction == actions.HARD_DROP or action.direction == actions.SOFT_DROP:\n try:\n self.mutex_current_piece.acquire()\n while self.CheckValidity(self.current_piece, (1, 0)):\n self.current_piece.x += 1\n moved = True\n finally:\n self.mutex_current_piece.release()\n if post_processing and action.direction == actions.HARD_DROP:\n self.PutPiece()\n\n if moved:\n self.last_action = action\n\n at_bottom = not self.CheckValidity(self.current_piece, (1, 0))\n if (at_bottom and action.direction != actions.HARD_DROP and\n action.source_user):\n self._RefreshLockTime()\n\n return moved\n\n def _RefreshLockTime(self):\n self._enable_lock_time = True\n if self.accumulate_lock_time >= self.current_maximum_lock_time:\n self.current_maximum_lock_time = min(\n self.current_maximum_lock_time + self.incremental_lock_time,\n self.maximum_lock_time)\n\n def _ResetLockTime(self):\n self._enable_lock_time = False\n self.accumulate_lock_time = 0\n self.current_maximum_lock_time = 0\n\n def Swap(self):\n \"\"\"Swaps the held piece and the current if its swappable\"\"\"\n if not self.can_swap:\n return\n\n try:\n self.mutex_current_piece.acquire()\n t = self.held_piece\n self.held_piece = self.current_piece\n self.current_piece = t\n\n if not self.current_piece:\n self._TakePieceFromList()\n\n self.current_piece.Init()\n self.held_piece.Init()\n self.can_swap = False\n finally:\n self.mutex_current_piece.release()\n\n def CheckGameOver(self):\n self.is_gameover = np.any(\n self.GetMapArea((0, 0), (self.map_height_padding, self.width)) != 0)\n\n return self.is_gameover\n\n def _AnalyzeElimination(self, n_eliminate: int) -> int:\n ret = 0\n is_last_put_t = isinstance(self.last_put_piece, shape.T)\n if n_eliminate == 1:\n if (is_last_put_t and self.last_action and self.last_action.rotation != 0):\n print(\"TSS\")\n ret += TSS\n self.line_tobesent += ATTACK_TSS\n else:\n ret += SINGLE\n\n if n_eliminate == 2:\n # TSD\n if (is_last_put_t and self.last_action and self.last_action.rotation != 0):\n print(\"TSD\")\n ret += TSD\n self.line_tobesent += ATTACK_TSD\n # Normal Double\n else:\n ret += DOUBLE\n self.line_tobesent += ATTACK_DOUBLE\n if n_eliminate == 3:\n # TST\n if (is_last_put_t and self.last_action and self.last_action.rotation != 0):\n print(\"TST\")\n ret += TST\n self.line_tobesent += ATTACK_TST\n else:\n ret += TRIPLE\n self.line_tobesent += ATTACK_TRIPLE\n\n if n_eliminate == 4:\n ret += QUAD\n self.line_tobesent += ATTACK_QUAD\n\n # Checks for PC\n if np.all(self.color_map == 0):\n print(\"PC\")\n ret += PC\n self.line_tobesent += ATTACK_PC\n\n return ret * (self.level + 3)\n\n def _LineClear(self):\n elimated_lines = []\n elimated_cnt = 0\n # Checks the 4 lines... This is not adapt to shape with higher than 4 lines\n # but that's not a part of this game. I don't have plan to support custom\n # shapes.\n for row in range(4):\n if not (self.last_put_piece.x + row >= 0 and\n self.last_put_piece.x + row < self.height + self.map_height_padding):\n continue\n if np.all(self.color_map[self.last_put_piece.x + row, :] != 0):\n elimated_lines.append(row + self.last_put_piece.x)\n elimated_cnt += 1\n\n self.color_map = np.vstack((np.zeros((elimated_cnt, self.width),\n dtype=self.dtype),\n np.delete(self.color_map, elimated_lines, axis=0)))\n\n # Updates the bit_map\n side_padding = (1 << self.map_side_padding) - 1\n init_row = (side_padding << (self.map_side_padding + self.width)) | side_padding\n self.bit_map = np.concatenate((elimated_cnt * [init_row],\n np.delete(self.bit_map, elimated_lines))).astype(self.dtype)\n\n self.accumulated_lines_eliminated += elimated_cnt\n self.score += self._AnalyzeElimination(n_eliminate=elimated_cnt)\n\n def _SendAttack(self):\n \"\"\"Send attack to target.\"\"\"\n # This feature has not been implemented yet.\n self.line_sent += self.line_tobesent\n self.line_tobesent = 0\n\n def PutPiece(self, piece: shape.Shape = None):\n \"\"\" Puts a piece to color_map if it is a valid placement then execute the post processing.\n\n :param piece: The piece to put, if None, put the self.current_piece\n :param color_map: The color_map where the piece puts, if None, self.color_map will be used.\n :returns: True if the piece has been put. False otherwise.\n \"\"\"\n if self._PrePutPiece(piece):\n self._PostPutPiece(piece)\n return True\n else:\n return False\n\n def _PrePutPiece(self, piece: shape.Shape = None, map: np.array = None):\n \"\"\" Puts a piece to color_map if it is a valid placement.\n Post put processing such as self._LineClear will not be executed\n\n :param piece: The piece to put, if None, put the self.current_piece\n :param map: The color_map where the piece puts, if None, self.color_map will be used.\n :returns: True if the piece has been put. False otherwise.\n \"\"\"\n try:\n if not piece:\n self.mutex_current_piece.acquire()\n piece = self.current_piece\n\n if map is None:\n map = self.color_map\n\n if not self.CheckValidity(piece):\n return False\n\n for (i, j) in piece.GetShape():\n self.SetMap((piece.x + i, piece.y + j), piece.id, map)\n return True\n finally:\n if self.mutex_current_piece.locked():\n self.mutex_current_piece.release()\n\n def _PostPutPiece(self, piece: shape.Shape = None):\n if piece is not None:\n self.last_put_piece = piece\n else:\n self.last_put_piece = self.current_piece\n\n # LineClear should be called prior to SendAttack\n self._LineClear()\n if piece is None:\n self._TakePieceFromList()\n\n self.CheckGameOver()\n self._ResetLockTime()\n self._SendAttack()\n self.can_swap = True\n self.piece_dropped += 1\n\n def TextDraw(self):\n preview_map = self.color_map.copy()\n self._PrePutPiece(self.current_piece, preview_map)\n for i in preview_map:\n print(i)\n print()\n\n def SpawnPiece(self, piece: shape.Shape = None) -> bool:\n if not piece:\n self._TakePieceFromList()\n else:\n self.current_piece = piece.copy()\n\n return self.CheckValidity(self.current_piece)\n\n def _FindFittedPiece(self, piece: shape.Shape = None, num_90rotations: int = 0):\n \"\"\"Finds a location that fits this piece with n 90rotations.\n Ref: https://tetris.fandom.com/wiki/SRS\n :param piece: The piece to be put in the color_map. If none, it will be set to the current_piece\n :param num_90rotations: How many 90 rotations\n :return: piece - shape.Shape: the piece with rotations that fits the color_map.\n \"\"\"\n if not piece:\n piece = self.current_piece\n\n def _IsJLSTZ(piece: shape.Shape):\n jlstz = [shape.J, shape.L, shape.S, shape.T, shape.Z]\n for s in jlstz:\n if isinstance(piece, s):\n return True\n return False\n\n # The 180 rotation wall kick table is copied from\n # https://tetris.fandom.com/wiki/SRS#180.C2.B0_rotation\n # which is origined from\n # https://github.com/JoshuaWebb/nullpomino/blob/master/src/mu/nu/nullpo/game/subsystem/wallkick/StandardWallkick.java\n offset_map_jlstz = [\n # state 0\n ([(0, 0), (0, -1), (-1, -1), (2, 0), (2, -1)], # 0>>1\n # 0>>2, 180 rotation\n # [(0,0), (1, 0), (2, 0), (1, 1), (2, 1), (-1, 0), (-2, 0), (-1, 1), (-2, 1), (0, -1), (3, 0), (-3, 0)],\n [(0, 0)],\n [(0, 0), (0, 1), (-1, 1), (2, 0), (2, 1)]), # 0>>3\n\n # state 1\n ([(0, 0), (0, 1), (1, 1), (-2, 0), (-2, 1)], # 1>>2\n # l>>3, 180 rotation\n # [(0,0), (0, 1), (0, 2), (-1, 1), (-1, 2), (0, -1), (0, -2), (-1, -1), (-1, -2), (1, 0), (0, 3), (0, -3)],\n [(0, 0)],\n [(0, 0), (0, 1), (1, 1), (-2, 0), (-2, 1)]), # 1>>0\n\n # state 2\n ([(0, 0), (0, 1), (-1, 1), (2, 0), (2, 1)], # 2>>3\n # [(0,0), (-1, 0), (-2, 0), (-1, -1), (-2, -1), (1, 0), (2, 0), (1, -1), (2, -1), (0, 1), (-3, 0), (3, 0)], # 2>>0,\n [(0, 0)],\n [(0, 0), (0, -1), (-1, -1), (2, 0), (2, -1)]), # 2>>1\n\n # state 3\n ([(0, 0), (0, -1), (1, -1), (2, 0), (-2, -1)], # 3>>0\n # 3>>1, 180 rotation\n # [(0,0), (0, 1), (0, 2), (1, 1), (1, 2), (0, -1), (0, -2), (1, -1), (1, -2), (-1, 0), (0, 3), (0, -3)],\n [(0, 0)],\n [(0, 0), (0, -1), (1, -1), (2, 0), (-2, -1)]), # 3>>2\n ]\n\n offset_map_i = [\n # state 0\n [[(0, 0), (0, -2), (0, 1), (1, -2), (-2, 1), ], # 0>>1\n # [(0,0), (-1, 0), (-2, 0), (1, 0), (2, 0), (0, 1)], # 0>>2, 180 rotation\n [(0, 0)],\n [(0, 0), (0, -1), (0, 2), (-2, -1), (1, 2)]], # 0>>3\n\n # state 1\n [[(0, 0), (0, -1), (0, 2), (-2, -1), (1, 2)], # 1>>2\n # [(0,0), (0, 1), (0, 2), (0, -1), (0, -2), (-1, 0)], # 1>>3, 180 rotation,\n [(0, 0)],\n [(0, 0), (0, 2), (0, -1), (-1, 2), (2, -1)]], # 1>>0\n\n # state 2\n [[(0, 0), (0, 2), (0, -1), (-1, 2), (2, -1)], # 2>>3\n # [(0, 0), (1, 0), (2, 0), (-1, 0), (-2, 0), (0, -1)], # 2>>0, 180 rotation\n [(0, 0)],\n [(0, 0), (0, 1), (0, -2), (2, 1), (-1, -2)]], # 2>>1\n\n # state 3\n [[(0, 0), (0, 1), (0, -2), (2, 1), (-1, -2)], # 3>>0\n # [(0, 0), (0, 1), (0, 2), (0, -1), (0, -2), (1, 0)], # 3>>1, 180 rotation\n [(0, 0)],\n [(0, 0), (0, -2), (0, 1), (1, -2), (2, 1)]], # 3>>2\n ]\n\n state = piece.state\n num_90rotations %= 4\n offset_piece = piece.copy()\n ori_x = offset_piece.x\n ori_y = offset_piece.y\n\n for _ in range(num_90rotations):\n offset_piece.Rotate90()\n\n if num_90rotations == 0:\n if self.CheckValidity(offset_piece):\n return offset_piece\n num_90rotations -= 1\n\n if _IsJLSTZ(piece):\n for (offset_x, offset_y) in offset_map_jlstz[state][num_90rotations]:\n offset_piece.x = ori_x + offset_x\n offset_piece.y = ori_y + offset_y\n if (offset_piece.y >= self.width or\n offset_piece.x >= self.height + self.map_height_padding):\n continue\n if self.CheckValidity(offset_piece):\n return offset_piece\n else:\n for (offset_x, offset_y) in offset_map_i[state][num_90rotations]:\n offset_piece.x = ori_x + offset_x\n offset_piece.y = ori_y + offset_y\n if (offset_piece.y >= self.width or\n offset_piece.x >= self.height + self.map_height_padding):\n continue\n if self.CheckValidity(offset_piece):\n return offset_piece\n\n return None\n\n def Rotate(self, n: int) -> bool:\n \"\"\"Rotates the current piece.\n :param n: rotations, in range [0,4)\n :return: True if the current piece can be rotated. False otherwise.\n \"\"\"\n n %= 4\n if n == 0:\n return False\n\n fitted_piece = self._FindFittedPiece(num_90rotations=n)\n if fitted_piece:\n self.current_piece = fitted_piece\n self.last_action = actions.Action(dir=0, rotation=n)\n\n if not self.CheckValidity(self.current_piece, (1, 0)):\n self._RefreshLockTime()\n\n return fitted_piece is not None\n\n def CheckValidity(self, piece: shape.Shape, offset: Tuple[int, int] = (0, 0)):\n \"\"\"Checks if the piece with offset can be put in the color_map\n :param piece: The piece to be put.\n :param offset: The inital offset to the piece\n :return: True if the current state can fit into the color_map. False otherwise.\n \"\"\"\n (ox, oy, os) = (piece.x, piece.y, piece.state)\n piece.x += offset[0]\n piece.y += offset[1]\n\n a = self.bit_map[piece.x: piece.x + 4]\n b = self.width - piece.y\n c = piece.GetBitMap().astype(self.dtype)\n d = c << b\n e = a & d\n check_rst = e == 0\n (piece.x, piece.y, piece.state) = (ox, oy, os)\n return np.all(check_rst)\n\n def _GetNextBag(self):\n start_y = int((self.width - 3) / 2)\n assert start_y >= 0\n\n bag = [shape.I(start_y=start_y),\n shape.J(start_y=start_y),\n shape.L(start_y=start_y),\n shape.O(start_y=start_y),\n shape.S(start_y=start_y),\n shape.T(start_y=start_y),\n shape.Z(start_y=start_y)]\n np.random.shuffle(bag)\n return bag\n\n def _RefillPieces(self):\n \"\"\"\n When there are less than REFILL_THRESHOLD pieces in the list,\n refill it with a new bag.\n \"\"\"\n if len(self.piece_list) <= REFILL_THRESHOLD:\n self.piece_list.extend(self._GetNextBag())\n\n def _TakePieceFromList(self):\n self._RefillPieces()\n self.current_piece = self.piece_list[0].copy()\n self.piece_list = self.piece_list[1:]\n\n\ndef CreateGameFromState(state: GameState) -> GameClient:\n game = GameClient(height=state.height, width=state.width)\n game.color_map = np.copy(state.color_map)\n game.current_piece = state.current_piece.copy()\n if state.held_piece is not None:\n game.held_piece = state.held_piece.copy()\n else:\n game.held_piece = None\n game.score = state.score\n game.piece_list = state.piece_list.copy()\n game.can_swap = state.can_swap\n game.is_gameover = state.is_gameover\n game.accumulated_lines_eliminated = state.accumulated_lines_eliminated\n game.piece_dropped = state.piece_dropped\n game.line_sent = state.line_sent\n game.line_received = state.line_received\n return game\n" ]
[ [ "numpy.pad", "numpy.min", "numpy.random.shuffle", "numpy.all", "numpy.copy", "numpy.delete", "numpy.packbits", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ZackPashkin/pytorch
[ "5b1f5c8f17ec4067dc9f9df98bbcc6757ab24444" ]
[ "test/test_binary_ufuncs.py" ]
[ "import torch\nimport numpy as np\n\nimport itertools\nfrom itertools import product\nimport math\nimport random\nimport unittest\nimport warnings\nimport operator\nfrom functools import partial\n\nfrom torch._six import inf, nan\nfrom torch.testing._internal.common_utils import (\n TestCase, iter_indices, TEST_WITH_ASAN, run_tests,\n torch_to_numpy_dtype_dict, make_tensor, TEST_SCIPY, set_default_dtype)\nfrom torch.testing._internal.common_device_type import (\n instantiate_device_type_tests, onlyCUDA, onlyCPU, dtypes, dtypesIfCUDA,\n dtypesIfCPU, deviceCountAtLeast, precisionOverride, onlyOnCPUAndCUDA,\n skipCUDAIfRocm, skipIf)\nfrom torch.testing import all_types_and_complex_and\n\nif TEST_SCIPY:\n import scipy.special\n\n# TODO: remove this\ndef _generate_input(shape, dtype, device, with_extremal):\n if shape == ():\n x = torch.tensor((), dtype=dtype, device=device)\n else:\n if dtype.is_floating_point or dtype.is_complex:\n # work around torch.randn not being implemented for bfloat16\n if dtype == torch.bfloat16:\n x = torch.randn(*shape, device=device) * random.randint(30, 100)\n x = x.to(torch.bfloat16)\n else:\n x = torch.randn(*shape, dtype=dtype, device=device) * random.randint(30, 100)\n x[torch.randn(*shape) > 0.5] = 0\n if with_extremal and dtype.is_floating_point:\n # Use extremal values\n x[torch.randn(*shape) > 0.5] = float('nan')\n x[torch.randn(*shape) > 0.5] = float('inf')\n x[torch.randn(*shape) > 0.5] = float('-inf')\n elif with_extremal and dtype.is_complex:\n x[torch.randn(*shape) > 0.5] = complex('nan')\n x[torch.randn(*shape) > 0.5] = complex('inf')\n x[torch.randn(*shape) > 0.5] = complex('-inf')\n elif dtype == torch.bool:\n x = torch.zeros(shape, dtype=dtype, device=device)\n x[torch.randn(*shape) > 0.5] = True\n else:\n x = torch.randint(15, 100, shape, dtype=dtype, device=device)\n\n return x\n\n# TODO: refactor this out\n# Converts half/bfloat16 dtype to float when device is cpu\ndef _convert_t(dtype, device):\n if device == 'cpu' and dtype in {torch.half, torch.bfloat16}:\n return torch.float\n return dtype\n\n# TODO: revise the tests to use make_tensor in common_utils.py instead\n# Returns a tensor of the requested shape, dtype, and device\n# Requesting a half CPU tensor returns a float CPU tensor with\n# values representable by a half.\n# Initialization uses randint for non-float types and randn for float types.\ndef _make_tensor(shape, dtype, device, fill_ones=False) -> torch.Tensor:\n # Returns a tensor filled with ones\n if fill_ones:\n return torch.ones(*shape, dtype=_convert_t(dtype, device), device=device)\n\n # Returns a tensor with random integer values\n if not (dtype.is_floating_point or dtype.is_complex):\n t = torch.randint(0, 10, shape, device=device)\n if dtype != torch.uint8:\n t = t - 5 # generate negative values also\n return t.to(_convert_t(dtype, device))\n\n # Populates the CPU tensor with floats representable as half/bfloat16\n if dtype == torch.half and device == 'cpu':\n return torch.randn(*shape, dtype=torch.float, device=device).half().float()\n if dtype == torch.bfloat16 and device == 'cpu':\n return torch.randn(*shape, dtype=torch.float, device=device).bfloat16().float()\n\n # Default: returns a tensor with random float values\n return torch.randn(shape, dtype=dtype, device=device).to(dtype=dtype)\n\n# TODO: update to use opinfos consistently\nclass TestBinaryUfuncs(TestCase):\n\n def test_add_broadcast_empty(self, device):\n # empty + empty\n self.assertRaises(RuntimeError, lambda: torch.randn(5, 0, device=device) + torch.randn(0, 5, device=device))\n self.assertEqual(torch.randn(5, 0, device=device), torch.randn(0, device=device) + torch.randn(5, 0, device=device))\n self.assertEqual(torch.randn(5, 0, 0, device=device), torch.randn(0, device=device) + torch.randn(5, 0, 1, device=device))\n\n # scalar + empty\n self.assertEqual(torch.randn(5, 0, 6, device=device), torch.randn((), device=device) + torch.randn(5, 0, 6, device=device))\n\n # non-empty, empty\n self.assertEqual(torch.randn(0, device=device), torch.randn(0, device=device) + torch.randn(1, device=device))\n self.assertEqual(torch.randn(0, 7, 0, 6, 5, 0, 7, device=device),\n torch.randn(0, 7, 0, 6, 5, 0, 1, device=device) + torch.randn(1, 1, 5, 1, 7, device=device))\n self.assertRaises(RuntimeError, lambda: torch.randn(7, 0, device=device) + torch.randn(2, 1, device=device))\n\n def test_addcmul_scalars_as_floats(self, device):\n # zero-dim variables that don't require grad should bind to scalar arguments\n x = torch.tensor(2.)\n y = torch.tensor(3., device=device)\n # 3 + (3 * 3) * 2\n self.assertEqual(y.addcmul(y, y, value=x), 21)\n\n x = torch.tensor(2., requires_grad=True)\n self.assertRaises(Exception, lambda: y.addcmul(y, y, value=x))\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_comparison_ops(self, device):\n x = torch.randn(5, 5)\n y = torch.randn(5, 5)\n\n eq = x == y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] == y[idx], eq[idx] == 1)\n\n ne = x != y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] != y[idx], ne[idx] == 1)\n\n lt = x < y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] < y[idx], lt[idx] == 1)\n\n le = x <= y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] <= y[idx], le[idx] == 1)\n\n gt = x > y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] > y[idx], gt[idx] == 1)\n\n ge = x >= y\n for idx in iter_indices(x):\n self.assertEqual(x[idx] >= y[idx], ge[idx] == 1)\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_comparison_ops_must_take_bool_output(self, device):\n for op in [torch.lt, torch.le, torch.gt, torch.ge, torch.eq, torch.ne,\n torch.logical_and, torch.logical_or, torch.logical_xor]:\n self.assertEqual(op(torch.tensor([True]), torch.tensor([False])).dtype, torch.bool)\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_inplace_comparison_ops_require_inputs_have_same_dtype(self, device):\n with self.assertRaisesRegex(RuntimeError, 'Expected object of scalar type'):\n for op in ['lt_', 'le_', 'gt_', 'ge_', 'eq_', 'ne_', 'logical_xor_', 'logical_and_', 'logical_or_']:\n x = torch.tensor([1], dtype=torch.int)\n y = torch.tensor([2], dtype=torch.long)\n in_place_method = getattr(x, op)\n in_place_method(y)\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_comparison_ops_check_for_scalar_overflow(self, device):\n s = 1 << 20\n t = torch.tensor([1 << 5], dtype=torch.uint8)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t < s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s < t)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t <= s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s <= t)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t > s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s > t)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t >= s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s >= t)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t == s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s == t)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t != s)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(s != t)\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_comparison_ops_check_for_zerodim_tensor_overflow(self, device):\n t1 = torch.tensor([1 << 5], dtype=torch.uint8)\n t2 = torch.tensor([1 << 30], dtype=torch.int32)\n ts1 = torch.tensor(1 << 20, dtype=torch.int32)\n ts2 = torch.tensor(1 << 40, dtype=torch.int64)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 < ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 < t2)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 <= ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 <= t2)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 > ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 > t2)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 >= ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 >= t2)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 == ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 == t2)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(t1 != ts1)\n with self.assertRaisesRegex(RuntimeError, 'value cannot be converted to type'):\n self.assertTrue(ts2 != t2)\n\n # TODO: update to work on CUDA, too\n @onlyCPU\n def test_bitwise_ops(self, device):\n x = torch.randn(5, 5).gt(0)\n y = torch.randn(5, 5).gt(0)\n\n and_result = x & y\n for idx in iter_indices(x):\n if and_result[idx]:\n self.assertTrue(x[idx] and y[idx])\n else:\n self.assertFalse(x[idx] and y[idx])\n\n or_result = x | y\n for idx in iter_indices(x):\n if or_result[idx]:\n self.assertTrue(x[idx] or y[idx])\n else:\n self.assertFalse(x[idx] or y[idx])\n\n xor_result = x ^ y\n for idx in iter_indices(x):\n if xor_result[idx]:\n self.assertTrue(x[idx] ^ y[idx])\n else:\n self.assertFalse(x[idx] ^ y[idx])\n\n x_clone = x.clone()\n x_clone &= y\n self.assertEqual(x_clone, and_result)\n\n x_clone = x.clone()\n x_clone |= y\n self.assertEqual(x_clone, or_result)\n\n x_clone = x.clone()\n x_clone ^= y\n self.assertEqual(x_clone, xor_result)\n\n def test_inplace_division(self, device):\n t = torch.rand(5, 5, device=device)\n id_before = id(t)\n t /= 2\n id_after = id(t)\n self.assertEqual(id_before, id_after)\n\n @dtypes(*torch.testing.get_all_dtypes(include_bool=False, include_complex=False))\n def test_div_rounding_modes(self, device, dtype):\n if dtype.is_floating_point:\n low, high = -10.0, 10.0\n else:\n info = torch.iinfo(dtype)\n low, high = info.min, info.max\n\n a = make_tensor((100,), device, dtype, low=low, high=high)\n b = make_tensor((100,), device, dtype, low=low, high=high)\n\n # Avoid division by zero so we can test (a / b) * b == a\n if dtype.is_floating_point:\n eps = 0.1\n b[(-eps < b) & (b < eps)] = eps\n else:\n b[b == 0] = 1\n\n if not dtype.is_floating_point:\n # floor(a / b) * b can be < a, so fixup slightly to avoid underflow\n a = torch.where(a < 0, a + b, a)\n\n d_true = torch.divide(a, b, rounding_mode=None)\n self.assertTrue(d_true.is_floating_point())\n self.assertEqual(d_true * b, a.to(d_true.dtype))\n\n d_floor = torch.divide(a, b, rounding_mode='floor')\n if dtype not in (torch.bfloat16, torch.half):\n self.assertEqual(d_floor * b + torch.remainder(a, b), a)\n else:\n self.assertEqual(d_floor * b + torch.remainder(a.float(), b.float()), a,\n exact_dtype=False)\n\n d_trunc = torch.divide(a, b, rounding_mode='trunc')\n rounding_unsupported = (\n dtype == torch.half and device != 'cuda' or\n dtype == torch.bfloat16 and device != 'cpu')\n d_ref = d_true.float() if rounding_unsupported else d_true\n self.assertEqual(d_trunc, d_ref.trunc().to(dtype))\n\n @dtypes(torch.bfloat16, torch.half, torch.float32, torch.float64)\n def test_div_rounding_nonfinite(self, device, dtype):\n\n # Compare division of special floating point values against NumPy\n num = torch.tensor([1.0, -1.0, 0, 0.1, -0.1, np.pi, -np.pi, np.inf, -np.inf, np.nan],\n dtype=dtype)\n # Divide by zero is tested seperately\n denom = num[num != 0]\n\n a, b = num[None, :].clone(), denom[:, None].clone()\n\n # Compare bfloat16 against NumPy float\n exact_dtype = dtype != torch.bfloat16\n if exact_dtype:\n an, bn = a.cpu().numpy(), b.cpu().numpy()\n else:\n an, bn = a.float().cpu().numpy(), b.float().cpu().numpy()\n\n for mode, np_ref in ((None, np.true_divide), (\"floor\", np.floor_divide)):\n with np.errstate(all='ignore'):\n expect = np_ref(an, bn)\n kwargs = dict(rounding_mode=mode) if mode is not None else {}\n with set_default_dtype(torch.double):\n actual = torch.divide(a, b, **kwargs)\n self.assertEqual(actual, torch.from_numpy(expect),\n exact_device=False, exact_dtype=exact_dtype)\n\n # Compare contiguous (likely vectorized) against non-contiguous (not vectorized)\n a_noncontig = torch.empty([2 * i for i in a.shape], dtype=dtype, device=device)[::2, ::2]\n a_noncontig[:] = a\n b_noncontig = torch.empty([2 * i for i in b.shape], dtype=dtype, device=device)[::2, ::2]\n b_noncontig[:] = b\n\n for rounding_mode in (None, \"trunc\", \"floor\"):\n expect = torch.divide(a_noncontig, b_noncontig, rounding_mode=rounding_mode)\n actual = torch.divide(a, b, rounding_mode=rounding_mode)\n self.assertEqual(actual, expect)\n\n @dtypes(torch.bfloat16, torch.half, torch.float32, torch.float64)\n def test_divide_by_zero_rounding(self, device, dtype):\n a = torch.tensor([1.0, -1.0, 0, 0.1, -0.1, np.pi, -np.pi, np.inf, -np.inf, np.nan],\n dtype=dtype)\n exact_dtype = (dtype != torch.bfloat16)\n if exact_dtype:\n an = a.cpu().numpy()\n else:\n an = a.float().cpu().numpy()\n\n zero = torch.zeros_like(a)\n\n # NOTE: NumPy's floor_divide rounding changed in 1.20.0 to be consistent with divide\n expect = np.divide(an, 0)\n for rounding_mode in (None, 'floor'):\n # CPU scalar\n actual = torch.divide(a, 0, rounding_mode=rounding_mode)\n self.assertEqual(actual, expect, exact_dtype=exact_dtype)\n # Device tensor\n actual = torch.divide(a, zero, rounding_mode=rounding_mode)\n self.assertEqual(actual, expect, exact_dtype=exact_dtype)\n\n @dtypes(*torch.testing.get_all_dtypes(\n include_bool=False, include_complex=False, include_bfloat16=False))\n def test_div_rounding_numpy(self, device, dtype):\n info = (torch.finfo(dtype) if dtype.is_floating_point\n else torch.iinfo(dtype))\n low, high = info.min, info.max\n\n # Compare division of random values against NumPy\n a = make_tensor((4096,), device, dtype, low=low, high=high)\n b = make_tensor((4096,), device, dtype, low=low, high=high)\n\n # Avoid division by zero which raises for integers and, for floats,\n # NumPy 1.20 changed floor_divide to follow IEEE rules for inf/nan\n # after dividing by zero.\n b[b == 0] = 1\n\n # Compare bfloat16 against NumPy float\n exact_dtype = dtype != torch.bfloat16\n\n if exact_dtype:\n an, bn = a.cpu().numpy(), b.cpu().numpy()\n else:\n an, bn = a.float().cpu().numpy(), b.float().cpu().numpy()\n\n for mode, np_ref in (\n (None, np.true_divide),\n (\"floor\", np.floor_divide),\n (\"trunc\", lambda a, b: np.trunc(np.true_divide(a, b)).astype(a.dtype))\n ):\n with np.errstate(all='ignore'):\n expect = torch.from_numpy(np_ref(an, bn))\n\n kwargs = dict(rounding_mode=mode) if mode is not None else {}\n # Contiguous (likely vectorized)\n with set_default_dtype(torch.double):\n actual = torch.divide(a, b, **kwargs)\n self.assertEqual(actual, expect, exact_device=False, exact_dtype=exact_dtype)\n\n # Non-contiguous (not vectorized)\n expect = expect[::2]\n with set_default_dtype(torch.double):\n actual = torch.divide(a[::2], b[::2], **kwargs)\n\n self.assertEqual(actual, expect, exact_device=False, exact_dtype=exact_dtype)\n\n # Tests that trying to add, inplace, a CUDA tensor to a CPU tensor\n # throws the correct error message\n @onlyCUDA\n def test_cross_device_inplace_error_msg(self, device):\n a = torch.tensor(2.)\n b = torch.tensor(2., device=device)\n with self.assertRaisesRegex(RuntimeError,\n \"Expected all tensors to be on the same device\"):\n a += b\n\n # TODO: refactor this test into a more generic one, it's parked here currently\n @onlyOnCPUAndCUDA\n def test_out_resize_warning(self, device):\n a = torch.tensor((1, 2, 3), device=device, dtype=torch.float32)\n b = torch.tensor((4, 5, 6), device=device, dtype=torch.float32)\n\n unary_inputs = (a,)\n binary_inputs = (a, b)\n unary_ops = (torch.ceil, torch.exp)\n binary_ops = (torch.add, torch.sub)\n for op in (unary_ops + binary_ops):\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n inputs = unary_inputs if op in unary_ops else binary_inputs\n\n # No warnings\n op(*inputs, out=torch.empty(3, device=device))\n op(*inputs, out=torch.empty(0, device=device))\n self.assertEqual(len(w), 0)\n\n # Cases that throw warnings\n op(*inputs, out=torch.empty(2, device=device))\n self.assertEqual(len(w), 1)\n\n # Verifies that the inplace dunders (like idiv) actually are in place\n @onlyOnCPUAndCUDA\n def test_inplace_dunders(self, device):\n t = torch.randn((1,), device=device)\n expected = t.data_ptr()\n t += 1\n t -= 1\n t *= 1\n t /= 1\n with self.assertWarnsOnceRegex(UserWarning, 'floor_divide'):\n t //= 1\n t %= 1\n self.assertEqual(expected, t.data_ptr())\n\n def check_internal_mem_overlap(self, inplace_op, num_inputs,\n dtype, device,\n expected_failure=False):\n if isinstance(inplace_op, str):\n inplace_op = getattr(torch.Tensor, inplace_op)\n input = torch.randn(1, dtype=dtype, device=device).expand(3, 3)\n inputs = [input] + [torch.randn_like(input)\n for i in range(num_inputs - 1)]\n if not expected_failure:\n with self.assertRaisesRegex(RuntimeError, 'single memory location'):\n inplace_op(*inputs)\n else:\n with self.assertRaises(AssertionError):\n with self.assertRaisesRegex(RuntimeError, 'single memory location'):\n inplace_op(*inputs)\n\n def unary_check_input_output_mem_overlap(self, data, sz, op,\n expected_failure=False):\n\n def _test(op, output, input):\n output_exp = torch.empty_like(output)\n op(input, out=output_exp)\n self.assertEqual(op(input, out=output), output_exp, msg=op.__name__)\n\n # output is identical to input:\n _test(op, output=data[0:sz], input=data[0:sz])\n # output and input are independent:\n _test(op, output=data[0:sz], input=data[sz:2 * sz])\n # output partially overlaps with input:\n if not expected_failure:\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, data[0:sz], data[1:sz + 1])\n else:\n with self.assertRaises(AssertionError):\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, data[0:sz], data[1:sz + 1])\n\n def binary_check_input_output_mem_overlap(self, op, device,\n expected_failure=False):\n sz = 3\n data = torch.randn(2 * sz, device=device)\n other = torch.randn(sz, device=device)\n\n self.unary_check_input_output_mem_overlap(\n data, sz, lambda input, out: op(other, input, out=out),\n expected_failure=expected_failure)\n\n self.unary_check_input_output_mem_overlap(\n data, sz, lambda input, out: op(input, other, out=out),\n expected_failure=expected_failure)\n\n @dtypes(torch.double)\n def test_binary_op_mem_overlap(self, device, dtype):\n ops = [\n (\"add\", True, True, 'cpu'),\n (\"add\", True, True, 'cuda'),\n (\"mul\", True, True, 'cpu'),\n (\"mul\", True, True, 'cuda'),\n (\"sub\", True, True, 'cpu'),\n (\"sub\", True, True, 'cuda'),\n (\"div\", True, True, 'cpu'),\n (\"div\", True, True, 'cuda'),\n (\"pow\", True, True, 'cpu'),\n (\"pow\", True, True, 'cuda'),\n (\"fmod\", True, True, 'cpu'),\n (\"fmod\", True, True, 'cuda'),\n (\"atan2\", True, True, 'cpu'),\n (\"atan2\", True, True, 'cuda'),\n (\"hypot\", True, True, 'cpu'),\n (\"hypot\", True, True, 'cuda'),\n (\"igamma\", True, True, 'cpu'),\n (\"igamma\", True, True, 'cuda'),\n (\"igammac\", True, True, 'cpu'),\n (\"igammac\", True, True, 'cuda'),\n (\"nextafter\", True, True, 'cpu'),\n (\"nextafter\", True, True, 'cuda'),\n (\"le\", True, True, 'cpu'),\n (\"le\", True, True, 'cuda'),\n (\"lt\", True, True, 'cpu'),\n (\"lt\", True, True, 'cuda'),\n (\"ge\", True, True, 'cpu'),\n (\"ge\", True, True, 'cuda'),\n (\"gt\", True, True, 'cpu'),\n (\"gt\", True, True, 'cuda'),\n (\"eq\", True, True, 'cpu'),\n (\"eq\", True, True, 'cuda'),\n (\"ne\", True, True, 'cpu'),\n (\"ne\", True, True, 'cuda'),\n (\"logical_and\", True, True, 'cpu'),\n (\"logical_and\", True, True, 'cuda'),\n (\"logical_or\", True, True, 'cpu'),\n (\"logical_or\", True, True, 'cuda'),\n (\"logical_xor\", True, True, 'cpu'),\n (\"logical_xor\", True, True, 'cuda'),\n ]\n\n for (fn, has_input_output_mem_overlap_check,\n has_internal_mem_overlap_check, dev) in ops:\n if dev != device:\n continue\n out_op = getattr(torch, fn)\n inplace_op = getattr(torch.Tensor, fn + '_')\n self.check_internal_mem_overlap(\n inplace_op, 2, dtype, device,\n expected_failure=not has_internal_mem_overlap_check)\n\n self.binary_check_input_output_mem_overlap(out_op, device,\n expected_failure=not has_input_output_mem_overlap_check)\n\n def _do_pow_for_exponents(self, m1, exponents, pow_fn, atol):\n for num in exponents:\n if isinstance(num, int) and num < 0 and not m1.is_floating_point() and not m1.is_complex():\n with self.assertRaisesRegex(RuntimeError,\n r'Integers to negative integer powers are not allowed\\.'):\n torch.pow(m1[4], num)\n else:\n # base - tensor, exponent - number\n # contiguous\n res1 = torch.pow(m1[4], num)\n res2 = res1.clone().zero_()\n # `math.pow` has issues with complex exponentiation so we need to resort to normal `pow`.\n for i in range(res2.size(0)):\n res2[i] = pow_fn(m1[4][i], num)\n rtol = 0 if atol is not None else None\n self.assertEqual(res1, res2, atol=atol, rtol=rtol)\n\n # non-contiguous\n res1 = torch.pow(m1[:, 4], num)\n res2 = res1.clone().zero_()\n for i in range(res2.size(0)):\n res2[i] = pow_fn(m1[i, 4], num)\n self.assertEqual(res1, res2, atol=atol, rtol=rtol)\n\n # scalar ** tensor to enforce correct handling of dtypes for __rpow__().\n expected_dtype = torch.result_type(num, m1)\n res1 = num ** m1[4]\n res2 = torch.tensor(num, dtype=expected_dtype, device=m1.device) ** m1[4]\n self.assertEqual(res1, res2)\n self.assertEqual(res1.dtype, expected_dtype)\n\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_pow(self, device, dtype):\n m1 = torch.empty(0, dtype=dtype, device=device)\n if m1.is_floating_point() or m1.is_complex():\n m1 = make_tensor((100, 100), low=0, high=1, dtype=dtype, device=device) + 0.5\n else:\n # math.pow will overflow and throw exceptions for large integers\n range_high = 4 if dtype in (torch.int8, torch.uint8) else 10\n m1 = make_tensor((100, 100), low=1, high=range_high, dtype=dtype, device=device)\n\n exponents = [-2.8, -2, -1, -0.5, 0, 0.5, 1, 2, 3, 4, 3.3]\n complex_exponents = [-2.5j, -1.0j, 0j, 1.0j, 2.5j, 1.0 + 1.0j, -1.0 - 1.5j, 3.3j]\n if m1.is_complex():\n self._do_pow_for_exponents(m1, exponents + complex_exponents, pow, 10e-4)\n else:\n self._do_pow_for_exponents(m1, exponents, math.pow, None)\n self._do_pow_for_exponents(m1, complex_exponents, pow, 10e-4)\n\n # base - number, exponent - tensor\n # contiguous\n res1 = torch.pow(3, m1[4])\n res2 = res1.clone().zero_()\n for i in range(res2.size(0)):\n res2[i] = pow(3, m1[4, i])\n self.assertEqual(res1, res2)\n\n # non-contiguous\n res1 = torch.pow(3, m1[:, 4])\n res2 = res1.clone().zero_()\n for i in range(res2.size(0)):\n res2[i] = pow(3, m1[i][4])\n self.assertEqual(res1, res2)\n\n # TODO: refactor all these tests using opinfos properly\n def _test_pow(self, base, exponent, np_exponent=None):\n if np_exponent is None:\n np_exponent = exponent\n\n def to_np(value):\n if isinstance(value, torch.Tensor):\n return value.cpu().numpy()\n return value\n\n try:\n np_res = np.power(to_np(base), to_np(np_exponent))\n expected = torch.from_numpy(np_res) if isinstance(np_res, np.ndarray) else torch.tensor(np_res, dtype=base.dtype)\n except ValueError as e:\n err_msg = \"Integers to negative integer powers are not allowed.\"\n self.assertEqual(str(e), err_msg)\n out = torch.empty_like(base)\n test_cases = [\n lambda: base.pow(exponent),\n lambda: base.pow_(exponent),\n lambda: torch.pow(base, exponent),\n lambda: torch.pow(base, exponent, out=out)\n ]\n for test_case in test_cases:\n self.assertRaisesRegex(RuntimeError, err_msg, test_case)\n else:\n if isinstance(base, torch.Tensor):\n actual = base.pow(exponent)\n self.assertEqual(actual, expected.to(actual))\n actual = base.clone()\n # When base is a 0-dim cpu tensor and exp is a cuda tensor, we exp `pow` to work but `pow_` to fail, since\n # `pow` will try to create the output tensor on a cuda device, but `pow_` needs to use the cpu tensor as the output\n if (isinstance(exponent, torch.Tensor) and base.dim() == 0 and base.device.type == 'cpu' and\n exponent.device.type == 'cuda'):\n regex = 'Expected all tensors to be on the same device, but found at least two devices, cuda.* and cpu!'\n self.assertRaisesRegex(RuntimeError, regex, base.pow_, exponent)\n elif torch.can_cast(torch.result_type(base, exponent), base.dtype):\n actual2 = actual.pow_(exponent)\n self.assertEqual(actual, expected)\n self.assertEqual(actual2, expected)\n else:\n self.assertRaisesRegex(RuntimeError, \"Found dtype \\\\w+ but expected \\\\w+\", lambda: actual.pow_(exponent))\n\n actual = torch.pow(base, exponent)\n self.assertEqual(actual, expected.to(actual))\n\n actual2 = torch.pow(base, exponent, out=actual)\n self.assertEqual(actual, expected.to(actual))\n self.assertEqual(actual2, expected.to(actual))\n\n # Tests pow() for integral, floating-type tensors, with integral, floating-type\n # exponents (tensor or scalar), respectively. noncontiguous tensors are also tested.\n def test_int_and_float_pow(self, device):\n\n def _test_int_and_float_pow(dt, low, high, dev):\n test_cases = (\n ((4, 4), 0, (4, 1)),\n ((3, 1), 4, (3, 1)),\n ((2,), 4, (1,)),\n ((1,), 2, ()),\n ((513, 513), 4, (513,)),\n ((5, 5, 5), 5, (5,)),\n ((), 2, ()),\n )\n for base_shape, exp_scalar, exp_shape in test_cases:\n base_tensor = make_tensor(base_shape, dtype=dt, device=dev, low=low, high=high)\n # int tensors don't take negative exponents\n if dt in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:\n exp_tensor = make_tensor(exp_shape, dtype=dt, device=dev, low=0, high=high)\n else:\n exp_tensor = make_tensor(exp_shape, dtype=dt, device=dev, low=low, high=high)\n self._test_pow(base_tensor, exp_scalar)\n self._test_pow(base_tensor, exp_tensor)\n # test non-contiguous tensors as well\n base_tensor = make_tensor(base_shape, dtype=dt, device=dev, low=low, high=high,\n noncontiguous=True)\n if dt in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:\n exp_tensor = make_tensor(exp_shape, dtype=dt, device=dev, low=0, high=high,\n noncontiguous=True)\n else:\n exp_tensor = make_tensor(exp_shape, dtype=dt, device=dev, low=low, high=high,\n noncontiguous=True)\n self._test_pow(base_tensor, exp_scalar)\n self._test_pow(base_tensor, exp_tensor)\n\n _test_int_and_float_pow(torch.int8, -2, 2, device)\n _test_int_and_float_pow(torch.uint8, 0, 3, device)\n _test_int_and_float_pow(torch.int16, -5, 5, device)\n _test_int_and_float_pow(torch.int64, -10, 10, device)\n _test_int_and_float_pow(torch.int32, -10, 10, device)\n _test_int_and_float_pow(torch.float16, 0., 5., device)\n _test_int_and_float_pow(torch.float32, 0., 10., device)\n _test_int_and_float_pow(torch.float64, 0., 10., device)\n # pow's output would have some NaNs as well\n _test_int_and_float_pow(torch.float32, -10., 10., device)\n _test_int_and_float_pow(torch.float64, -10., 10., device)\n\n # Tests that a Runtime error occurs when a base tensor cannot be resized\n # by pow's inplace variant due to PyTorch's broadcasting semantics.\n def test_pow_inplace_resizing_exception(self, device):\n test_cases = (\n ((), (3,)),\n ((2,), (2, 1)),\n ((2, 1), (2, 2)),\n ((2, 2), (2, 1, 1)),\n )\n test_inputs = list((make_tensor(base_size, dtype=torch.float64, device=device,\n high=10., low=0.),\n make_tensor(exp_size, dtype=torch.float64, device=device,\n high=10., low=0.))\n for base_size, exp_size in test_cases)\n for base, exponent in test_inputs:\n regex = \"doesn't match the broadcast shape\"\n self.assertRaisesRegex(RuntimeError, regex, base.pow_, exponent)\n\n def test_int_tensor_pow_neg_ints(self, device):\n ints = [torch.iinfo(torch.int32).min,\n -3, -2, -1, 0, 1, 2, 3,\n torch.iinfo(torch.int32).max]\n neg_ints = [torch.iinfo(torch.int32).min, -3, -2, -1]\n tensor = torch.tensor(ints, dtype=torch.int32, device=device)\n for pow in neg_ints:\n self._test_pow(tensor, pow)\n\n def test_long_tensor_pow_floats(self, device):\n ints = [0, 1, 23, 4567]\n floats = [0.0, 1 / 3, 1 / 2, 1.0, 3 / 2, 2.0]\n tensor = torch.tensor(ints, dtype=torch.int64, device=device)\n for pow in floats:\n self._test_pow(tensor, pow)\n\n @dtypes(*[torch.float32, torch.float64])\n def test_float_scalar_pow_float_tensor(self, device, dtype):\n floats = [2.0, -3 / 2, -1.0, -1 / 2, -1 / 3, 0.0,\n 1 / 3, 1 / 2, 1.0, 3 / 2, 2.0]\n exponent_shapes = (\n (1,),\n (2, 2),\n (2, 1),\n (2, 2, 2),\n )\n tensors = list(make_tensor(shape, dtype=dtype, device=device, low=0)\n for shape in exponent_shapes)\n floats_tensor = torch.tensor(floats, dtype=dtype, device=device)\n for base in floats:\n self._test_pow(base, floats_tensor)\n for tensor in tensors:\n self._test_pow(base, tensor)\n\n @onlyCUDA\n def test_cuda_tensor_pow_scalar_tensor(self, device):\n cuda_tensors = [torch.randn((3, 3), device=device), torch.tensor(3.0, device=device)]\n scalar_tensors = [torch.tensor(5.0, device='cpu'), torch.tensor(-3), torch.tensor(1)]\n for base, exp in product(cuda_tensors, scalar_tensors):\n self._test_pow(base, exp)\n\n @onlyCUDA\n def test_cpu_tensor_pow_cuda_scalar_tensor(self, device):\n cuda_tensors = [torch.tensor(5.0, device='cuda'), torch.tensor(-3, device='cuda')]\n for exp in cuda_tensors:\n base = torch.randn((3, 3), device='cpu')\n regex = 'Expected all tensors to be on the same device, but found at least two devices, cuda.* and cpu!'\n self.assertRaisesRegex(RuntimeError, regex, torch.pow, base, exp)\n for exp in cuda_tensors:\n # Binary ops with a cpu + cuda tensor are allowed if the cpu tensor has 0 dimension\n base = torch.tensor(3.0, device='cpu')\n self._test_pow(base, exp)\n\n @onlyCUDA\n @dtypes(torch.complex64, torch.complex128)\n def test_pow_cuda_complex_extremal_failing(self, device, dtype):\n t = torch.tensor(complex(-1., float('inf')), dtype=dtype, device=device)\n with self.assertRaises(AssertionError):\n cuda_out = t.pow(2)\n cpu_out = t.cpu().pow(2)\n self.assertEqual(cpu_out, cuda_out)\n\n @onlyOnCPUAndCUDA\n @dtypes(*(torch.testing.get_all_dtypes(include_bool=False, include_bfloat16=False)))\n def test_complex_scalar_pow_tensor(self, device, dtype):\n complexes = [0.5j, 1. + 1.j, -1.5j, 2.2 - 1.6j, 1 + 0j]\n first_exp = make_tensor((100,), device, dtype, low=-2, high=2)\n second_exp = make_tensor((100,), device, dtype, low=-2, high=2, noncontiguous=True)\n first_exp[0] = first_exp[10] = first_exp[20] = 0\n second_exp[0] = second_exp[10] = second_exp[20] = 0\n for base in complexes:\n self._test_pow(base, first_exp)\n self._test_pow(base, second_exp)\n\n @onlyOnCPUAndCUDA\n def test_pow_scalar_type_promotion(self, device):\n # Test against a scalar and non-scalar input\n inputs = [17, [17]]\n for input in inputs:\n # We expect the computation to be performed in uint8 (overflowing to 0), and then cast to int64\n input_tensor_uint8 = torch.tensor(input, dtype=torch.uint8, device=device)\n out_uint8_computation = torch.pow(2, input_tensor_uint8, out=torch.tensor(0, dtype=torch.int64, device=device))\n\n # Computation should run in int64, and not overflow\n input_tensor_int64 = torch.tensor(input, dtype=torch.int64, device=device)\n out_int64_computation = torch.pow(2, input_tensor_int64, out=torch.tensor(0, dtype=torch.int64, device=device))\n\n self.assertNotEqual(out_uint8_computation, out_int64_computation)\n self.assertEqual(out_uint8_computation.to(dtype=torch.uint8), out_int64_computation.to(dtype=torch.uint8))\n\n def test_tensor_pow_tensor(self, dev):\n def rotate(l, n):\n return l[-n:] + l[:-n]\n\n def test_tensor_pow_tensor(values, torch_type, numpy_type):\n vals_tensor = torch.tensor(values, dtype=torch_type, device=dev)\n for i in range(len(values)):\n pows = rotate(values, i)\n pows_tensor = torch.tensor(pows, dtype=torch_type, device=dev)\n self._test_pow(vals_tensor, pows_tensor)\n\n ints = [0, 1, 2, 3]\n test_tensor_pow_tensor(ints, torch.uint8, np.uint8)\n test_tensor_pow_tensor(ints, torch.int8, np.int8)\n test_tensor_pow_tensor(ints, torch.int16, np.int16)\n test_tensor_pow_tensor(ints, torch.int32, np.int32)\n test_tensor_pow_tensor(ints, torch.int64, np.int64)\n\n floats = [-3.0, -2.0, -1.0, -1 / 2, -1 / 3,\n 0.0, 1 / 3, 1 / 2, 1.0, 2.0, 3.0]\n test_tensor_pow_tensor(floats, torch.float16, np.float16)\n test_tensor_pow_tensor(floats, torch.float32, np.float32)\n test_tensor_pow_tensor(floats, torch.float64, np.float64)\n\n\n def test_logical_xor_with_nontrivial_alignment(self, device):\n # test tensor that is not aligned to multiple of 16 bytes\n size = 128\n a = (torch.randn(size, device=device) > 0)\n b = (torch.randn(size, device=device) > 0)\n c = (torch.randn(size, device=device) > 0)\n non_trivial_alignment = [1, 2, 4, 8, 15]\n for i in non_trivial_alignment:\n for j in non_trivial_alignment:\n for k in non_trivial_alignment:\n a_ = a[i: 100 + i]\n b_ = b[j: 100 + j]\n c_ = c[k: 100 + k]\n torch.logical_xor(a_, b_, out=c_)\n for x, y, z in zip(a_.tolist(), b_.tolist(), c_.tolist()):\n self.assertEqual(x ^ y, z)\n\n @dtypes(torch.float)\n def test_add_with_tail(self, device, dtype):\n # test tensor where there is a tail which is not a multiple\n # of GPU warp size\n for tail_size in [1, 63, 67, 130]:\n size = 4096 + tail_size\n a = torch.randn(size, device=device, dtype=dtype)\n b = torch.randn(size, device=device, dtype=dtype)\n c = a + b\n for x, y, z in zip(a.tolist(), b.tolist(), c.tolist()):\n self.assertEqual(x + y, z)\n\n # Tests that CUDA tensors on different devices cannot be used in the same\n # binary operation, and that CUDA \"scalars\" cannot be used in the same\n # binary operation as non-scalar CPU tensors.\n @deviceCountAtLeast(2)\n @onlyCUDA\n def test_cross_device_binary_ops(self, devices):\n vals = (1., (2.,))\n cpu_tensor = torch.randn(2, 2)\n\n def do_test(op, a, b):\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors.+\"):\n op(a, b)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors.+\"):\n op(b, a)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors.+\"):\n op(a, cpu_tensor)\n with self.assertRaisesRegex(RuntimeError, \"Expected all tensors.+\"):\n op(cpu_tensor, a)\n\n for op in (operator.add, torch.add,\n operator.sub, torch.sub,\n operator.mul, torch.mul,\n operator.truediv, torch.true_divide,\n operator.floordiv, torch.floor_divide):\n for a, b in product(vals, vals):\n a = torch.tensor(a, device=devices[0])\n b = torch.tensor(b, device=devices[1])\n\n do_test(op, a, b)\n\n # This test ensures that a scalar Tensor can be safely used\n # in a binary operation in conjunction with a Tensor on all\n # available CUDA devices\n @deviceCountAtLeast(2)\n @onlyCUDA\n def test_binary_op_scalar_device_unspecified(self, devices):\n scalar_val = torch.tensor(1.)\n for default_device in devices:\n with torch.cuda.device(default_device):\n for device in devices:\n device_obj = torch.device(device)\n x = torch.rand(3, device=device)\n y0 = x * scalar_val\n self.assertEqual(y0.device, device_obj)\n y1 = scalar_val * x\n self.assertEqual(y1.device, device_obj)\n self.assertEqual(y0, y1)\n\n def test_div_and_floordiv_vs_python(self, device):\n # Tests torch division ops which can handle both arguments being\n # scalars.\n # NOTE: torch.floor_divide currently truncates instead of flooring.\n # the quotient. See https://github.com/pytorch/pytorch/issues/43874.\n def _scalar_helper(python_op, torch_op):\n for a, b in product(range(-10, 10), range(-10, 10)):\n for op in (lambda x: x * .5, lambda x: math.floor(x)):\n a = op(a)\n b = op(b)\n\n # Skips zero divisors\n if b == 0:\n continue\n\n expected = python_op(a, b)\n\n for op in (operator.truediv, torch.true_divide):\n actual_scalar = torch_op(a, b)\n\n a_t = torch.tensor(a, device=device)\n b_t = torch.tensor(b, device=device)\n\n actual_tensor = torch_op(a_t, b_t)\n actual_first_tensor = torch_op(a_t, b)\n actual_second_tensor = torch_op(a, b_t)\n\n self.assertEqual(actual_scalar, expected_div)\n self.assertEqual(actual_tensor.item(), expected_div)\n self.assertEqual(actual_first_tensor, actual_tensor)\n self.assertEqual(actual_second_tensor, actual_tensor)\n\n _scalar_helper(operator.truediv, operator.truediv)\n _scalar_helper(operator.truediv, torch.true_divide)\n with self.assertWarnsOnceRegex(UserWarning, 'floor_divide'):\n _scalar_helper(lambda a, b: math.trunc(a / b), operator.floordiv)\n _scalar_helper(lambda a, b: math.trunc(a / b), torch.floor_divide)\n\n # NOTE: torch.floor_divide currently truncates instead of flooring.\n # See https://github.com/pytorch/pytorch/issues/43874.\n @onlyOnCPUAndCUDA\n def test_div_and_floordiv_script_vs_python(self, device):\n # Creates jitted functions of two tensors\n def _wrapped_div(a, b):\n return a / b\n\n def _wrapped_floordiv(a, b):\n return a // b\n\n scripted_div = torch.jit.script(_wrapped_div)\n scripted_floordiv = torch.jit.script(_wrapped_floordiv)\n for a, b in product(range(-10, 10), range(-10, 10)):\n for op in (lambda x: x * .5, lambda x: math.floor(x)):\n a = op(a)\n b = op(b)\n\n # Skips zero divisors\n if b == 0:\n continue\n\n expected_div = a / b\n expected_truncdiv = math.trunc(a / b)\n a_t = torch.tensor(a, device=device)\n b_t = torch.tensor(b, device=device)\n\n self.assertEqual(scripted_div(a_t, b_t), expected_div)\n with self.assertWarnsOnceRegex(UserWarning, 'floor_divide'):\n self.assertEqual(scripted_floordiv(a_t, b_t), expected_truncdiv)\n\n # Creates jitted functions of one tensor\n def _wrapped_div_scalar(a):\n return a / 5\n\n # NOTE: the JIT implements division as torch.reciprocal(a) * 5\n def _wrapped_rdiv_scalar(a):\n return 5 / a\n\n def _wrapped_floordiv_scalar(a):\n return a // 5\n\n # NOTE: this fails if the input is not an integer tensor\n # See https://github.com/pytorch/pytorch/issues/45199\n def _wrapped_rfloordiv_scalar(a):\n return 5 // a\n\n scripted_div_scalar = torch.jit.script(_wrapped_div_scalar)\n scripted_rdiv_scalar = torch.jit.script(_wrapped_rdiv_scalar)\n scripted_floordiv_scalar = torch.jit.script(_wrapped_floordiv_scalar)\n scripted_rfloordiv_scalar = torch.jit.script(_wrapped_rfloordiv_scalar)\n\n for a in range(-10, 10):\n for op in (lambda x: x * .5, lambda x: math.floor(x)):\n a = op(a)\n\n a_t = torch.tensor(a, device=device)\n\n self.assertEqual(a / 5, scripted_div_scalar(a_t))\n with self.assertWarnsOnceRegex(UserWarning, 'floor_divide'):\n self.assertEqual(math.trunc(a / 5), scripted_floordiv_scalar(a_t))\n\n # Skips zero divisors\n if a == 0:\n continue\n\n self.assertEqual(5 / a, scripted_rdiv_scalar(a_t))\n\n # Handles Issue 45199 (see comment above)\n if a_t.is_floating_point():\n with self.assertRaises(RuntimeError):\n scripted_rfloordiv_scalar(a_t)\n else:\n # This should emit a UserWarning, why doesn't it?\n # See issue gh-52387\n self.assertEqual(5 // a, scripted_rfloordiv_scalar(a_t))\n\n # NOTE: torch.floor_divide currently truncates instead of flooring\n # the quotient. See https://github.com/pytorch/pytorch/issues/43874.\n @onlyOnCPUAndCUDA\n def test_idiv_and_ifloordiv_vs_python(self, device):\n def _wrapped_idiv_tensor(a, b):\n a /= b\n return a\n\n def _wrapped_idiv_scalar(a):\n a /= 5\n return a\n\n def _wrapped_true_divide__tensor(a, b):\n a.true_divide_(b)\n return a\n\n def _wrapped_true_divide__scalar(a):\n a.true_divide_(5)\n return a\n\n def _wrapped_floor_divide__tensor(a, b):\n a.floor_divide_(b)\n return a\n\n def _wrapped_floor_divide__scalar(a):\n a.floor_divide_(5)\n return a\n\n # The following functions are unsupported by the JIT\n def _wrapped_ifloordiv_tensor(a, b):\n a //= b\n return a\n\n def _wrapped_ifloordiv_scalar(a):\n a //= 5\n return a\n\n with self.assertRaises(torch.jit.frontend.NotSupportedError):\n scripted_ifloordiv_tensor = torch.jit.script(_wrapped_ifloordiv_tensor)\n\n with self.assertRaises(torch.jit.frontend.NotSupportedError):\n scripted_ifloordiv_scalar = torch.jit.script(_wrapped_ifloordiv_scalar)\n\n scripted_idiv_tensor = torch.jit.script(_wrapped_idiv_tensor)\n scripted_idiv_scalar = torch.jit.script(_wrapped_idiv_scalar)\n scripted_true_divide__tensor = torch.jit.script(_wrapped_true_divide__tensor)\n scripted_true_divide__scalar = torch.jit.script(_wrapped_true_divide__scalar)\n scripted_floor_divide__tensor = torch.jit.script(_wrapped_floor_divide__tensor)\n scripted_floor_divide__scalar = torch.jit.script(_wrapped_floor_divide__scalar)\n\n for a, b in product(range(-10, 10), range(-10, 10)):\n for op in (lambda x: x * .5, lambda x: math.floor(x)):\n a = op(a)\n b = op(b)\n\n # Skips zero divisors\n if b == 0:\n continue\n\n expected_idiv = a / b\n expected_ifloordiv = a // b\n expected_itruncdiv = math.trunc(a / b)\n\n a_t = torch.tensor(a, device=device)\n b_t = torch.tensor(b, device=device)\n\n if a_t.is_floating_point():\n tmp0 = a_t.clone()\n tmp0 /= b\n\n tmp1 = a_t.clone()\n tmp1 /= b_t\n\n self.assertEqual(tmp0.item(), expected_idiv)\n self.assertEqual(tmp1.item(), expected_idiv)\n self.assertEqual(scripted_true_divide__tensor(a_t.clone(), b_t).item(), expected_idiv)\n self.assertEqual(scripted_true_divide__scalar(a_t.clone()).item(), a / 5)\n else:\n tmp = a_t.clone()\n with self.assertRaises(RuntimeError):\n tmp /= b\n with self.assertRaises(RuntimeError):\n tmp /= b_t\n with self.assertRaises(RuntimeError):\n scripted_true_divide__tensor(tmp, b_t)\n with self.assertRaises(RuntimeError):\n scripted_true_divide__scalar(tmp)\n\n\n if not a_t.is_floating_point() and b_t.is_floating_point():\n # Inplace modification fails because a float tensor is required\n # if the divisor is a float tensor\n with self.assertRaises(RuntimeError), self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n a_t.clone().floor_divide_(b_t)\n with self.assertRaises(RuntimeError), self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n scripted_floor_divide_tensor(a_t.clone(), b_t)\n tmp = a_t.clone()\n with self.assertRaises(RuntimeError), self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n tmp //= b_t\n else:\n # Inplace modification is OK when both or neither tensor is\n # a float tensor\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n self.assertEqual(a_t.clone().floor_divide_(b_t).item(), expected_itruncdiv)\n self.assertEqual(scripted_floor_divide__tensor(a_t.clone(), b_t).item(), expected_itruncdiv)\n tmp = a_t.clone()\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n tmp //= b_t\n self.assertEqual(tmp.item(), expected_itruncdiv)\n\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n self.assertEqual(scripted_floor_divide__scalar(a_t), math.trunc(a / 5))\n\n # Tests binary op equivalence with Python builtin ops\n # Also tests that reverse operations are equivalent to forward ops\n # NOTE: division ops are tested separately above\n def test_binary_ops_with_scalars(self, device):\n for ops in ((operator.add, torch.add),\n (operator.sub, torch.sub),\n (operator.mul, torch.mul),\n (operator.truediv, torch.div)):\n python_op, torch_op = ops\n\n for a, b in product(range(-10, 10), range(-10, 10)):\n for op in (lambda x: x * .5, lambda x: math.floor(x)):\n a = op(a)\n b = op(b)\n\n # Skips zero divisors\n if b == 0 or a == 0:\n continue\n\n a_tensor = torch.tensor(a, device=device)\n b_tensor = torch.tensor(b, device=device)\n a_tensor_cpu = a_tensor.cpu()\n b_tensor_cpu = b_tensor.cpu()\n vals = (a, b, a_tensor, b_tensor, a_tensor_cpu, b_tensor_cpu)\n\n for args in product(vals, vals):\n first, second = args\n\n first_scalar = first if not isinstance(first, torch.Tensor) else first.item()\n second_scalar = second if not isinstance(second, torch.Tensor) else second.item()\n expected = python_op(first_scalar, second_scalar)\n\n self.assertEqual(expected, python_op(first, second))\n self.assertEqual(expected, torch_op(first, second))\n\n @dtypes(*product(torch.testing.get_all_dtypes(include_complex=False), torch.testing.get_all_dtypes(include_complex=False)))\n def test_maximum_minimum_type_promotion(self, device, dtypes):\n a = torch.tensor((0, 1), device=device, dtype=dtypes[0])\n b = torch.tensor((1, 0), device=device, dtype=dtypes[1])\n for op in (torch.maximum, torch.max, torch.fmax, torch.minimum, torch.min, torch.fmin):\n result = op(a, b)\n self.assertEqual(result.dtype, torch.result_type(a, b))\n\n @dtypes(*(torch.testing.get_all_int_dtypes() + [torch.bool]))\n def test_maximum_minimum_int_and_bool(self, device, dtype):\n ops = ((torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum),\n (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin))\n rng = np.random.default_rng()\n a_np = np.array(rng.integers(-100, 100, size=10), dtype=torch_to_numpy_dtype_dict[dtype])\n b_np = np.array(rng.integers(-100, 100, size=10), dtype=torch_to_numpy_dtype_dict[dtype])\n\n for torch_op, alias, numpy_op in ops:\n a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype)\n b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype)\n tensor_result = torch_op(a_tensor, b_tensor)\n\n out = torch.empty_like(a_tensor)\n torch_op(a_tensor, b_tensor, out=out)\n\n numpy_result = numpy_op(a_np, b_np)\n\n if alias is not None:\n alias_result = alias(a_tensor, b_tensor)\n self.assertEqual(alias_result, tensor_result)\n\n self.assertEqual(tensor_result, numpy_result)\n self.assertEqual(out, numpy_result)\n\n @precisionOverride({torch.bfloat16: 1e-2})\n @dtypes(*(torch.testing.get_all_fp_dtypes()))\n def test_maximum_minimum_float(self, device, dtype):\n ops = ((torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum),\n (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin))\n\n if dtype == torch.bfloat16:\n a_np = np.random.randn(10).astype(np.float64)\n b_np = np.random.randn(10).astype(np.float64)\n else:\n a_np = np.random.randn(10).astype(torch_to_numpy_dtype_dict[dtype])\n b_np = np.random.randn(10).astype(torch_to_numpy_dtype_dict[dtype])\n\n for torch_op, alias, numpy_op in ops:\n numpy_result = numpy_op(a_np, b_np)\n\n a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype)\n b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype)\n tensor_result = torch_op(a_tensor, b_tensor)\n out = torch.empty_like(a_tensor)\n torch_op(a_tensor, b_tensor, out=out)\n\n if alias is not None:\n alias_result = alias(a_tensor, b_tensor)\n self.assertEqual(alias_result, tensor_result, exact_dtype=False)\n\n self.assertEqual(tensor_result, numpy_result, exact_dtype=False)\n self.assertEqual(out, numpy_result, exact_dtype=False)\n\n @dtypes(*(torch.testing.get_all_fp_dtypes()))\n def test_maximum_minimum_float_nan_and_inf(self, device, dtype):\n # np.maximum and np.minimum functions compare input arrays element-wisely.\n # if one of the elements being compared is a NaN, then that element is returned.\n ops = ((torch.maximum, torch.max, np.maximum), (torch.minimum, torch.min, np.minimum),\n (torch.fmax, None, np.fmax), (torch.fmin, None, np.fmin))\n a_vals = (float('inf'), -float('inf'), float('nan'), float('inf'), float('nan'), float('nan'), 1, float('nan'))\n b_vals = (-float('inf'), float('inf'), float('inf'), float('nan'), float('nan'), 0, float('nan'), -5)\n if dtype == torch.bfloat16:\n a_np = np.array(a_vals, dtype=np.float64)\n b_np = np.array(b_vals, dtype=np.float64)\n else:\n a_np = np.array(a_vals, dtype=torch_to_numpy_dtype_dict[dtype])\n b_np = np.array(b_vals, dtype=torch_to_numpy_dtype_dict[dtype])\n\n for torch_op, alias, numpy_op in ops:\n numpy_result = numpy_op(a_np, b_np)\n\n a_tensor = torch.from_numpy(a_np).to(device=device, dtype=dtype)\n b_tensor = torch.from_numpy(b_np).to(device=device, dtype=dtype)\n tensor_result = torch_op(a_tensor, b_tensor)\n\n out = torch.empty_like(a_tensor)\n torch_op(a_tensor, b_tensor, out=out)\n\n if alias is not None:\n alias_result = alias(a_tensor, b_tensor)\n self.assertEqual(alias_result, tensor_result)\n\n if dtype == torch.bfloat16:\n self.assertEqual(tensor_result, numpy_result, exact_dtype=False)\n self.assertEqual(out, numpy_result, exact_dtype=False)\n else:\n self.assertEqual(tensor_result, numpy_result)\n self.assertEqual(out, numpy_result)\n\n @dtypes(*product(torch.testing.get_all_complex_dtypes(), torch.testing.get_all_dtypes()))\n def test_maximum_minimum_complex(self, device, dtypes):\n for torch_op in (torch.maximum, torch.minimum, torch.max, torch.min, torch.fmax, torch.fmin):\n with self.assertRaisesRegex(RuntimeError, '.+not implemented for.+'):\n torch_op(torch.ones(1, device=device, dtype=dtypes[0]),\n torch.ones(1, device=device, dtype=dtypes[1]))\n\n with self.assertRaisesRegex(RuntimeError, '.+not implemented for.+'):\n torch_op(torch.ones(1, device=device, dtype=dtypes[1]),\n torch.ones(1, device=device, dtype=dtypes[0]))\n\n @onlyCUDA\n def test_maximum_minimum_cross_device(self, device):\n a = torch.tensor((1, 2, -1))\n b = torch.tensor((3, 0, 4), device=device)\n ops = (torch.maximum, torch.minimum)\n\n for torch_op in ops:\n with self.assertRaisesRegex(RuntimeError,\n \"Expected all tensors to be on the same device\"):\n torch_op(a, b)\n\n with self.assertRaisesRegex(RuntimeError,\n \"Expected all tensors to be on the same device\"):\n torch_op(b, a)\n\n # test cuda tensor and cpu scalar\n ops = ((torch.maximum, np.maximum), (torch.minimum, np.minimum))\n a_np = np.array(1)\n b_np = np.array([3, 0, 4])\n\n for torch_op, numpy_op in ops:\n a_tensor = torch.from_numpy(a_np)\n b_tensor = torch.from_numpy(b_np).to(device=device)\n tensor_result_1 = torch_op(a_tensor, b_tensor)\n numpy_result_1 = numpy_op(a_np, b_np)\n tensor_result_2 = torch_op(b_tensor, a_tensor)\n numpy_result_2 = numpy_op(b_np, a_np)\n\n self.assertEqual(tensor_result_1, numpy_result_1)\n self.assertEqual(tensor_result_2, numpy_result_2)\n\n # TODO: tests like this should be generic\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float, torch.double)\n def test_mul_intertype_scalar(self, device, dtype):\n x = torch.tensor(1.5, dtype=dtype, device=device)\n y = torch.tensor(3, dtype=torch.int32, device=device)\n\n self.assertEqual(x * y, 4.5)\n self.assertEqual(y * x, 4.5)\n\n with self.assertRaisesRegex(RuntimeError, \"can't be cast to the desired output type\"):\n y *= x\n x *= y\n self.assertEqual(x, 4.5)\n\n @onlyCPU\n @dtypes(*torch.testing.get_all_dtypes())\n def test_sub(self, device, dtype):\n m1 = torch.tensor([2.34, 4.44], dtype=dtype, device=device)\n m2 = torch.tensor([1.23, 2.33], dtype=dtype, device=device)\n\n if dtype == torch.bool:\n self.assertRaises(RuntimeError, lambda: m1 - m2)\n elif (dtype == torch.bfloat16 or dtype == torch.half):\n # bfloat16 has a lower precision so we have to have a separate check for it\n self.assertEqual(m1 - m2, torch.tensor([1.11, 2.11], dtype=dtype), atol=0.01, rtol=0)\n else:\n self.assertEqual(m1 - m2, torch.tensor([1.11, 2.11], dtype=dtype))\n\n # TODO: what is this test testing?\n @onlyCPU\n @dtypes(torch.float)\n def test_csub(self, device, dtype):\n # with a tensor\n a = torch.randn(100, 90, dtype=dtype, device=device)\n b = a.clone().normal_()\n\n res_add = torch.add(a, b, alpha=-1)\n res_csub = a.clone()\n res_csub.sub_(b)\n self.assertEqual(res_add, res_csub)\n\n # with a scalar\n a = torch.randn(100, 100, dtype=dtype, device=device)\n\n scalar = 123.5\n res_add = torch.add(a, -scalar)\n res_csub = a.clone()\n res_csub.sub_(scalar)\n self.assertEqual(res_add, res_csub)\n\n # TODO: reconcile with minimum/maximum tests\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float, torch.double)\n def test_min_max_binary_op_nan(self, device, dtype):\n a = torch.rand(1000, dtype=dtype, device=device)\n b = torch.rand(1000, dtype=dtype, device=device)\n\n # 0:250: a -- nan, b -- not nan\n a[:250] = float('nan')\n # 250:500: a -- not nan, b -- nan\n b[250:500] = float('nan')\n # 500:750: a and b both nan\n a[500:750] = float('nan')\n b[500:750] = float('nan')\n # 750:1000: neither nan\n\n ma = torch.max(a, b)\n mi = torch.min(a, b)\n\n for i in range(750):\n self.assertTrue(torch.isnan(ma[i]), \"max(a, b): {}, a: {}, b: {}\".format(ma[i], a[i], b[i]))\n self.assertTrue(torch.isnan(mi[i]), \"min(a, b): {}, a: {}, b: {}\".format(mi[i], a[i], b[i]))\n\n for i in range(750, 1000):\n self.assertFalse(torch.isnan(ma[i]), \"max(a, b): {}, a: {}, b: {}\".format(ma[i], a[i], b[i]))\n self.assertFalse(torch.isnan(mi[i]), \"min(a, b): {}, a: {}, b: {}\".format(mi[i], a[i], b[i]))\n\n @dtypes(*product(torch.testing.get_all_dtypes(include_complex=False),\n torch.testing.get_all_dtypes(include_complex=False)))\n def test_copysign(self, device, dtypes):\n def _test_copysign_numpy(a, b):\n torch_result = torch.copysign(a, b)\n\n if a.dtype == torch.bfloat16:\n np_a = a.to(torch.float).cpu().numpy()\n else:\n np_a = a.cpu().numpy()\n\n if b.dtype == torch.bfloat16:\n np_b = b.to(torch.float).cpu().numpy()\n else:\n np_b = b.cpu().numpy()\n expected = torch.from_numpy(np.copysign(np_a, np_b))\n # To handle inconsistencies of type promotion between PyTorch and Numpy\n # Applied for both arguments having integral precision and bfloat16\n types = [torch.bool, torch.bfloat16] + torch.testing.get_all_int_dtypes()\n if a.dtype in types or b.dtype in types:\n promoted_type = torch.promote_types(torch_result.dtype, expected.dtype)\n torch_result = torch_result.to(promoted_type)\n expected = expected.to(promoted_type)\n\n # Verify Value\n self.assertEqual(torch_result, expected)\n # Verify Sign\n # Use double copysign to verify the correctnes of 0.0 and -0.0, since\n # it always True for self.assertEqual(0.0 == -0.0). So, we use 1 as the\n # magnitude to verify the sign between torch and numpy results, elementwise.\n # Special case: NaN conversions between FP32 and FP16 is not bitwise\n # equivalent to pass this assertion.\n if a.dtype != torch.float16 and b.dtype != torch.float16:\n self.assertEqual(torch.copysign(torch.tensor(1.0), torch_result),\n torch.copysign(torch.tensor(1.0), expected))\n\n # Compare Result with NumPy\n # Type promotion\n a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9)\n b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9)\n _test_copysign_numpy(a, b)\n\n # Broadcast\n a = make_tensor((10, 1, 10), device=device, dtype=dtypes[0], low=-9, high=9)\n b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9)\n _test_copysign_numpy(a, b)\n\n a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9)\n b = make_tensor((10, 1, 10), device=device, dtype=dtypes[1], low=-9, high=9)\n _test_copysign_numpy(a, b)\n\n # 0.0/-0.0/inf/-inf/nan\n cases = [0.0, -0.0, float('inf'), float('-inf'), float('nan')]\n # torch.bfloat16 can not hold '-nan'\n # torch.half can not hold '-nan' on CUDA\n types = [torch.float32, torch.float64]\n if device == 'cpu':\n types.append(torch.float16)\n if dtypes[0] in types:\n b = make_tensor((10, 10), device=device, dtype=dtypes[1], low=-9, high=9)\n for case in cases:\n _test_copysign_numpy(torch.tensor([case], device=device, dtype=dtypes[0]), b)\n\n if dtypes[1] in torch.testing.get_all_fp_dtypes():\n a = make_tensor((10, 10), device=device, dtype=dtypes[0], low=-9, high=9)\n for case in cases:\n _test_copysign_numpy(a, torch.tensor([case], device=device, dtype=dtypes[1]))\n\n @dtypes(torch.bfloat16, torch.float)\n def test_div(self, device, dtype):\n for op, method, inplace in ((torch.div, torch.Tensor.div, torch.Tensor.div_),\n (torch.true_divide, torch.Tensor.true_divide,\n torch.Tensor.true_divide_)):\n m1 = torch.randn(10, 10, dtype=torch.float, device=device).to(dtype=dtype)\n res1 = m1.clone()\n inplace(res1[:, 3], 2)\n res2 = m1.clone()\n for i in range(m1.size(0)):\n res2[i, 3] = res2[i, 3] / 2\n self.assertEqual(res1, res2)\n\n if dtype == torch.bfloat16:\n a1 = torch.tensor([4.2, 6.2], dtype=dtype, device=device)\n a2 = torch.tensor([2., 2.], dtype=dtype, device=device)\n self.assertEqual(op(a1, a2),\n torch.tensor([2.1, 3.1], dtype=dtype, device=device),\n atol=0.01, rtol=0)\n self.assertEqual(method(a1, a2), op(a1, a2))\n\n @dtypes(torch.bfloat16, torch.float)\n def test_true_divide_out(self, device, dtype):\n a1 = torch.tensor([4.2, 6.2], dtype=dtype, device=device)\n a2 = torch.tensor([2., 2.], dtype=dtype, device=device)\n res = torch.empty_like(a1)\n self.assertEqual(torch.true_divide(a1, a2, out=res),\n torch.tensor([2.1, 3.1], dtype=dtype, device=device),\n atol=0.01, rtol=0)\n\n @onlyCUDA\n @dtypes(torch.half)\n def test_divmul_scalar(self, device, dtype):\n x = torch.tensor(100., device=device, dtype=dtype)\n x_ref = x.float()\n scale = 1e5\n res = x.div(scale)\n expected = x_ref.div(scale)\n self.assertEqual(res, expected.to(dtype), atol=0., rtol=0.)\n x = torch.tensor(1e-5, device=device, dtype=dtype)\n x_ref = x.float()\n res = x.mul(scale)\n expected = x_ref.mul(scale)\n self.assertEqual(res, expected.to(dtype), atol=0., rtol=0.)\n res = scale * x\n self.assertEqual(res, expected.to(dtype), atol=0., rtol=0.)\n\n @dtypesIfCUDA(*set(torch.testing.get_all_math_dtypes('cuda')) - {torch.complex64, torch.complex128})\n @dtypes(*set(torch.testing.get_all_math_dtypes('cpu')) - {torch.complex64, torch.complex128})\n def test_floor_divide_tensor(self, device, dtype):\n x = torch.randn(10, device=device).mul(30).to(dtype)\n y = torch.arange(1, 11, dtype=dtype, device=device)\n\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n z = x // y\n z_alt = torch.trunc(x.double() / y.double()).to(dtype)\n\n self.assertEqual(z.dtype, x.dtype)\n self.assertEqual(z, z_alt)\n\n @dtypesIfCUDA(*set(torch.testing.get_all_math_dtypes('cuda')) - {torch.complex64, torch.complex128})\n @dtypes(*set(torch.testing.get_all_math_dtypes('cpu')) - {torch.complex64, torch.complex128})\n def test_floor_divide_scalar(self, device, dtype):\n x = torch.randn(100, device=device).mul(10).to(dtype)\n\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n z = x // 3\n z_alt = torch.tensor([math.trunc(v.item() / 3.) for v in x], dtype=x.dtype, device=device)\n\n self.assertEqual(z.dtype, x.dtype)\n self.assertEqual(z, z_alt)\n\n # Note: this tests fails on XLA\n @onlyOnCPUAndCUDA\n @dtypes(torch.float, torch.long)\n def test_floor_divide_out(self, device, dtype):\n x = torch.randn(10, device=device).mul(10).to(dtype)\n y = torch.arange(1, 11, dtype=dtype, device=device)\n o = torch.empty(10, dtype=dtype, device=device)\n\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n torch.floor_divide(x, y, out=o)\n self.assertEqual(o, x // y)\n\n # Tests scalar with out\n torch.floor_divide(x, 2, out=o)\n self.assertEqual(o, x // 2)\n\n if dtype == torch.int:\n o = torch.empty(10, dtype=torch.float, device=device)\n torch.floor_divide(x, y, out=o)\n self.assertEqual(o, torch.floor_divide(x.float(), y.float()))\n\n @onlyCPU\n @dtypes(*torch.testing.get_all_math_dtypes('cpu'))\n def test_rdiv(self, device, dtype):\n if dtype is torch.float16:\n return\n elif dtype.is_complex:\n x = torch.rand(100, dtype=dtype, device=device).add(1).mul(4)\n else:\n x = torch.rand(100, device=device).add(1).mul(4).to(dtype)\n y = 30 / x\n z = torch.tensor([30 / v.item() for v in x], device=device)\n self.assertEqual(y, z, exact_dtype=False)\n\n @dtypes(*torch.testing.get_all_fp_dtypes(include_bfloat16=False))\n def test_fmod_remainder_by_zero_float(self, device, dtype):\n fn_list = (torch.fmod, torch.remainder)\n for fn in fn_list:\n # check floating-point tensor fmod/remainder to zero is nan on both CPU and GPU\n x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9)\n zero = torch.zeros_like(x)\n self.assertTrue(torch.all(fn(x, 0.0).isnan()))\n self.assertTrue(torch.all(fn(x, zero).isnan()))\n\n @onlyOnCPUAndCUDA # Check Issue https://github.com/pytorch/pytorch/issues/48130\n @skipCUDAIfRocm # Error happens on both ROCM and XLA\n @dtypes(*torch.testing.get_all_int_dtypes())\n def test_fmod_remainder_by_zero_integral(self, device, dtype):\n fn_list = (torch.fmod, torch.remainder)\n for fn in fn_list:\n # check integral tensor fmod/remainder to zero\n x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9)\n zero = torch.zeros_like(x)\n # RuntimeError on CPU\n if self.device_type == 'cpu':\n with self.assertRaisesRegex(RuntimeError, \"ZeroDivisionError\"):\n fn(x, zero)\n # Different value for different dtype on CUDA:\n # Due to it's an undefined behavior, CUDA returns a pattern of all 1s\n # for integral dividend (other than int64) divided by zero. For int64,\n # CUDA returns all 1s for negative dividend, half 1s for positive dividend.\n # uint8: 0xff -> 255\n # int32: 0xffffffff -> -1\n else:\n if dtype == torch.int64:\n self.assertEqual(fn(x, zero) == 4294967295, x >= 0)\n self.assertEqual(fn(x, zero) == -1, x < 0)\n else:\n value = 255 if dtype == torch.uint8 else -1\n self.assertTrue(torch.all(fn(x, zero) == value))\n\n @dtypes(*torch.testing.get_all_dtypes(include_bfloat16=False, include_bool=False, include_complex=False))\n def test_fmod_remainder(self, device, dtype):\n # Use numpy as reference\n def _helper(x, mod, fns_list):\n for fn, inplace_fn, ref_fn in fns_list:\n np_x = x.cpu().numpy() if torch.is_tensor(x) else x\n np_mod = mod.cpu().numpy() if torch.is_tensor(mod) else mod\n exp = ref_fn(np_x, np_mod)\n exp = torch.from_numpy(exp)\n res = fn(x, mod)\n\n self.assertEqual(res, exp, exact_dtype=False)\n\n if torch.is_tensor(x):\n # out\n out = torch.empty(0, device=device, dtype=res.dtype)\n fn(x, mod, out=out)\n self.assertEqual(out, exp, exact_dtype=False)\n self.assertEqual(out.size(), torch.Size([10, 10]))\n # in-place (Type cast runtime error)\n try:\n inplace_fn(x, mod)\n self.assertEqual(x, exp, exact_dtype=False)\n except RuntimeError as e:\n self.assertRegex(str(e), \"result type (Half|Float|Double) \"\n \"can't be cast to the desired output \"\n \"type (Byte|Char|Short|Int|Long)\")\n\n x = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9)\n # mod with same dtype as x\n mod = make_tensor((10, 10), device=device, dtype=dtype, low=-9, high=9)\n # Exclude 0\n mod[mod == 0] = 1\n\n # Mods: Integer, Float, Tensor, Non-contiguous Tensor\n mods = [3, 2.3, mod, mod.t()]\n # mod with floating-point dtype\n if dtype in torch.testing.get_all_int_dtypes():\n mod_float = make_tensor((10, 10), device=device, dtype=torch.float, low=-9, high=9)\n mod[mod == 0] = 1\n mods.append(mod_float)\n\n for dividend, mod in product([x, x.t()], mods):\n _helper(dividend, mod,\n ((torch.fmod, torch.Tensor.fmod_, np.fmod),\n (torch.remainder, torch.Tensor.remainder_, np.remainder),))\n\n # Tests for torch.remainder(scalar, tensor)\n for dividend, mod in product([5, 3.14], mods):\n if torch.is_tensor(mod):\n _helper(dividend, mod,\n ((torch.remainder, torch.Tensor.remainder_, np.remainder),))\n\n @dtypes(torch.float, torch.double)\n def test_remainder_fmod_large_dividend(self, device, dtype):\n alarge = 1e9\n pi = 3.14159265358979\n for avalue in [alarge, -alarge]:\n for bvalue in [pi, -pi]:\n a = torch.tensor([avalue], dtype=dtype, device=device)\n b = torch.tensor([bvalue], dtype=dtype, device=device)\n c = torch.remainder(a, b)\n d = torch.fmod(a, b)\n self.assertTrue((b[0] > 0) == (c[0] > 0)) # remainder has same sign as divisor\n self.assertTrue((a[0] > 0) == (d[0] > 0)) # fmod has same sign as dividend\n self.assertTrue(abs(c[0]) < abs(b[0])) # remainder is within range of divisor\n self.assertTrue(abs(d[0]) < abs(b[0])) # fmod is within range of divisor\n if ((a[0] > 0) == (b[0] > 0)):\n self.assertTrue(c[0] == d[0]) # remainder is same as fmod\n else:\n self.assertTrue(abs(c[0] - d[0]) == abs(b[0])) # differ by one divisor\n\n @dtypesIfCPU(torch.bfloat16, torch.float32, torch.float64)\n @dtypes(torch.float32, torch.float64)\n def test_hypot(self, device, dtype):\n inputs = [\n (torch.randn(10, device=device).to(dtype), torch.randn(10, device=device).to(dtype)),\n (torch.randn((3, 3, 3), device=device).to(dtype), torch.randn((3, 3, 3), device=device).to(dtype)),\n (torch.randn((10, 1), device=device).to(dtype), torch.randn((10, 1), device=device).to(dtype).transpose(0, 1)),\n (torch.randint(100, (10, ), device=device, dtype=torch.long), torch.randn(10, device=device).to(dtype))\n ]\n for input in inputs:\n actual = torch.hypot(input[0], input[1])\n if dtype == torch.bfloat16:\n expected = torch.sqrt(input[0] * input[0] + input[1] * input[1])\n else:\n expected = np.hypot(input[0].cpu().numpy(), input[1].cpu().numpy())\n self.assertEqual(actual, expected, exact_dtype=False)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)\n def test_gcd(self, device, dtype):\n # Tests gcd(0, 0), gcd(0, a) cases\n t1 = torch.tensor([0, 10, 0], dtype=dtype, device=device)\n t2 = torch.tensor([0, 0, 10], dtype=dtype, device=device)\n actual = torch.gcd(t1, t2)\n expected = np.gcd([0, 10, 0], [0, 0, 10])\n self.assertEqual(actual, expected, exact_dtype=False)\n\n if dtype == torch.uint8:\n # Test unsigned integers with potential sign issues (i.e., uint8 with value >= 128)\n a = torch.tensor([190, 210], device=device, dtype=dtype)\n b = torch.tensor([190, 220], device=device, dtype=dtype)\n actual = torch.gcd(a, b)\n expected = torch.tensor([190, 10], device=device, dtype=dtype)\n self.assertEqual(actual, expected)\n else:\n # Compares with NumPy\n a = torch.randint(-20, 20, (1024,), device=device, dtype=dtype)\n b = torch.randint(-20, 20, (1024,), device=device, dtype=dtype)\n actual = torch.gcd(a, b)\n expected = np.gcd(a.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(actual, expected)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.int16, torch.int32, torch.int64)\n def test_lcm(self, device, dtype):\n # Tests lcm(0, 0), lcm(0, a) cases\n t1 = torch.tensor([0, 10, 0], dtype=dtype, device=device)\n t2 = torch.tensor([0, 0, 10], dtype=dtype, device=device)\n actual = torch.lcm(t1, t2)\n expected = np.lcm([0, 10, 0], [0, 0, 10])\n self.assertEqual(actual, expected, exact_dtype=False)\n\n # Compares with NumPy\n a = torch.randint(-20, 20, (1024,), device=device, dtype=dtype)\n b = torch.randint(-20, 20, (1024,), device=device, dtype=dtype)\n actual = torch.lcm(a, b)\n expected = np.lcm(a.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(actual, expected, exact_dtype=False)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float32, torch.float64)\n def test_nextafter(self, device, dtype):\n # Test special cases\n t1 = torch.tensor([0, 0, 10], device=device, dtype=dtype)\n t2 = torch.tensor([inf, -inf, 10], device=device, dtype=dtype)\n actual = torch.nextafter(t1, t2)\n expected = np.nextafter(t1.cpu().numpy(), t2.cpu().numpy())\n self.assertEqual(actual, expected, atol=0, rtol=0)\n\n actual = torch.nextafter(t2, t1)\n expected = np.nextafter(t2.cpu().numpy(), t1.cpu().numpy())\n self.assertEqual(actual, expected, atol=0, rtol=0)\n\n t1 = torch.tensor([0, nan], device=device, dtype=dtype)\n t2 = torch.tensor([nan, 0], device=device, dtype=dtype)\n self.assertTrue(torch.nextafter(t1, t2).isnan().all())\n\n a = torch.randn(100, device=device, dtype=dtype)\n b = torch.randn(100, device=device, dtype=dtype)\n actual = torch.nextafter(a, b)\n expected = np.nextafter(a.cpu().numpy(), b.cpu().numpy())\n self.assertEqual(actual, expected, atol=0, rtol=0)\n\n def _test_cop(self, torchfn, mathfn, dtype, device):\n def reference_implementation(res2):\n for i, j in iter_indices(sm1):\n idx1d = i * sm1.size(0) + j\n res2[i, j] = mathfn(sm1[i, j], sm2[idx1d])\n return res2\n\n # contiguous\n m1 = torch.randn(10, 10, 10, dtype=dtype, device=device)\n m2 = torch.randn(10, 10 * 10, dtype=dtype, device=device)\n sm1 = m1[4]\n sm2 = m2[4]\n\n res1 = torchfn(sm1, sm2.view(10, 10))\n res2 = reference_implementation(res1.clone())\n self.assertEqual(res1, res2)\n\n # non-contiguous\n m1 = torch.randn(10, 10, 10, dtype=dtype, device=device)\n m2 = torch.randn(10 * 10, 10 * 10, dtype=dtype, device=device)\n sm1 = m1[:, 4]\n sm2 = m2[:, 4]\n # view as sm1.size()\n sm2.set_(sm2.storage(), sm2.storage_offset(), sm1.size(), (sm2.stride()[0] * 10, sm2.stride()[0]))\n res1 = torchfn(sm1, sm2)\n # reference_implementation assumes 1-d sm2\n sm2.set_(sm2.storage(), sm2.storage_offset(), m2[:, 4].size(), m2[:, 4].stride())\n res2 = reference_implementation(res1.clone())\n self.assertEqual(res1, res2)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cdiv(self, device, dtype):\n self._test_cop(torch.div, lambda x, y: x / y, dtype, device)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cremainder(self, device, dtype):\n self._test_cop(torch.remainder, lambda x, y: x % y, dtype, device)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cmul(self, device, dtype):\n self._test_cop(torch.mul, lambda x, y: x * y, dtype, device)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_cpow(self, device, dtype):\n self._test_cop(torch.pow, lambda x, y: nan if x < 0 else math.pow(x, y), dtype, device)\n\n @onlyCPU\n @dtypes(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)\n def test_floor_divide_zero(self, device, dtype):\n a = torch.tensor([0, 1], dtype=dtype, device=device)\n b = torch.tensor([0, 1], dtype=dtype, device=device)\n with self.assertRaisesRegex(RuntimeError, 'ZeroDivisionError'):\n with self.assertWarnsOnceRegex(UserWarning, \"floor_divide\"):\n a // b\n\n @unittest.skipIf(TEST_WITH_ASAN, \"Integer overflows are not allowed under ASAN\")\n @dtypes(*torch.testing.get_all_dtypes())\n def test_muldiv_scalar(self, device, dtype):\n x = make_tensor((10, 3), device, dtype, low=None, high=None)\n s = make_tensor((1,), 'cpu', dtype, low=None, high=None).item()\n y = torch.full_like(x, s)\n self.assertEqual(x * s, x * y)\n self.assertEqual(s * x, y * x)\n self.assertEqual(x / s, x / y)\n self.assertEqual(s / x, y / x)\n\n @dtypes(*tuple(itertools.combinations_with_replacement(torch.testing.get_all_dtypes(), 2)))\n def test_comparison_ops_type_promotion_and_broadcasting(self, device, dtypes):\n # issue #42660\n # testing all combinations of broadcasting and type promotion\n # with a range of dtypes and input shapes, and with extremal values\n def compare_with_numpy_bin_op(torch_fn, np_fn, x, y, out=None):\n # working around the fact that numpy doesn't support bfloat16\n # by letting numpy treat them as float32's\n x_np = x if x.dtype != torch.bfloat16 else x.to(torch.float32)\n y_np = y.cpu().numpy() if y.dtype != torch.bfloat16 else y.to(torch.float32).cpu().numpy()\n self.compare_with_numpy(lambda inp: torch_fn(inp, y, out=out) if out else torch_fn(inp, y),\n lambda inp: np_fn(inp, y_np, out=out) if out else np_fn(inp, y_np),\n x_np)\n\n complex_op_denylist = [torch.lt, torch.le, torch.gt, torch.ge] # complex not supported\n input_sizes = [\n (1,),\n (10,),\n (10, 1),\n (1, 10),\n (4, 10),\n (64, 10),\n (12, 3)]\n op_pairs = [(torch.lt, np.less),\n (torch.le, np.less_equal),\n (torch.gt, np.greater),\n (torch.ge, np.greater_equal),\n (torch.eq, np.equal),\n (torch.ne, np.not_equal),\n (torch.logical_and, np.logical_and),\n (torch.logical_or, np.logical_or),\n (torch.logical_xor, np.logical_xor)]\n\n for size1 in input_sizes:\n size2 = (2,) + size1 # perform broadcasting\n for with_extremal in [False, True]:\n a = _generate_input(size1, dtypes[0], device, with_extremal)\n b = _generate_input(size2, dtypes[1], device, with_extremal)\n for torch_op, numpy_op in op_pairs:\n if (dtypes[0].is_complex or dtypes[1].is_complex) and torch_op in complex_op_denylist:\n continue\n # functional version of op\n compare_with_numpy_bin_op(torch_op, numpy_op, a, b)\n\n # functional comparison ops always return bool tensors\n self.assertEqual(torch_op(a, b).dtype, torch.bool)\n\n # out version of op\n out = torch.zeros(1, dtype=torch.complex128) # all casts to complex128 are safe\n compare_with_numpy_bin_op(torch_op, numpy_op, a, b, out=out)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.int8, torch.int16, torch.int32, torch.int64)\n def test_signed_shift(self, device, dtype):\n \"Ensure that signed integer bit shifting works as expected.\"\n a = torch.tensor([-10, 10], device=device, dtype=dtype) # [11...1110110, 1010]\n expected_l = torch.tensor([-40, 40], device=device, dtype=dtype) # [11...11011000, 101000]\n self.assertEqual(a << 2, expected_l)\n self.compare_with_numpy(lambda x: x << 2, lambda x: np.left_shift(x, 2), a)\n expected_r = torch.tensor([-5, 5], device=device, dtype=dtype) # [1111...111011, 101]\n self.assertEqual(a >> 1, expected_r)\n self.compare_with_numpy(lambda x: x >> 1, lambda x: np.right_shift(x, 1), a)\n\n def test_bitwise_and(self, device):\n for dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64):\n a = torch.tensor([1, -2, 3], dtype=dtype, device=device)\n b = torch.tensor([2, 1, 3], dtype=dtype, device=device)\n expected_res = torch.tensor([0, 0, 3], dtype=dtype, device=device)\n b_scalar = 2\n expected_res_scalar = torch.tensor([0, 2, 2], dtype=dtype, device=device)\n\n # standard version\n self.assertEqual(torch.bitwise_and(a, b), expected_res)\n self.assertEqual(torch.bitwise_and(a, b_scalar), expected_res_scalar)\n\n # out\n c = torch.empty(0, dtype=dtype, device=device)\n torch.bitwise_and(a, b, out=c)\n self.assertEqual(c, expected_res)\n torch.bitwise_and(a, b_scalar, out=c)\n self.assertEqual(c, expected_res_scalar)\n\n # in-place\n a1 = a.clone()\n a1.bitwise_and_(b)\n self.assertEqual(a1, expected_res)\n a.bitwise_and_(b_scalar)\n self.assertEqual(a, expected_res_scalar)\n\n self.assertEqual(torch.tensor([False, True, False], device=device),\n torch.bitwise_and(torch.tensor([True, True, False], device=device),\n torch.tensor([False, True, False], device=device)))\n\n def test_bitwise_or(self, device):\n for dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64):\n a = torch.tensor([1, -2, 3], dtype=dtype, device=device)\n b = torch.tensor([2, 1, 3], dtype=dtype, device=device)\n expected_res = torch.tensor([3, -1, 3], dtype=dtype, device=device)\n b_scalar = 2\n expected_res_scalar = torch.tensor([3, -2, 3], dtype=dtype, device=device)\n\n # standard version\n self.assertEqual(torch.bitwise_or(a, b), expected_res)\n self.assertEqual(torch.bitwise_or(a, b_scalar), expected_res_scalar)\n\n # out\n c = torch.empty(0, dtype=dtype, device=device)\n torch.bitwise_or(a, b, out=c)\n self.assertEqual(c, expected_res)\n torch.bitwise_or(a, b_scalar, out=c)\n self.assertEqual(c, expected_res_scalar)\n\n # in-place\n a1 = a.clone()\n a1.bitwise_or_(b)\n self.assertEqual(a1, expected_res)\n a.bitwise_or_(b_scalar)\n self.assertEqual(a, expected_res_scalar)\n\n self.assertEqual(torch.tensor([True, True, False], device=device),\n torch.bitwise_or(torch.tensor([True, True, False], device=device),\n torch.tensor([False, True, False], device=device)))\n\n def test_bitwise_xor(self, device):\n for dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64):\n a = torch.tensor([1, -2, 3], dtype=dtype, device=device)\n b = torch.tensor([2, 1, 3], dtype=dtype, device=device)\n expected_res = torch.tensor([3, -1, 0], dtype=dtype, device=device)\n b_scalar = 2\n expected_res_scalar = torch.tensor([3, -4, 1], dtype=dtype, device=device)\n\n # standard version\n self.assertEqual(torch.bitwise_xor(a, b), expected_res)\n self.assertEqual(torch.bitwise_xor(a, b_scalar), expected_res_scalar)\n\n # out\n c = torch.empty(0, dtype=dtype, device=device)\n torch.bitwise_xor(a, b, out=c)\n self.assertEqual(c, expected_res)\n torch.bitwise_xor(a, b_scalar, out=c)\n self.assertEqual(c, expected_res_scalar)\n\n # in-place\n a1 = a.clone()\n a1.bitwise_xor_(b)\n self.assertEqual(a1, expected_res)\n a.bitwise_xor_(b_scalar)\n self.assertEqual(a, expected_res_scalar)\n\n self.assertEqual(torch.tensor([True, False, False], device=device),\n torch.bitwise_xor(torch.tensor([True, True, False], device=device),\n torch.tensor([False, True, False], device=device)))\n\n @dtypes(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)\n def test_bitwise_shift(self, device, dtype):\n ops = [\n (torch.bitwise_left_shift, np.left_shift),\n (operator.lshift, operator.lshift),\n (torch.bitwise_right_shift, np.right_shift),\n (operator.rshift, operator.rshift),\n ]\n for torch_op, numpy_op in ops:\n a = torch.tensor([19, -20, -21, 22], dtype=dtype, device=device)\n b = torch.tensor([2, 1, 3, 1], dtype=dtype, device=device)\n a_np = a.cpu().numpy()\n b_np = b.cpu().numpy()\n\n # Tensor x Tensor\n self.assertEqual(torch_op(a, b), torch.tensor(numpy_op(a_np, b_np), device=device))\n # Tensor x int scalar\n self.assertEqual(torch_op(a, 2), torch.tensor(numpy_op(a_np, 2), device=device))\n\n def test_bitwise_shift_float(self, device):\n ops = [\n (torch.bitwise_left_shift, lambda x, y: x * 2. ** y),\n (operator.lshift, lambda x, y: x * 2. ** y),\n (torch.bitwise_right_shift, lambda x, y: x / 2. ** y),\n (operator.rshift, lambda x, y: x / 2. ** y),\n ]\n for torch_op, expected_op in ops:\n # int tensor x float\n a = torch.tensor([19, -20, -21, 22], dtype=torch.int64, device=device)\n self.assertEqual(torch_op(a, 1.8), torch.floor(expected_op(a, 1)).to(a.dtype))\n # float tensor x int scalar\n a = torch.tensor([19.1, -20.2, -21.3, 22.4], dtype=torch.float32, device=device)\n self.assertEqual(torch_op(a, 2), expected_op(a, 2))\n # float tensor x float scalar\n a = torch.tensor([19.1, -20.2, -21.3, 22.4], dtype=torch.float32, device=device)\n self.assertEqual(torch_op(a, 2.2), expected_op(a, 2.2))\n\n @onlyOnCPUAndCUDA\n @dtypes(*list(product(torch.testing.get_all_dtypes(include_complex=False),\n torch.testing.get_all_dtypes(include_complex=False))))\n def test_heaviside(self, device, dtypes):\n input_dtype = dtypes[0]\n values_dtype = dtypes[1]\n\n rng = np.random.default_rng()\n input = np.array(rng.integers(-10, 10, size=10),\n dtype=torch_to_numpy_dtype_dict[input_dtype if (input_dtype != torch.bfloat16) else torch.float64])\n input[0] = input[3] = input[7] = 0\n values = np.array(rng.integers(-10, 10, size=10),\n dtype=torch_to_numpy_dtype_dict[values_dtype if (values_dtype != torch.bfloat16) else torch.float64])\n np_result = torch.from_numpy(np.heaviside(input, values)).to(device=device, dtype=input_dtype)\n\n input = torch.from_numpy(input).to(device=device, dtype=input_dtype)\n values = torch.from_numpy(values).to(device=device, dtype=values_dtype)\n out = torch.empty_like(input)\n\n if input_dtype == values_dtype:\n torch_result = torch.heaviside(input, values)\n self.assertEqual(np_result, torch_result)\n\n torch_result = input.heaviside(values)\n self.assertEqual(np_result, torch_result)\n\n torch.heaviside(input, values, out=out)\n self.assertEqual(np_result, out)\n\n input.heaviside_(values)\n self.assertEqual(np_result, input)\n else:\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for tensors with different dtypes.'):\n torch.heaviside(input, values)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for tensors with different dtypes.'):\n input.heaviside(values)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for tensors with different dtypes.'):\n torch.heaviside(input, values, out=out)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for tensors with different dtypes.'):\n input.heaviside_(values)\n\n @onlyCUDA\n def test_heaviside_cross_device(self, device):\n x = torch.tensor([-9, 5, 0, 6, -2, 2], device=device)\n y = torch.tensor(0)\n result = torch.heaviside(x, y)\n expect = torch.tensor([0, 1, 0, 1, 0, 1], device=device)\n self.assertEqual(result, expect)\n\n result = torch.heaviside(y, x)\n expect = torch.tensor([-9, 5, 0, 6, -2, 2], device=device)\n self.assertEqual(result, expect)\n\n x = torch.tensor([-9, 5, 0, 6, -2, 2])\n y = torch.tensor(0, device=device)\n with self.assertRaisesRegex(RuntimeError, 'Expected all tensors to be on the same device'):\n torch.heaviside(x, y)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected all tensors to be on the same device'):\n torch.heaviside(y, x)\n\n @dtypes(*list(product(torch.testing.get_all_complex_dtypes(),\n torch.testing.get_all_complex_dtypes())))\n def test_heaviside_complex(self, device, dtypes):\n input_dtype = dtypes[0]\n values_dtype = dtypes[1]\n\n data = (complex(0, -6), complex(-1, 3), complex(1, 1))\n input = torch.tensor(data, device=device, dtype=input_dtype)\n values = torch.tensor(data, device=device, dtype=values_dtype)\n out = torch.empty_like(input)\n real = input.real\n\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for complex tensors.'):\n torch.heaviside(input, real)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for complex tensors.'):\n real.heaviside(values)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for complex tensors.'):\n input.heaviside_(values)\n with self.assertRaisesRegex(RuntimeError, 'heaviside is not yet implemented for complex tensors.'):\n torch.heaviside(real, real, out=out)\n\n def _test_logical(self, device, dtypes, op, a_, b_, expected_res_):\n expected_res = torch.tensor(expected_res_, dtype=dtypes[0], device=device)\n a = torch.tensor(a_, dtype=dtypes[0], device=device)\n b = torch.tensor(b_, dtype=dtypes[1], device=device)\n\n # new tensor\n self.assertEqual(expected_res.bool(), getattr(a, op)(b))\n # out\n c = torch.empty(0, dtype=torch.bool, device=device)\n getattr(torch, op)(a, b, out=c)\n self.assertEqual(expected_res.bool(), c)\n\n # in-place\n # TODO: remove when different dtypes as operands are supported\n if dtypes[0] != dtypes[1]:\n with self.assertRaises(RuntimeError):\n getattr(a, op + '_')(b)\n return\n\n getattr(a, op + '_')(b)\n self.assertEqual(expected_res, a)\n\n @dtypes(*product(torch.testing.get_all_dtypes(), torch.testing.get_all_dtypes()))\n def test_logical_xor(self, device, dtypes):\n self._test_logical(device, dtypes, 'logical_xor', [10, 0, 1, 0], [1, 0, 0, 10], [0, 0, 1, 1])\n\n @dtypes(*product(torch.testing.get_all_dtypes(), torch.testing.get_all_dtypes()))\n def test_logical_and(self, device, dtypes):\n self._test_logical(device, dtypes, 'logical_and', [10, 0, 1, 0], [1, 0, 0, 10], [1, 0, 0, 0])\n\n @dtypes(*product(torch.testing.get_all_dtypes(), torch.testing.get_all_dtypes()))\n def test_logical_or(self, device, dtypes):\n self._test_logical(device, dtypes, 'logical_or', [10, 0, 1, 0], [1, 0, 0, 10], [1, 0, 1, 1])\n\n def test_remainder_overflow(self, device):\n # Check Integer Overflows\n x = torch.tensor(23500, dtype=torch.int64, device=device)\n q = 392486996410368\n self.assertEqual(x % q, x)\n self.assertEqual(-x % q, q - x)\n self.assertEqual(x % -q, x - q)\n self.assertEqual(-x % -q, -x)\n\n def test_rpow(self, device):\n m = torch.randn(10, 10, device=device)\n self.assertEqual(torch.pow(2, m), 2**m)\n\n # test with scalar\n m = torch.randn(1, device=device).squeeze()\n assert m.dim() == 0, \"m is intentionally a scalar\"\n self.assertEqual(torch.pow(2, m), 2**m)\n\n @onlyCPU\n def test_ldexp(self, device):\n # random values\n mantissas = torch.randn(64, device=device)\n exponents = torch.randint(-31, 31, (64,), device=device, dtype=torch.int32)\n\n # basic test\n np_outcome = np.ldexp(mantissas.numpy(), exponents.numpy())\n pt_outcome_1 = torch.ldexp(mantissas, exponents)\n pt_outcome_2 = mantissas.ldexp(exponents)\n self.assertEqual(np_outcome, pt_outcome_1)\n self.assertEqual(np_outcome, pt_outcome_2)\n mantissas.ldexp_(exponents)\n self.assertEqual(np_outcome, mantissas)\n\n # test bounds\n mantissas = torch.tensor([float('inf'), float('-inf'), float('inf'), float('nan')], device=device)\n exponents = torch.randint(0, 31, (4,), device=device, dtype=torch.int32)\n np_outcome = np.ldexp(mantissas.numpy(), exponents.numpy())\n pt_outcome = torch.ldexp(mantissas, exponents)\n self.assertEqual(np_outcome, pt_outcome)\n\n @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble)\n def test_lerp(self, device, dtype):\n start_end_weight_shapes = [(), (5,), (5, 5)]\n for shapes in product(start_end_weight_shapes, start_end_weight_shapes, start_end_weight_shapes):\n start = torch.randn(shapes[0], device=device, dtype=dtype)\n end = torch.randn(shapes[1], device=device, dtype=dtype)\n\n # Tensor weights\n weights = [torch.randn(shapes[2], device=device, dtype=dtype), random.random()]\n if dtype.is_complex:\n weights += [complex(0, 1), complex(0.4, 1.2)]\n\n for weight in weights:\n actual = torch.lerp(start, end, weight)\n actual_method = start.lerp(end, weight)\n self.assertEqual(actual, actual_method)\n actual_out = torch.tensor(1., dtype=dtype, device=device)\n torch.lerp(start, end, weight, out=actual_out)\n self.assertEqual(actual, actual_out)\n expected = start + weight * (end - start)\n self.assertEqual(expected, actual)\n\n def _test_logaddexp(self, device, dtype, base2):\n if base2:\n ref_func = np.logaddexp2\n our_func = torch.logaddexp2\n else:\n ref_func = np.logaddexp\n our_func = torch.logaddexp\n\n def _test_helper(a, b):\n ref = ref_func(a.cpu().numpy(), b.cpu().numpy())\n v = our_func(a, b)\n self.assertEqual(ref, v)\n\n # simple test\n a = torch.randn(64, 2, dtype=dtype, device=device) - 0.5\n b = torch.randn(64, 2, dtype=dtype, device=device) - 0.5\n _test_helper(a, b)\n _test_helper(a[:3], b[:3])\n\n # large value test for numerical stability\n a *= 10000\n b *= 10000\n _test_helper(a, b)\n _test_helper(a[:3], b[:3])\n\n a = torch.tensor([float('inf'), float('-inf'), float('inf'), float(\"nan\")], dtype=dtype, device=device)\n b = torch.tensor([float('inf'), float('-inf'), float('-inf'), float(\"nan\")], dtype=dtype, device=device)\n _test_helper(a, b)\n\n @dtypes(torch.float32, torch.float64)\n def test_logaddexp(self, device, dtype):\n self._test_logaddexp(device, dtype, base2=False)\n\n @dtypes(torch.float32, torch.float64)\n def test_logaddexp2(self, device, dtype):\n self._test_logaddexp(device, dtype, base2=True)\n\n def test_add(self, device):\n dtypes = [torch.float, torch.double] + torch.testing.get_all_complex_dtypes()\n for dtype in dtypes:\n # [res] torch.add([res,] tensor1, tensor2)\n m1 = torch.randn(100, 100, dtype=dtype, device=device)\n v1 = torch.randn(100, dtype=dtype, device=device)\n\n # contiguous\n res1 = torch.add(m1[4], v1)\n res2 = res1.clone().zero_()\n for i in range(m1.size(1)):\n res2[i] = m1[4, i] + v1[i]\n self.assertEqual(res1, res2)\n\n m1 = torch.randn(100, 100, device=device)\n v1 = torch.randn(100, device=device)\n\n # non-contiguous\n res1 = torch.add(m1[:, 4], v1)\n res2 = res1.clone().zero_()\n for i in range(m1.size(0)):\n res2[i] = m1[i, 4] + v1[i]\n self.assertEqual(res1, res2)\n\n # [res] torch.add([res,] tensor, value)\n m1 = torch.randn(10, 10, device=device)\n\n # contiguous\n res1 = m1.clone()\n res1[3].add_(2)\n res2 = m1.clone()\n for i in range(m1.size(1)):\n res2[3, i] = res2[3, i] + 2\n self.assertEqual(res1, res2)\n\n # non-contiguous\n m1 = torch.randn(10, 10, device=device)\n res1 = m1.clone()\n res1[:, 3].add_(2)\n res2 = m1.clone()\n for i in range(m1.size(0)):\n res2[i, 3] = res2[i, 3] + 2\n self.assertEqual(res1, res2)\n\n # inter-type\n m1 = torch.randn(10, 10, dtype=dtype, device=device)\n self.assertEqual(m1 + 3, m1 + torch.tensor(3))\n self.assertEqual(3 + m1, torch.tensor(3) + m1)\n\n # contiguous + non-contiguous\n m1 = torch.randn(10, 10, dtype=dtype, device=device)\n m2 = torch.randn(10, 10, dtype=dtype, device=device).t()\n res = m1 + m2\n self.assertTrue(res.is_contiguous())\n self.assertEqual(res, m1 + m2.contiguous())\n\n # 1d + empty\n m1 = torch.tensor([1.0], dtype=dtype, device=device)\n m2 = torch.tensor([], dtype=dtype, device=device)\n self.assertEqual(m1 + m2, [])\n\n # inter-type unint8\n one = torch.tensor(1, dtype=torch.uint8, device=device)\n self.assertEqual(torch.add(one, 1), 2)\n self.assertEqual(torch.add(one, 1).dtype, torch.uint8)\n\n # bool\n m1 = torch.tensor([True, False, False, True, False, False], dtype=torch.bool, device=device)\n m2 = torch.tensor([True, True, False, False, False, True], dtype=torch.bool, device=device)\n expected = torch.tensor([True, True, False, True, False, True], dtype=torch.bool, device=device)\n self.assertEqual(m1 + m2, expected)\n\n # fused multiply add\n a = torch.zeros(2, 3, dtype=torch.bool, device=device)\n res = torch.add(a, a, alpha=0)\n expected = torch.zeros(2, 3, device=device).bool()\n self.assertEqual(res, expected)\n\n # bfloat16\n m1 = torch.tensor([1., 2.], dtype=torch.bfloat16)\n m2 = torch.tensor([3., 4.], dtype=torch.bfloat16)\n self.assertEqual(m1 + m2, torch.tensor([4., 6.], dtype=torch.bfloat16))\n\n # different alpha types\n m1 = torch.tensor([2 + 3j, 4 + 5j], dtype=torch.complex64, device=device)\n m2 = torch.tensor([4 + 5j, 2 + 3j], dtype=torch.complex64, device=device)\n # add complex numbers with float alpha\n res = torch.add(m1, m2, alpha=0.1)\n expected = torch.tensor([2.4000 + 3.5000j, 4.2000 + 5.3000j], dtype=torch.complex64, device=device)\n self.assertEqual(res, expected)\n\n # add complex numbers with complex alpha\n res = torch.add(m1, m2, alpha=complex(0.1, 0.2))\n expected = torch.tensor([1.4000 + 4.3000j, 3.6000 + 5.7000j], dtype=torch.complex64, device=device)\n self.assertEqual(res, expected)\n\n # add complex numbers with integer alpha\n res = torch.add(m1, m2, alpha=2)\n expected = torch.tensor([10. + 13.j, 8. + 11.j], dtype=torch.complex64, device=device)\n self.assertEqual(res, expected)\n\n # mismatched alpha\n m1 = torch.tensor([1], dtype=torch.int8, device=device)\n m2 = torch.tensor([2], dtype=torch.int8, device=device)\n self.assertRaisesRegex(RuntimeError,\n r\"Boolean alpha only supported for Boolean results\\.\",\n lambda: torch.add(m1, m2, alpha=True))\n self.assertRaisesRegex(RuntimeError,\n r\"For integral input tensors, argument alpha must not be a floating point number\\.\",\n lambda: torch.add(m1, m2, alpha=1.0))\n\n # mismatched alpha, float / double tensor and complex alpha\n msg = r\"For non-complex input tensors, argument alpha must not be a complex number\\.\"\n m1 = torch.tensor([3., 4.], device=device)\n m2 = torch.tensor([4., 3.], device=device)\n self.assertRaisesRegex(RuntimeError, msg,\n lambda: torch.add(m1, m2, alpha=complex(0.1, 0.2)))\n\n m1 = torch.tensor([3., 4.], dtype=torch.double, device=device)\n m2 = torch.tensor([4., 3.], dtype=torch.double, device=device)\n self.assertRaisesRegex(RuntimeError, msg,\n lambda: torch.add(m1, m2, alpha=complex(0.1, 0.2)))\n\n # complex\n m1 = torch.tensor((4.0000 + 4.0000j), dtype=torch.complex64)\n m2 = torch.tensor(4., dtype=torch.float64)\n self.assertRaisesRegex(RuntimeError, r\"result type ComplexFloat can't be cast to the desired output type Double\",\n lambda: torch.add(m1, m1, out=m2))\n\n @onlyCUDA\n def test_addsub_half_tensor(self, device):\n x = torch.tensor([60000.0], dtype=torch.half, device=device)\n for op, y, alpha in (\n (torch.add, torch.tensor([-60000.0], dtype=torch.half, device=device), 2),\n (torch.sub, torch.tensor([60000.0], dtype=torch.half, device=device), 2),\n (torch.add, -70000.0, 1),\n (torch.sub, 70000.0, 1),\n ):\n actual = op(x, y, alpha=alpha)\n self.assertTrue(not (actual.isnan() or actual.isinf()))\n\n def test_sub_typing(self, device):\n m1 = torch.tensor([True, False, False, True, False, False], dtype=torch.bool, device=device)\n m2 = torch.tensor([True, True, False, False, False, True], dtype=torch.bool, device=device)\n self.assertRaisesRegex(RuntimeError,\n r\"Subtraction, the `\\-` operator, with two bool tensors is not supported. \"\n r\"Use the `\\^` or `logical_xor\\(\\)` operator instead.\",\n lambda: m1 - m2)\n self.assertRaisesRegex(RuntimeError,\n r\"Subtraction, the `\\-` operator, with a bool tensor is not supported. \"\n r\"If you are trying to invert a mask, use the `\\~` or `logical_not\\(\\)` operator instead.\",\n lambda: 1 - m1)\n self.assertRaisesRegex(RuntimeError,\n r\"Subtraction, the `\\-` operator, with a bool tensor is not supported. \"\n r\"If you are trying to invert a mask, use the `\\~` or `logical_not\\(\\)` operator instead.\",\n lambda: m2 - 1)\n\n # mismatched alpha\n m1 = torch.tensor([1], dtype=torch.int8, device=device)\n m2 = torch.tensor([2], dtype=torch.int8, device=device)\n self.assertRaisesRegex(RuntimeError,\n r\"Boolean alpha only supported for Boolean results\\.\",\n lambda: torch.sub(m1, m2, alpha=True))\n self.assertRaisesRegex(RuntimeError,\n r\"For integral input tensors, argument alpha must not be a floating point number\\.\",\n lambda: torch.sub(m1, m2, alpha=1.0))\n\n def test_mul(self, device):\n m1 = torch.randn(10, 10, device=device)\n res1 = m1.clone()\n res1[:, 3].mul_(2)\n res2 = m1.clone()\n for i in range(res1.size(0)):\n res2[i, 3] = res2[i, 3] * 2\n self.assertEqual(res1, res2)\n\n a1 = torch.tensor([True, False, False, True], dtype=torch.bool, device=device)\n a2 = torch.tensor([True, False, True, False], dtype=torch.bool, device=device)\n self.assertEqual(a1 * a2, torch.tensor([True, False, False, False], dtype=torch.bool, device=device))\n\n if device == 'cpu':\n a1 = torch.tensor([0.1, 0.1], dtype=torch.bfloat16, device=device)\n a2 = torch.tensor([1.1, 0.1], dtype=torch.bfloat16, device=device)\n self.assertEqual(a1 * a2, torch.tensor([0.11, 0.01], dtype=torch.bfloat16, device=device), atol=0.01, rtol=0)\n self.assertEqual(a1.mul(a2), a1 * a2)\n\n def test_bool_tensor_comparison_ops(self, device):\n a = torch.tensor([True, False, True, False, True, False], dtype=torch.bool, device=device)\n b = torch.tensor([True, False, True, True, True, True], dtype=torch.bool, device=device)\n self.assertEqual(a == b, torch.tensor([1, 1, 1, 0, 1, 0], dtype=torch.bool, device=device))\n self.assertEqual(a != b, torch.tensor([0, 0, 0, 1, 0, 1], dtype=torch.bool, device=device))\n self.assertEqual(a < b, torch.tensor([0, 0, 0, 1, 0, 1], dtype=torch.bool, device=device))\n self.assertEqual(a > b, torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.bool, device=device))\n self.assertEqual(a >= b, torch.tensor([1, 1, 1, 0, 1, 0], dtype=torch.bool, device=device))\n self.assertEqual(a <= b, torch.tensor([1, 1, 1, 1, 1, 1], dtype=torch.bool, device=device))\n self.assertEqual(a > False, torch.tensor([1, 0, 1, 0, 1, 0], dtype=torch.bool, device=device))\n self.assertEqual(a == torch.tensor(True, dtype=torch.bool, device=device),\n torch.tensor([1, 0, 1, 0, 1, 0], dtype=torch.bool, device=device))\n self.assertEqual(a == torch.tensor(0, dtype=torch.bool, device=device),\n torch.tensor([0, 1, 0, 1, 0, 1], dtype=torch.bool, device=device))\n self.assertFalse(a.equal(b))\n\n @dtypes(*torch.testing.get_all_dtypes(include_complex=False))\n def test_logical(self, device, dtype):\n if dtype != torch.bool:\n x = torch.tensor([1, 2, 3, 4], device=device, dtype=dtype)\n b = torch.tensor([2], device=device, dtype=dtype)\n self.assertEqual(x.lt(2), torch.tensor([True, False, False, False]))\n self.assertEqual(x.le(2), torch.tensor([True, True, False, False]))\n self.assertEqual(x.ge(2), torch.tensor([False, True, True, True]))\n self.assertEqual(x.gt(2), torch.tensor([False, False, True, True]))\n self.assertEqual(x.eq(2), torch.tensor([False, True, False, False]))\n self.assertEqual(x.ne(2), torch.tensor([True, False, True, True]))\n\n self.assertEqual(x.lt(b), torch.tensor([True, False, False, False]))\n self.assertEqual(x.le(b), torch.tensor([True, True, False, False]))\n self.assertEqual(x.ge(b), torch.tensor([False, True, True, True]))\n self.assertEqual(x.gt(b), torch.tensor([False, False, True, True]))\n self.assertEqual(x.eq(b), torch.tensor([False, True, False, False]))\n self.assertEqual(x.ne(b), torch.tensor([True, False, True, True]))\n else:\n x = torch.tensor([True, False, True, False], device=device)\n self.assertEqual(x.lt(True), torch.tensor([False, True, False, True]))\n self.assertEqual(x.le(True), torch.tensor([True, True, True, True]))\n self.assertEqual(x.ge(True), torch.tensor([True, False, True, False]))\n self.assertEqual(x.gt(True), torch.tensor([False, False, False, False]))\n self.assertEqual(x.eq(True), torch.tensor([True, False, True, False]))\n self.assertEqual(x.ne(True), torch.tensor([False, True, False, True]))\n\n def test_atan2(self, device):\n def _test_atan2_with_size(size, device):\n a = torch.rand(size=size, device=device, dtype=torch.double)\n b = torch.rand(size=size, device=device, dtype=torch.double)\n actual = a.atan2(b)\n x = a.view(-1)\n y = b.view(-1)\n expected = torch.tensor([math.atan2(x[i].item(), y[i].item()) for i in range(x.numel())],\n device=device, dtype=torch.double)\n self.assertEqual(expected, actual.view(-1), rtol=0, atol=0.02)\n\n _test_atan2_with_size((2, 2), device)\n _test_atan2_with_size((3, 3), device)\n _test_atan2_with_size((5, 5), device)\n\n def test_atan2_edgecases(self, device):\n def _test_atan2(x, y, expected, device, dtype):\n expected_tensor = torch.tensor([expected], dtype=dtype, device=device)\n x_tensor = torch.tensor([x], dtype=dtype, device=device)\n y_tensor = torch.tensor([y], dtype=dtype, device=device)\n actual = torch.atan2(y_tensor, x_tensor)\n self.assertEqual(expected_tensor, actual, rtol=0, atol=0.02)\n\n for dtype in [torch.float, torch.double]:\n _test_atan2(0, 0, 0, device, dtype)\n _test_atan2(0, 1, math.pi / 2, device, dtype)\n _test_atan2(0, -1, math.pi / -2, device, dtype)\n _test_atan2(-1, 0, math.pi, device, dtype)\n _test_atan2(1, 0, 0, device, dtype)\n _test_atan2(-1, -1, math.pi * -3 / 4 , device, dtype)\n _test_atan2(1, 1, math.pi / 4 , device, dtype)\n _test_atan2(1, -1, math.pi / -4 , device, dtype)\n _test_atan2(-1, 1, math.pi * 3 / 4 , device, dtype)\n\n def test_trapz(self, device):\n def test_dx(sizes, dim, dx, device):\n t = torch.randn(sizes, device=device)\n actual = torch.trapz(t, dx=dx, dim=dim)\n expected = np.trapz(t.cpu().numpy(), dx=dx, axis=dim)\n self.assertEqual(expected.shape, actual.shape)\n self.assertEqual(expected, actual, exact_dtype=False)\n\n def test_x(sizes, dim, x, device):\n t = torch.randn(sizes, device=device)\n actual = torch.trapz(t, x=torch.tensor(x, device=device), dim=dim)\n expected = np.trapz(t.cpu().numpy(), x=x, axis=dim)\n self.assertEqual(expected.shape, actual.shape)\n self.assertEqual(expected, actual.cpu(), exact_dtype=False)\n\n test_dx((2, 3, 4), 1, 1, device)\n test_dx((10, 2), 0, 0.1, device)\n test_dx((1, 10), 0, 2.3, device)\n test_dx((0, 2), 0, 1.0, device)\n test_dx((0, 2), 1, 1.0, device)\n test_x((2, 3, 4), 1, [1.0, 2.0, 3.0], device)\n test_x((10, 2), 0, [2.0, 3.0, 4.0, 7.0, 11.0, 14.0, 22.0, 26.0, 26.1, 30.3], device)\n test_x((1, 10), 0, [1.0], device)\n test_x((0, 2), 0, [], device)\n test_x((0, 2), 1, [1.0, 2.0], device)\n with self.assertRaisesRegex(\n IndexError,\n 'Dimension out of range'):\n test_x((2, 3), 2, [], device)\n test_dx((2, 3), 2, 1.0, device)\n with self.assertRaisesRegex(\n RuntimeError,\n 'There must be one `x` value for each sample point'):\n test_x((2, 3), 1, [1.0, 2.0], device)\n test_x((2, 3), 1, [1.0, 2.0, 3.0, 4.0], device)\n\n @dtypes(torch.double)\n def test_pow_scalar_overloads_mem_overlap(self, device, dtype):\n sz = 3\n doubles = torch.randn(2 * sz, dtype=dtype, device=device)\n self.check_internal_mem_overlap(\n lambda t: t.pow_(42), 1, dtype, device)\n self.unary_check_input_output_mem_overlap(\n doubles, sz, lambda input, out: torch.pow(input, 42, out=out))\n self.unary_check_input_output_mem_overlap(\n doubles, sz, lambda input, out: torch.pow(42, input, out=out))\n\n @dtypes(*list(product(torch.testing.get_all_dtypes(include_bool=False),\n torch.testing.get_all_dtypes(include_bool=False))))\n def test_float_power(self, device, dtypes):\n def to_np(value):\n if isinstance(value, torch.Tensor) and value.dtype == torch.bfloat16:\n return value.to(torch.float).cpu().numpy()\n return value.cpu().numpy() if isinstance(value, torch.Tensor) else value\n\n base_dtype = dtypes[0]\n exp_dtype = dtypes[1]\n out_dtype = torch.complex128 if base_dtype.is_complex or exp_dtype.is_complex else torch.float64\n\n base = make_tensor((30,), device, base_dtype, low=1, high=100)\n # Complex and real results do not agree between PyTorch and NumPy when computing negative and zero power of 0\n # Related: https://github.com/pytorch/pytorch/issues/48000\n # base[0] = base[3] = base[7] = 0\n exp = make_tensor((30,), device, exp_dtype, low=-2, high=2)\n exp[0] = exp[4] = exp[6] = 0\n\n expected = torch.from_numpy(np.float_power(to_np(base), to_np(exp)))\n\n exponents = [-2.8, -2, -1, -0.5, 0.5, 1, 2]\n complex_exponents = exponents + [-2.5j, -1.0j, 1.0j, 2.5j, 1.0 + 1.0j, -1.0 - 1.5j, 3.3j]\n\n for op in (torch.float_power, torch.Tensor.float_power, torch.Tensor.float_power_):\n\n # Case of Tensor x Tensor\n if op is torch.Tensor.float_power_ and base_dtype != out_dtype:\n with self.assertRaisesRegex(RuntimeError, \"operation's result requires dtype\"):\n op(base.clone(), exp)\n else:\n result = op(base.clone(), exp)\n self.assertEqual(expected, result)\n\n if op is torch.float_power:\n out = torch.empty_like(base).to(device=device, dtype=out_dtype)\n op(base, exp, out=out)\n self.assertEqual(expected, out)\n\n # Case of Tensor x Scalar\n for i in complex_exponents if exp_dtype.is_complex else exponents:\n out_dtype_scalar_exp = torch.complex128 if base_dtype.is_complex or type(i) == complex else torch.float64\n expected_scalar_exp = torch.from_numpy(np.float_power(to_np(base), i))\n\n if op is torch.Tensor.float_power_ and base_dtype != out_dtype_scalar_exp:\n with self.assertRaisesRegex(RuntimeError, \"operation's result requires dtype\"):\n op(base.clone(), i)\n else:\n result = op(base.clone(), i)\n self.assertEqual(expected_scalar_exp, result)\n\n if op is torch.float_power:\n out = torch.empty_like(base).to(device=device, dtype=out_dtype_scalar_exp)\n op(base, i, out=out)\n self.assertEqual(expected_scalar_exp, out)\n\n # Case of Scalar x Tensor\n for i in complex_exponents if base_dtype.is_complex else exponents:\n out_dtype_scalar_base = torch.complex128 if exp_dtype.is_complex or type(i) == complex else torch.float64\n expected_scalar_base = torch.from_numpy(np.float_power(i, to_np(exp)))\n\n result = torch.float_power(i, exp)\n self.assertEqual(expected_scalar_base, result)\n\n out = torch.empty_like(exp).to(device=device, dtype=out_dtype_scalar_base)\n torch.float_power(i, exp, out=out)\n self.assertEqual(expected_scalar_base, out)\n\n def test_float_power_exceptions(self, device):\n def _promo_helper(x, y):\n for i in (x, y):\n if type(i) == complex:\n return torch.complex128\n elif type(i) == torch.Tensor and i.is_complex():\n return torch.complex128\n return torch.double\n\n test_cases = ((torch.tensor([-2, -1, 0, 1, 2], device=device), -.25),\n (torch.tensor([-1.0j, 0j, 1.0j, 1.0 + 1.0j, -1.0 - 1.5j], device=device), 2.))\n for base, exp in test_cases:\n for out_dtype in (torch.long, torch.float, torch.double, torch.cdouble):\n out = torch.empty(1, device=device, dtype=out_dtype)\n required_dtype = _promo_helper(base, exp)\n\n if out.dtype == required_dtype:\n torch.float_power(base, exp, out=out)\n else:\n with self.assertRaisesRegex(RuntimeError, \"operation's result requires dtype\"):\n torch.float_power(base, exp, out=out)\n\n if base.dtype == required_dtype:\n torch.Tensor.float_power_(base.clone(), exp)\n else:\n with self.assertRaisesRegex(RuntimeError, \"operation's result requires dtype\"):\n torch.Tensor.float_power_(base.clone(), exp)\n\n @skipIf(not TEST_SCIPY, \"Scipy required for the test.\")\n @dtypes(*product(torch.testing.get_all_dtypes(include_complex=False, include_bfloat16=False),\n torch.testing.get_all_dtypes(include_complex=False, include_bfloat16=False)))\n def test_xlogy_xlog1py(self, device, dtypes):\n x_dtype, y_dtype = dtypes\n\n def out_variant_helper(torch_fn, x, y):\n expected = torch_fn(x, y)\n out = torch.empty_like(expected)\n torch_fn(x, y, out=out)\n self.assertEqual(expected, out)\n\n def xlogy_inplace_variant_helper(x, y):\n if x.dtype in torch.testing.get_all_int_dtypes() + [torch.bool]:\n with self.assertRaisesRegex(RuntimeError,\n \"can't be cast to the desired output type\"):\n x.clone().xlogy_(y)\n else:\n expected = torch.empty_like(x)\n torch.xlogy(x, y, out=expected)\n inplace_out = x.clone().xlogy_(y)\n self.assertEqual(expected, inplace_out)\n\n def test_helper(torch_fn, reference_fn, inputs, scalar=None):\n x, y, z = inputs\n torch_fn_partial = partial(torch_fn, x)\n reference_fn_partial = partial(reference_fn, x.cpu().numpy())\n self.compare_with_numpy(torch_fn_partial, reference_fn_partial, x, exact_dtype=False)\n self.compare_with_numpy(torch_fn_partial, reference_fn_partial, y, exact_dtype=False)\n self.compare_with_numpy(torch_fn_partial, reference_fn_partial, z, exact_dtype=False)\n\n val = scalar if scalar is not None else x\n out_variant_helper(torch_fn, val, x)\n out_variant_helper(torch_fn, val, y)\n out_variant_helper(torch_fn, val, z)\n\n # Tensor-Tensor Test (tensor of same and different shape)\n x = make_tensor((3, 2, 4, 5), device, x_dtype, low=0.5, high=1000)\n y = make_tensor((3, 2, 4, 5), device, y_dtype, low=0.5, high=1000)\n z = make_tensor((4, 5), device, y_dtype, low=0.5, high=1000)\n\n x_1p = make_tensor((3, 2, 4, 5), device, x_dtype, low=-0.5, high=1000)\n y_1p = make_tensor((3, 2, 4, 5), device, y_dtype, low=-0.5, high=1000)\n z_1p = make_tensor((4, 5), device, y_dtype, low=-0.5, high=1000)\n\n xlogy_fns = torch.xlogy, scipy.special.xlogy\n xlog1py_fns = torch.special.xlog1py, scipy.special.xlog1py\n\n test_helper(*xlogy_fns, (x, y, z))\n xlogy_inplace_variant_helper(x, x)\n xlogy_inplace_variant_helper(x, y)\n xlogy_inplace_variant_helper(x, z)\n test_helper(*xlog1py_fns, (x_1p, y_1p, z_1p))\n\n # Scalar-Tensor Test\n test_helper(*xlogy_fns, (x, y, z), 3.14)\n test_helper(*xlog1py_fns, (x_1p, y_1p, z_1p), 3.14)\n\n # Special Values Tensor-Tensor\n t = torch.tensor([-1., 0., 1., 2., float('inf'), -float('inf'), float('nan')], device=device)\n zeros = torch.zeros(7, dtype=y_dtype, device=device)\n\n def test_zeros_special_helper(torch_fn, reference_fn, scalar=False):\n zeros_t = 0 if scalar else zeros\n zeros_np = 0 if scalar else zeros.cpu().numpy()\n torch_fn_partial = partial(torch_fn, zeros_t)\n reference_fn_partial = partial(reference_fn, zeros_np)\n self.compare_with_numpy(torch_fn_partial, reference_fn_partial, t, exact_dtype=False)\n out_variant_helper(torch_fn, zeros_t, t)\n\n test_zeros_special_helper(*xlogy_fns)\n xlogy_inplace_variant_helper(zeros, t)\n test_zeros_special_helper(*xlog1py_fns)\n\n # Special Values Scalar-Tensor\n test_zeros_special_helper(*xlogy_fns, scalar=True)\n test_zeros_special_helper(*xlog1py_fns, scalar=True)\n\n def test_xlogy_xlog1py_scalar_type_promotion(self, device):\n # Test that python numbers don't participate in type promotion at the same\n # priority level as 0-dim tensors\n t = torch.randn((), dtype=torch.float32, device=device)\n\n self.assertEqual(t.dtype, torch.xlogy(t, 5).dtype)\n self.assertEqual(t.dtype, torch.xlogy(t, 5.).dtype)\n self.assertEqual(t.dtype, torch.special.xlog1py(t, 5).dtype)\n self.assertEqual(t.dtype, torch.special.xlog1py(t, 5.).dtype)\n\n self.assertEqual(t.dtype, torch.xlogy(5, t).dtype)\n self.assertEqual(t.dtype, torch.xlogy(5., t).dtype)\n self.assertEqual(t.dtype, torch.special.xlog1py(5, t).dtype)\n self.assertEqual(t.dtype, torch.special.xlog1py(5., t).dtype)\n\n @skipIf(not TEST_SCIPY, \"Scipy required for the test.\")\n def test_xlogy_xlog1py_bfloat16(self, device):\n def _compare_helper(x, y, torch_fn, reference_fn):\n x_np = x if isinstance(x, float) else x.cpu().to(torch.float).numpy()\n y_np = y if isinstance(y, float) else y.cpu().to(torch.float).numpy()\n expected = torch.from_numpy(reference_fn(x_np, y_np))\n actual = torch_fn(x, y)\n self.assertEqual(expected, actual, exact_dtype=False)\n\n x_dtype, y_dtype = torch.bfloat16, torch.bfloat16\n\n # Tensor-Tensor Test (tensor of same and different shape)\n x = make_tensor((3, 2, 4, 5), device, x_dtype, low=0.5, high=1000)\n y = make_tensor((3, 2, 4, 5), device, y_dtype, low=0.5, high=1000)\n z = make_tensor((4, 5), device, y_dtype, low=0.5, high=1000)\n\n x_1p = make_tensor((3, 2, 4, 5), device, x_dtype, low=-0.8, high=1000)\n y_1p = make_tensor((3, 2, 4, 5), device, y_dtype, low=-0.8, high=1000)\n z_1p = make_tensor((4, 5), device, y_dtype, low=-0.8, high=1000)\n\n xlogy_fns = torch.xlogy, scipy.special.xlogy\n xlog1py_fns = torch.special.xlog1py, scipy.special.xlog1py\n\n _compare_helper(x, x, *xlogy_fns)\n _compare_helper(x, y, *xlogy_fns)\n _compare_helper(x, z, *xlogy_fns)\n _compare_helper(x, 3.14, *xlogy_fns)\n _compare_helper(y, 3.14, *xlogy_fns)\n _compare_helper(z, 3.14, *xlogy_fns)\n\n _compare_helper(x_1p, x_1p, *xlog1py_fns)\n _compare_helper(x_1p, y_1p, *xlog1py_fns)\n _compare_helper(x_1p, z_1p, *xlog1py_fns)\n _compare_helper(x_1p, 3.14, *xlog1py_fns)\n _compare_helper(y_1p, 3.14, *xlog1py_fns)\n _compare_helper(z_1p, 3.14, *xlog1py_fns)\n\n # Special Values Tensor-Tensor\n t = torch.tensor([-1., 0., 1., 2., float('inf'), -float('inf'), float('nan')], device=device)\n zeros = torch.tensor(7, dtype=y_dtype, device=device)\n\n _compare_helper(t, zeros, *xlogy_fns)\n _compare_helper(t, 0., *xlogy_fns)\n\n _compare_helper(t, zeros, *xlog1py_fns)\n _compare_helper(t, 0., *xlog1py_fns)\n\n @dtypes(*product(torch.testing.get_all_dtypes(include_complex=False,\n include_half=False, include_bfloat16=False),\n torch.testing.get_all_dtypes(include_complex=False,\n include_half=False, include_bfloat16=False)))\n @skipIf(not TEST_SCIPY, \"Scipy required for the test.\")\n def test_zeta(self, device, dtypes):\n x_dtype, q_dtype = dtypes\n\n def test_helper(x, q):\n x_np = x if isinstance(x, float) else x.cpu().numpy()\n q_np = q if isinstance(q, float) else q.cpu().numpy()\n expected = torch.from_numpy(scipy.special.zeta(x_np, q_np))\n actual = torch.special.zeta(x, q)\n\n rtol, atol = None, None\n if self.device_type == 'cpu':\n rtol, atol = 1e-6, 1e-6\n self.assertEqual(expected, actual, rtol=rtol, atol=atol, exact_dtype=False)\n\n # x tensor - q tensor same size\n x = make_tensor((2, 3, 4), device, x_dtype)\n q = make_tensor((2, 3, 4), device, q_dtype)\n test_helper(x, q)\n\n # x tensor - q tensor broadcast lhs\n x = make_tensor((2, 1, 4), device, x_dtype)\n q = make_tensor((2, 3, 4), device, q_dtype)\n test_helper(x, q)\n\n # x tensor - q tensor broadcast rhs\n x = make_tensor((2, 3, 4), device, x_dtype)\n q = make_tensor((2, 1, 4), device, q_dtype)\n test_helper(x, q)\n\n # x tensor - q tensor broadcast all\n x = make_tensor((2, 3, 1), device, x_dtype)\n q = make_tensor((2, 1, 4), device, q_dtype)\n test_helper(x, q)\n\n # x scalar - q tensor\n for x in np.linspace(-5, 5, num=10).tolist():\n if not q_dtype.is_floating_point:\n q_dtype = torch.get_default_dtype()\n q = make_tensor((2, 3, 4), device, q_dtype)\n test_helper(x, q)\n\n # x tensor - q scalar\n for q in np.linspace(-5, 5, num=10).tolist():\n if not x_dtype.is_floating_point:\n x_dtype = torch.get_default_dtype()\n x = make_tensor((2, 3, 4), device, x_dtype)\n test_helper(x, q)\n\n\ntensor_binary_ops = [\n '__lt__', '__le__',\n '__gt__', '__ge__',\n '__eq__', '__ne__',\n\n '__add__', '__radd__', '__iadd__',\n '__sub__', '__rsub__', '__isub__',\n '__mul__', '__rmul__', '__imul__',\n '__matmul__', '__rmatmul__',\n '__truediv__', '__rtruediv__', '__itruediv__',\n '__floordiv__', '__rfloordiv__', '__ifloordiv__',\n '__mod__', '__rmod__', '__imod__',\n '__pow__', '__rpow__', '__ipow__',\n '__lshift__', '__rlshift__', '__ilshift__',\n '__rshift__', '__rrshift__', '__irshift__',\n '__and__', '__iand__',\n '__xor__', '__ixor__',\n '__or__', '__ior__',\n\n # Unsupported operators\n # '__imatmul__',\n # '__divmod__', '__rdivmod__', '__idivmod__',\n # '__rand__', '__ror__', '__rxor__',\n]\n\n# Test that binary math operations return NotImplemented for unknown types.\ndef generate_not_implemented_tests(cls):\n class UnknownType:\n pass\n\n # TODO: refactor to inline these\n _types = [\n torch.half, torch.float, torch.double,\n torch.int8, torch.short, torch.int, torch.long,\n torch.uint8\n ]\n\n # TODO: refactor to use make_tensor\n def _small_2d(dtype, device, has_zeros=True, fill_ones=False, oneish=False):\n t = _make_tensor((5, 5), dtype, device, fill_ones=fill_ones)\n if oneish:\n return t.clamp(min=_number(.99, 1, dtype), max=1.01)\n if not has_zeros:\n return t.clamp(min=(_number(_div_min, 1, dtype)))\n return t\n\n def create_test_func(op):\n @dtypes(*_types)\n def test(self, device, dtype):\n # Generate the inputs\n tensor = _small_2d(dtype, device)\n\n # Runs the tensor op on the device\n result = getattr(tensor, op)(UnknownType())\n self.assertEqual(result, NotImplemented)\n return test\n\n for op in tensor_binary_ops:\n test_name = \"test_{}_not_implemented\".format(op)\n assert not hasattr(cls, test_name), \"{0} already in {1}\".format(\n test_name, cls.__name__)\n\n setattr(cls, test_name, create_test_func(op))\n\n\ngenerate_not_implemented_tests(TestBinaryUfuncs)\ninstantiate_device_type_tests(TestBinaryUfuncs, globals())\n\nif __name__ == '__main__':\n run_tests()\n" ]
[ [ "torch.fmod", "torch.randint", "torch.max", "torch.zeros", "torch.testing._internal.common_utils.iter_indices", "torch.testing.get_all_complex_dtypes", "torch.bitwise_xor", "torch.lcm", "torch.where", "torch.device", "torch.pow", "numpy.right_shift", "torch.sqrt", "torch.randn", "torch.logical_xor", "numpy.copysign", "torch.empty_like", "torch.min", "torch.floor_divide", "numpy.array", "torch.testing._internal.common_utils.run_tests", "torch.atan2", "torch.cuda.device", "torch.testing.get_all_fp_dtypes", "torch.testing.get_all_dtypes", "torch.testing.all_types_and_complex_and", "torch.result_type", "torch.testing._internal.common_utils.set_default_dtype", "numpy.divide", "torch.ldexp", "torch.testing._internal.common_device_type.skipIf", "torch.tensor", "torch.divide", "torch.testing._internal.common_device_type.deviceCountAtLeast", "torch.rand", "torch.heaviside", "torch.zeros_like", "torch.is_tensor", "torch.testing._internal.common_device_type.dtypes", "numpy.errstate", "torch.bitwise_and", "torch.sub", "torch.trapz", "torch.testing._internal.common_device_type.dtypesIfCPU", "torch.float_power", "torch.randn_like", "numpy.linspace", "torch.iinfo", "torch.testing.get_all_int_dtypes", "torch.full_like", "torch.finfo", "numpy.random.default_rng", "torch.ones", "torch.add", "torch.from_numpy", "torch.arange", "torch.nextafter", "torch.true_divide", "torch.special.zeta", "torch.bitwise_or", "numpy.left_shift", "torch.testing._internal.common_device_type.precisionOverride", "torch.special.xlog1py", "numpy.true_divide", "torch.remainder", "numpy.random.randn", "torch.jit.script", "torch.Size", "torch.testing._internal.common_utils.make_tensor", "torch.get_default_dtype", "torch.lerp", "numpy.heaviside", "torch.empty", "torch.xlogy", "torch.copysign", "torch.hypot", "torch.gcd", "torch.promote_types", "torch.isnan", "numpy.gcd", "torch.testing._internal.common_device_type.dtypesIfCUDA", "torch.testing.get_all_math_dtypes", "numpy.lcm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rkeulemans/exercise_public
[ "5f8020198b8b234169eea4d5e08c98344438de5d" ]
[ "helpers.py" ]
[ "from sympy import Rational, Symbol, latex, UnevaluatedExpr\nimport sympy as sp\nimport numpy as np\n\nu = lambda x : UnevaluatedExpr(x)\n\n# Helper functions\ndef explain_add(a, b):\n assert(np.shape(a) == np.shape(b))\n rows, columns = np.shape(a)\n return sp.Matrix([[Symbol(f\"({latex(u(a[i,j]))} + {latex(u(b[i,j]))})\") for j in range(columns)] for i in range(rows)])\n\ndef symbolic_matrix(character, rows, columns):\n # row or column vector\n if rows == 1:\n return sp.Matrix([[Symbol(f\"{{{character}}}_{{{j+1}}}\") for j in range(columns)] for i in range(rows)]) \n if columns == 1:\n return sp.Matrix([[Symbol(f\"{{{character}}}_{{{i+1}}}\") for j in range(columns)] for i in range(rows)]) \n return sp.Matrix([[Symbol(f\"{{{character}}}_{{{i+1}, {j+1}}}\") for j in range(columns)] for i in range(rows)])\n\ndef explain_multiply(a, b):\n # #rows in b == #columns in a\n assert(np.shape(a)[1] == np.shape(b)[0])\n rows = np.shape(a)[0]\n columns = np.shape(b)[1]\n result = np.empty(shape=(rows, columns), dtype=object)\n for i in range(rows):\n row = a[i,:]\n for j in range(columns):\n column = b[:,j]\n zipped = zip(row, column)\n mapped = list(map(lambda t: f\"{latex(u(t[0]))} \\cdot {latex(u(t[1]))}\", zipped))\n s = Symbol(\"\") \n result[i, j] = Symbol(\" + \".join(mapped), evaluate=False)\n \n return sp.Matrix(result)" ]
[ [ "numpy.shape", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
galactics/space-command
[ "496b054883c6464bcd8d73d72c8145ae80606336", "496b054883c6464bcd8d73d72c8145ae80606336" ]
[ "space/station.py", "space/passes.py" ]
[ "import logging\nfrom numpy import degrees, pi, radians\n\nfrom beyond.frames import get_frame, create_station\nfrom beyond.errors import UnknownFrameError\n\nfrom .wspace import ws\nfrom .utils import dms2deg, deg2dms\n\n\nlog = logging.getLogger(__name__)\n\n\nclass StationDb:\n def __new__(cls):\n\n if not hasattr(cls, \"_instance\"):\n # Singleton\n cls._instance = super().__new__(cls)\n\n return cls._instance\n\n @classmethod\n def list(cls):\n\n self = cls()\n\n if not hasattr(self, \"_stations\"):\n\n self._stations = {}\n for abbr, charact in ws.config[\"stations\"].items():\n\n charact[\"parent_frame\"] = get_frame(charact[\"parent_frame\"])\n full_name = charact.pop(\"name\")\n mask = charact.get(\"mask\")\n if mask:\n # reverse direction of the mask to put it in counterclockwise\n # to comply with the mathematical definition\n charact[\"mask\"] = (\n (2 * pi - radians(mask[\"azims\"][::-1])),\n radians(mask[\"elevs\"][::-1]),\n )\n\n # Deletion of all unknown characteristics from the charact dict\n # and conversion to object attributes (they may be used by addons)\n extra_charact = {}\n for key in list(charact.keys()):\n if key not in (\"parent_frame\", \"latlonalt\", \"mask\"):\n extra_charact[key] = charact.pop(key)\n\n self._stations[abbr] = create_station(abbr, **charact)\n self._stations[abbr].abbr = abbr\n self._stations[abbr].full_name = full_name\n\n for key, value in extra_charact.items():\n setattr(self._stations[abbr], key, value)\n\n return self._stations\n\n @classmethod\n def get(cls, name):\n\n self = cls()\n\n try:\n return get_frame(name)\n except UnknownFrameError:\n if name not in self.list().keys():\n raise\n return self.list()[name]\n\n @classmethod\n def save(cls, station):\n self = cls()\n\n ws.config[\"stations\"].update(station)\n ws.config.save()\n\n if hasattr(self, \"_stations\"):\n del self._stations\n\n\ndef wshook(cmd, *args, **kwargs):\n\n if cmd in (\"init\", \"full-init\"):\n name = \"TLS\"\n\n ws.config.setdefault(\"stations\", {})\n\n try:\n StationDb.get(name)\n except UnknownFrameError:\n StationDb.save(\n {\n name: {\n \"latlonalt\": [43.604482, 1.443962, 172.0],\n \"name\": \"Toulouse\",\n \"parent_frame\": \"WGS84\",\n }\n }\n )\n log.info(\"Station {} created\".format(name))\n else:\n log.warning(\"Station {} already exists\".format(name))\n\n\ndef space_station(*argv):\n \"\"\"Stations management\n\n Usage:\n space-station list [--map] [<abbr>]\n space-station create <abbr> <name> <lat> <lon> <alt>\n\n Options\n list List available stations\n create Interactively create a station\n <abbr> Abbreviation\n <name> Name of the station\n <lat> Latitude in degrees\n <lon> Longitude in degrees\n <alt> Altitude in meters\n -m, --map Display the station on a map\n\n Latitude and longitude both accept degrees as float or as\n degrees, minutes and seconds of arc (e.g. 43°25\"12')\n \"\"\"\n\n from pathlib import Path\n import matplotlib.pyplot as plt\n\n from .utils import docopt\n from .map.background import set_background\n\n args = docopt(space_station.__doc__)\n\n station = StationDb()\n\n if args[\"create\"]:\n abbr = args[\"<abbr>\"]\n name = args[\"<name>\"]\n latitude = args[\"<lat>\"]\n longitude = args[\"<lon>\"]\n altitude = args[\"<alt>\"]\n\n if \"°\" in latitude:\n latitude = dms2deg(latitude)\n else:\n latitude = float(latitude)\n\n if \"°\" in longitude:\n longitude = dms2deg(longitude)\n else:\n longitude = float(longitude)\n\n altitude = float(altitude)\n\n log.info(\"Creation of station '{}' ({})\".format(name, abbr))\n log.debug(\n \"{} {}, altitude : {} m\".format(\n deg2dms(latitude, \"lat\"), deg2dms(longitude, \"lon\"), altitude\n )\n )\n StationDb.save(\n {\n abbr: {\n \"name\": name,\n \"latlonalt\": (latitude, longitude, altitude),\n \"parent_frame\": \"WGS84\",\n }\n }\n )\n else:\n\n stations = []\n\n for station in sorted(station.list().values(), key=lambda x: x.abbr):\n\n if args[\"<abbr>\"] and station.abbr != args[\"<abbr>\"]:\n continue\n\n print(station.name)\n print(\"-\" * len(station.name))\n lat, lon, alt = station.latlonalt\n lat, lon = degrees([lat, lon])\n print(\"name: {}\".format(station.full_name))\n print(\n \"altitude: {} m\\nposition: {}, {}\".format(\n alt, deg2dms(lat, \"lat\"), deg2dms(lon, \"lon\")\n )\n )\n print()\n\n stations.append((station.name, lat, lon))\n\n if args[\"--map\"]:\n plt.figure(figsize=(15.2, 8.2))\n set_background()\n plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)\n plt.show()\n", "#!/usr/bin/env python\n# coding=utf-8\n\nimport sys\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nfrom beyond.propagators.listeners import LightListener, RadialVelocityListener\nfrom beyond.errors import UnknownFrameError\nfrom beyond.env.solarsystem import get_body\n\nfrom .utils import circle, docopt, parse_date, parse_timedelta\nfrom .station import StationDb\nfrom .sat import Sat\nfrom .map.background import set_background\n\nlog = logging.getLogger(__name__)\n\n\ndef space_passes(*argv):\n \"\"\"Compute and plot passes geometry\n\n Usage:\n space-passes <station> (- | <satellite>...) [options]\n\n Option:\n -h --help Show this help\n <station> Location from which the satellite is tracked\n <satellite> Satellite to track.\n - If used the orbit should be provided as stdin in TLE\n or CCSDS format (see example)\n -d --date <date> Starting date of the computation [default: now]\n (format: \"%Y-%m-%dT%H:%M:%S\")\n -r --range <days> Range of the computation [default: 1d]\n -n --no-events Don't compute AOS, MAX and LOS\n -e --events-only Only show AOS, MAX and LOS\n -l --light Compute day/penumbra/umbra transitions\n -s --step <step> Step-size [default: 30s]\n -p --passes <nb> Number of passes to display [default: 1]\n -g --graphs Display graphics with matplotlib\n -z --zenital Reverse direction of azimut angle on the polar plot\n to show as the passes as seen from the station\n looking to the sky\n --radial Compute radial velocity nullation point\n --csv Print in CSV format\n --sep=<sep> CSV separator [default: ,]\n\n Examples:\n Simple computation of the ISS, TLS is the name of my station\n\n $ space passes TLS ISS\n\n Hubble is not part of my satellite database, but I want to compute its\n visibility just once\n\n $ space tle norad 20580 | space passes TLS\n\n \"\"\"\n\n args = docopt(space_passes.__doc__)\n\n try:\n start = parse_date(args[\"--date\"])\n step = parse_timedelta(args[\"--step\"])\n stop = parse_timedelta(args[\"--range\"])\n pass_nb = int(args[\"--passes\"])\n sats = Sat.from_command(\n *args[\"<satellite>\"], text=sys.stdin.read() if args[\"-\"] else \"\"\n )\n except ValueError as e:\n log.error(e)\n sys.exit(1)\n\n try:\n station = StationDb.get(args[\"<station>\"])\n except UnknownFrameError:\n log.error(\"Unknwon station '{}'\".format(args[\"<station>\"]))\n sys.exit(1)\n\n events = not args[\"--no-events\"]\n\n light = LightListener()\n\n if args[\"--light\"] and events:\n events = [light, LightListener(LightListener.PENUMBRA)]\n if args[\"--radial\"]:\n rad = RadialVelocityListener(station, sight=True)\n if isinstance(events, list):\n events.append(rad)\n else:\n events = rad\n\n # Computation of the passes\n for sat in sats:\n\n lats, lons = [], []\n lats_e, lons_e = [], []\n azims, elevs = [], []\n azims_e, elevs_e, text_e = [], [], []\n\n info_size = 0\n if args[\"--csv\"]:\n print(\n args[\"--sep\"].join(\n [\n \"date\",\n \"event\",\n \"name\",\n \"azimut\",\n \"elevation\",\n \"distance\",\n \"light\",\n ]\n )\n )\n else:\n info_size = len(station.name) + 10\n header = \"Time Infos{} Sat{} Azim Elev Dist (km) Light \".format(\n \" \" * (info_size - 5), \" \" * (len(sat.name) - 3)\n )\n\n print(header)\n print(\"=\" * len(header))\n\n count = 0\n dates = []\n for orb in station.visibility(\n sat.orb, start=start, stop=stop, step=step, events=events\n ):\n\n if args[\"--events-only\"] and orb.event is None:\n continue\n\n azim = -np.degrees(orb.theta) % 360\n elev = np.degrees(orb.phi)\n azims.append(azim)\n elevs.append(90 - elev)\n dates.append(orb.date)\n r = orb.r / 1000.0\n\n if orb.event:\n azims_e.append(azim)\n elevs_e.append(90 - elev)\n\n light_info = \"Umbra\" if light(orb) <= 0 else \"Light\"\n\n if args[\"--csv\"]:\n fmt = [\n \"{orb.date:%Y-%m-%dT%H:%M:%S.%f}\",\n \"{event}\",\n \"{sat.name}\",\n \"{azim:.2f}\",\n \"{elev:.2f}\",\n \"{r:.2f}\",\n \"{light}\",\n ]\n fmt = args[\"--sep\"].join(fmt)\n else:\n fmt = \"{orb.date:%Y-%m-%dT%H:%M:%S.%f} {event:{info_size}} {sat.name} {azim:7.2f} {elev:7.2f} {r:10.2f} {light}\"\n\n print(\n fmt.format(\n orb=orb,\n r=r,\n azim=azim,\n elev=elev,\n light=light_info,\n sat=sat,\n event=orb.event if orb.event is not None else \"\",\n info_size=info_size,\n )\n )\n\n orb_itrf = orb.copy(frame=\"ITRF\")\n lon, lat = np.degrees(orb_itrf[1:3])\n lats.append(lat)\n lons.append(lon)\n\n if orb.event:\n lats_e.append(lat)\n lons_e.append(lon)\n text_e.append(orb.event.info)\n\n if (\n orb.event is not None\n and orb.event.info == \"LOS\"\n and orb.event.elev == 0\n ):\n print()\n count += 1\n if count == pass_nb:\n break\n\n # Plotting\n if args[\"--graphs\"] and azims:\n\n # Polar plot of the passes\n plt.figure(figsize=(15.2, 8.2))\n\n ax = plt.subplot(121, projection=\"polar\")\n ax.set_theta_zero_location(\"N\")\n\n plt.title(\"{} from {}\".format(sat.name, station))\n if not args[\"--zenital\"]:\n ax.set_theta_direction(-1)\n\n plt.plot(np.radians(azims), elevs, \".\")\n\n for azim, elev, txt in zip(azims_e, elevs_e, text_e):\n plt.plot(np.radians(azim), elev, \"ro\")\n plt.text(np.radians(azim), elev, txt, color=\"r\")\n\n if station.mask is not None:\n\n m_azims = np.arange(0, 2 * np.pi, np.pi / 180.0)\n m_elevs = [90 - np.degrees(station.get_mask(azim)) for azim in m_azims]\n\n plt.plot(-m_azims, m_elevs)\n\n # Add the Moon and Sun traces\n bodies = (('Sun', 'yo', None), ('Moon', 'wo', 'k'))\n bodies_ephem = {}\n\n for body, marker, edge in bodies:\n\n b_ephem = get_body(body).propagate(orb.date).ephem(dates=dates)\n bodies_ephem[body] = b_ephem\n mazim, melev = [], []\n for m in station.visibility(b_ephem):\n mazim.append(-m.theta)\n melev.append(90 - np.degrees(m.phi))\n\n plt.plot(mazim, melev, marker, mec=edge, mew=0.5)\n\n ax.set_yticks(range(0, 90, 20))\n ax.set_yticklabels(map(str, range(90, 0, -20)))\n ax.set_xticklabels([\"N\", \"NE\", \"E\", \"SE\", \"S\", \"SW\", \"W\", \"NW\"])\n ax.set_rmax(90)\n\n plt.tight_layout()\n\n plt.subplot(122)\n # Ground-track of the passes\n set_background()\n plt.plot(lons, lats, \"b.\")\n\n plt.plot(lons_e, lats_e, \"r.\")\n\n color = \"#202020\"\n\n # Ground Station\n sta_lat, sta_lon = np.degrees(station.latlonalt[:-1])\n\n # Visibility circle\n lon, lat = np.degrees(\n list(zip(*circle(orb_itrf.r, *station.latlonalt[-2::-1])))\n )\n lon = ((lon + 180) % 360) - 180\n plt.plot(lon, lat, \".\", color=color, ms=2)\n\n # Mask\n if station.mask is not None:\n m_azims = np.arange(0, 2 * np.pi, np.pi / 180.0)\n m_elevs = [station.get_mask(azim) for azim in m_azims]\n mask = [m_azims, m_elevs]\n\n lon, lat = np.degrees(\n list(\n zip(\n *circle(\n orb_itrf.r,\n np.radians(sta_lon),\n np.radians(sta_lat),\n mask=mask,\n )\n )\n )\n )\n lon = ((lon + 180) % 360) - 180\n plt.plot(lon, lat, color=\"c\", ms=2)\n\n # Add the moon and sun traces\n for body, marker, edge in bodies:\n b_itrf = np.asarray(bodies_ephem[body].copy(frame=\"ITRF\", form=\"spherical\"))\n lon = ((np.degrees(b_itrf[:, 1]) + 180 ) % 360) - 180\n lat = np.degrees(b_itrf[:, 2])\n plt.plot(lon, lat, marker, mec=edge, mew=0.5)\n\n plt.xlim([-180, 180])\n plt.ylim([-90, 90])\n plt.grid(linestyle=\":\")\n plt.xticks(range(-180, 181, 30))\n plt.yticks(range(-90, 91, 30))\n plt.tight_layout()\n plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)\n\n if args[\"--graphs\"]:\n plt.show()\n" ]
[ [ "numpy.radians", "numpy.degrees", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.tight_layout", "numpy.radians", "matplotlib.pyplot.ylim", "numpy.degrees", "numpy.arange", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "matplotlib.pyplot.subplot", "matplotlib.pyplot.grid", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
boringlee24/keras_old
[ "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d", "1e1176c45c4952ba1b9b9e58e9cc4df027ab111d" ]
[ "examples/pwr_run/checkpointing/final/final4_new2/job51.py", "examples/pwr_run/checkpointing/final_trace/top50/job48.py", "examples/pwr_run/checkpointing/debug/ovhd_profile/job6.py", "examples/pwr_run/ml_regression/new_speedup_def/knn_k80.py", "examples/pwr_run/checkpointing/nonpc_short/final1/job20.py", "examples/pwr_run/checkpointing/throughput/final4_new2/job48.py", "examples/pwr_run/gpu_pwr.py", "examples/pwr_run/checkpointing/final/no_threshold/job63.py", "examples/pwr_run/checkpointing/nonpc_short/final1/job36.py", "examples/pwr_run/checkpointing/final/no_safeguard/job61.py", "examples/pwr_run/checkpointing/non_slurm/random2/job1.py", "examples/pwr_run/checkpointing/nonpc_short/timed_feedback/job38.py", "examples/pwr_run/checkpointing/socket_short/random2/job33.py", "examples/pwr_run/checkpointing/final/no_safeguard/job68.py", "examples/pwr_run/checkpointing/timed/max_par/job2.py", "examples/pwr_run/checkpointing/debug/ovhd_profile/job28.py", "examples/pwr_run/checkpointing/debug/v100_only/job28.py", "examples/pwr_run/checkpointing/throughput/final1_inverse/job38.py", "examples/pwr_run/checkpointing/socket_short/true_random/job26.py", "examples/pwr_run/checkpointing/socket_short/true_random/job20.py", "examples/pwr_run/checkpointing/nonpc_short/k80_only/job39.py", "examples/pwr_run/checkpointing/jobs_max_pwr/job47.py", "examples/pwr_run/checkpointing/nonpc_short/timed_feedback/job11.py", "examples/pwr_run/checkpointing/throughput/final2_inverse/job19.py", "examples/pwr_run/checkpointing/socket_short/max_par/job14.py", "examples/pwr_run/densenet.py", "examples/pwr_run/checkpointing/nonpc_short/final3/job31.py", "examples/pwr_run/checkpointing/throughput/final2_inverse/job25.py", "examples/pwr_run/checkpointing/final_3level/final4_3level_obsolete/job71.py", "examples/pwr_run/checkpointing/non_slurm/random/job4.py", "examples/pwr_run/checkpointing/non_slurm/random/job49.py", "examples/pwr_run/checkpointing/dash/job_trace/jobs_sc/job83.py", "examples/pwr_run/checkpointing/final_3level/final4_3level_obsolete/job67.py", "examples/pwr_run/checkpointing/short/max_par/job27.py", "examples/pwr_run/checkpointing/final/high_overhead/job73.py", "examples/pwr_run/checkpointing/socket_short/feedback/job16.py", "examples/pwr_run/checkpointing/throughput/feedback_inverse/job20.py", "examples/pwr_run/variation/energy_var_lr.py", "examples/pwr_run/checkpointing/final/feedback_v100_only/job79.py", "examples/pwr_run/checkpointing/socket_short/min_par/job18.py", "examples/pwr_run/checkpointing/non_slurm/max_pwr/job27.py", "examples/pwr_run/checkpointing/nonpc_short/timed_pwr/job20.py", "examples/pwr_run/checkpointing/nonpc_short/final3/job11.py", "examples/pwr_run/checkpointing/nonpc_short/timed_pwr/job36.py", "examples/pwr_run/checkpointing/nonpc_short/k80_only/job47.py", "examples/pwr_run/checkpointing/throughput/final3/job39.py", "examples/pwr_run/checkpointing/final/high_overhead_2/job7.py", "examples/pwr_run/checkpointing/socket_short/max_par/job2.py", "examples/pwr_run/checkpointing/socket_short/true_random/job48.py", "examples/pwr_run/checkpointing/final/high_overhead/job78.py", "examples/pwr_run/checkpointing/final_eval/random/job9.py", "examples/pwr_run/checkpointing/throughput/final1/job31.py", "examples/pwr_run/checkpointing/non_slurm/random2/job20.py", "examples/pwr_run/checkpointing/throughput/unaware/job50.py", "examples/pwr_run/checkpointing/short/random2/job49.py", "examples/pwr_run/checkpointing/dash/job_trace/jobs_50/job3.py", "examples/pwr_run/checkpointing/non_slurm/random/job3.py", "examples/pwr_run/checkpointing/final/feedback_v100_only/job6.py", "examples/pwr_run/checkpointing/throughput/final2_inverse/job26.py", "examples/pwr_run/checkpointing/socket_short/random2/job6.py", "examples/pwr_run/checkpointing/nonpc_short/timed_oracle/job23.py", "examples/pwr_run/checkpointing/non_slurm/max_par/job23.py", "examples/pwr_run/checkpointing/final_eval/k80_only/job27.py", "examples/pwr_run/checkpointing/throughput/oracle/job18.py", "examples/pwr_run/checkpointing/nonpc_short/timed_oracle/job3.py", "examples/pwr_run/checkpointing/final/no_threshold/job53.py", "examples/pwr_run/checkpointing/nonpc_short/knn/job12.py", "examples/pwr_run/checkpointing/final/feedback_inverse_bad/main.py", "examples/pwr_run/checkpointing/throughput/final1_test/job22.py", "examples/pwr_run/checkpointing/throughput/final2_inverse/job8.py", "examples/pwr_run/checkpointing/throughput/final2/job34.py", "examples/pwr_run/checkpointing/throughput/final1/job33.py", "examples/pwr_run/checkpointing/throughput/final1_test/job35.py", "examples/pwr_run/checkpointing/nonpc_short/v100_only/job31.py", "examples/pwr_run/checkpointing/nonpc_short/v100_only/job24.py" ]
[ "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'vgg16'\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4_new2/' + job_name + '*'\n\ntotal_epochs = 6\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4_new2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0014\nargs_model = 'resnet101'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4/' + job_name + '*'\n\ntotal_epochs = 36\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nload_start = time.time()\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.005\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'\n\ntotal_epochs = 9\nstarting_epoch = 0\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess():\n save_start = time.time()\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n save_time = int(time.time() - save_start)\n message = job_name + ' save ' + str(save_time)\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n\nload_time = int(time.time() - load_start)\nif args.resume:\n message = job_name + ' load ' + str(load_time)\n send_signal.send(args.node, 10002, message)\n # Score trained model.\n scores = model.evaluate(x_test, y_test, verbose=1)\n print('Test loss:', scores[0])\n print('Test accuracy:', scores[1])\n # send signal to indicate job has finished\n message = job_name + ' finish'\n send_signal.send(args.node, 10002, message)\n sys.exit()\n\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=1,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\nif not args.resume:\n terminateProcess()\n", "import pandas\nimport pdb\nfrom datetime import datetime\nimport matplotlib\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport glob\nimport sys\nfrom matplotlib.ticker import MultipleLocator\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn import neighbors\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport json\n\nlog_dir = '/scratch/li.baol/GPU_pwr_meas/tensorflow/round1/regression/pwr/*'\ndirs = glob.glob(log_dir)\ndirs.sort()\n# store everything in a dict\nall_pwr = {} # {densenet121_32:{K80:a, K100:b}...}\n\nfor tc in dirs:\n test = tc.split('/')[6+1+1].split('.')[0]\n gpu = test.split('_')[0]\n model = test.replace(gpu + '_', '')\n\n # read tc.csv into a list\n data = pandas.read_csv(tc)\n pwr = np.asarray(data[data.columns[0]].tolist())\n \n if model in all_pwr:\n all_pwr[model][gpu] = pwr\n else:\n all_pwr[model] = {gpu: pwr}\n\nlog_dir = '/scratch/li.baol/GPU_pwr_meas/tensorflow/round1/regression/util/*'\ndirs = glob.glob(log_dir)\ndirs.sort()\n# store everything in a dict\nall_util = {} # {densenet121_32:{K80:a, K100:b}...}\n\nfor tc in dirs:\n test = tc.split('/')[6+1+1].split('.')[0]\n gpu = test.split('_')[0]\n model = test.replace(gpu + '_', '')\n\n # read tc.csv into a list\n data = pandas.read_csv(tc)\n util = np.asarray(data[data.columns[0]].tolist())\n \n if model in all_util:\n all_util[model][gpu] = util\n else:\n all_util[model] = {gpu: util}\n\nlog_dir = '/scratch/li.baol/GPU_pwr_meas/tensorflow/round1/regression/mem_util/*'\ndirs = glob.glob(log_dir)\ndirs.sort()\n# store everything in a dict\nall_mem_util = {} # {densenet121_32:{K80:a, K100:b}...}\n\nfor tc in dirs:\n test = tc.split('/')[6+1+1].split('.')[0]\n gpu = test.split('_')[0]\n model = test.replace(gpu + '_', '')\n\n # read tc.csv into a list\n data = pandas.read_csv(tc)\n mem_util = np.asarray(data[data.columns[0]].tolist())\n \n if model in all_mem_util:\n all_mem_util[model][gpu] = mem_util\n else:\n all_mem_util[model] = {gpu: mem_util}\n\nlog_dir = '/scratch/li.baol/GPU_time_meas/tensorflow/round1/csv/*'\ndirs = glob.glob(log_dir)\ndirs.sort()\n# store everything in a dict\nall_time = {} # {densenet121_32:{K80:a, K100:b}...}\n\nfor tc in dirs:\n test = tc.split('/')[6+1].split('.')[0]\n gpu = test.split('_')[0]\n model = test.replace(gpu + '_', '')\n\n # read tc.csv into a list\n data = pandas.read_csv(tc)\n time = np.asarray(data[data.columns[0]].tolist())\n \n if model in all_time:\n all_time[model][gpu] = time\n else:\n all_time[model] = {gpu: time}\n\n# Now plot V100 power save ratio (%) vs K80 power(W)\n\nx1_data = [] # power\nx2_data = [] # speed\nx3_data = [] # utilization\nx4_data = [] # mem util\ny_data = []\n\nfor key in all_pwr:\n# if ('mnasnet' not in key and 'mobilenet' not in key):\n for i in all_pwr[key]['K80'].tolist(): # power\n x1_data.append(i)\n for i in (1 / all_time[key]['K80']).tolist(): # speed\n x2_data.append(i)\n for i in (all_util[key]['K80']).tolist(): # utilization\n x3_data.append(i)\n for i in (all_mem_util[key]['K80']).tolist(): # mem util\n x4_data.append(i)\n for i in (all_time[key]['K80'] / all_time[key]['V100']).tolist(): # speed up \n y_data.append(i)\n\nx1_norm = [(i - min(x1_data)) / (max(x1_data) - min(x1_data)) for i in x1_data]\nx2_norm = [(i - min(x2_data)) / (max(x2_data) - min(x2_data)) for i in x2_data]\nx3_norm = [(i - min(x3_data)) / (max(x3_data) - min(x3_data)) for i in x3_data]\nx4_norm = [(i - min(x4_data)) / (max(x4_data) - min(x4_data)) for i in x4_data]\n\n# create training data\nx_data = []\nfor i in range(len(x1_norm)):\n x_data.append([x1_norm[i], x2_norm[i], x3_norm[i], x4_norm[i]])\n\nx_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3)\n\nwith open('x1_data.json', 'w') as outfile:\n json.dump(x1_data, outfile)\nwith open('x2_data.json', 'w') as outfile:\n json.dump(x2_data, outfile)\nwith open('x3_data.json', 'w') as outfile:\n json.dump(x3_data, outfile)\nwith open('x4_data.json', 'w') as outfile:\n json.dump(x4_data, outfile)\n\nwith open('y_data.json', 'w') as outfile:\n json.dump(y_data, outfile)\n#with open('x_data.json') as f:\n# x_data = json.load(f)\n#with open('y_data.json') as f:\n# y_data = json.load(f)\n#x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3)\n\nrmse_val = [] #to store rmse values for different k\nfor K in range(20):\n K = K+1\n model = neighbors.KNeighborsRegressor(n_neighbors = K, weights='distance')\n\n model.fit(x_train, y_train) #fit the model\n pred = model.predict(x_test) #make prediction on test set\n# model.predict(np.array(x_test[0]).reshape((1, -1)))\n err = sqrt(mean_squared_error(y_test, pred)) #calculate rmse\n rmse_val.append(err) #store rmse values\n err_pct = abs(y_test-pred) / y_test * 100\n print('RMSE value for k= ' , K , 'is:', err)\n print('error (%) is', np.mean(err_pct))\n\nxx_data = []\nfor i in range(len(x1_norm)):\n xx_data.append([x1_norm[i]])\n\n# now compare with liear regression\nx_train, x_test, y_train, y_test = train_test_split(xx_data, y_data, test_size=0.3)\nmodel2 = LinearRegression().fit(x_train, y_train)\npred = model2.predict(x_test) #make prediction on test set\nerr = sqrt(mean_squared_error(y_test,pred)) #calculate rmse\nprint('RMSE value for linear regression is ', err)\n\n\n\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1/' + job_name + '*'\n\ntotal_epochs = 44\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0014\nargs_model = 'resnet101'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4/' + job_name + '*'\n\ntotal_epochs = 134\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "import pandas\nimport pdb\nfrom datetime import datetime\nimport matplotlib\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport glob\nimport sys\nfrom matplotlib.ticker import MultipleLocator\n\ntestcase = sys.argv[1] # K80_vgg19_32\nprint(testcase)\nbase_dir = '/scratch/li.baol/GPU_pwr_meas/tensorflow/round1/'\nlog_dir = base_dir + testcase + '_*/' # /scratch/li.baol/GPU_pwr_meas/pytorch/K80_vgg19_32_*/\ndirs = glob.glob(log_dir)\ndirs.sort()\npwr_all = []\navg_all = []\n\nfor tc in dirs:\n model = tc.split('/')[5+1]\n files = glob.glob(tc + \"sample*.csv\")\n files.sort()\n avg_pwr = [0] * (len(files) + 1)\n \n for fil in files:\n file_path = fil\n minute = int(fil.split('/')[6+1].split('_')[1].split('.')[0])\n try: # in case the file is empty\n data = pandas.read_csv(file_path)\n pwr = data[data.columns[2]].tolist()\n \n pwr_array = np.asarray(pwr)\n if (len(pwr) == 0):\n avg_pwr[minute] = 0\n else:\n avg_pwr[minute] = np.average(pwr_array)\n except pandas.errors.EmptyDataError:\n avg_pwr[minute] = 0\n pass\n pwr_all.append(avg_pwr)\n avg_pwr_filter = [i for i in avg_pwr if i > 10] # remove power measurements below 10W\n avg_all.append(sum(avg_pwr_filter) / len(avg_pwr_filter))\n\n\n#------------- plot ---------------#\n\nwidth = 0.1\n\nfig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))\nfig.suptitle(testcase + \" GPU power (W) during training epochs\")\nfor i in range(len(pwr_all)): \n x = np.arange(len(pwr_all[i]))\n axs.scatter(x, pwr_all[i], label = str(i))\n\naxs.set_xlabel('# of sample with 10s interval')\naxs.set_ylabel('power(W)')\n#axs.set_yticks(minor=True)\naxs.get_yaxis().set_minor_locator(MultipleLocator(5))\naxs.legend()\n\naxs.grid(which='both', axis='y', linestyle=':', color='black')\npwr = int(sum(avg_all) / len(avg_all))\nplt.savefig(base_dir + \"png/\" + testcase + '_pwr' + str(pwr) + \".png\")\n\ndf = pandas.DataFrame(avg_all, columns=[\"power(W)\"])\ndf.to_csv(base_dir + 'csv/' + testcase + '.csv', index=False)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.01\nargs_model = 'resnet50'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_no_threshold/' + job_name + '*'\n\ntotal_epochs = 11\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_no_threshold/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0023\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1/' + job_name + '*'\n\ntotal_epochs = 78\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.008\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_no_safeguard/' + job_name + '*'\n\ntotal_epochs = 8\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_no_safeguard/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'vgg16'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random2/' + job_name + '*'\n\ntotal_epochs = 6\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.0015\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback/' + job_name + '*'\n\ntotal_epochs = 83\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.002\nargs_model = 'mnasnet'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random2/' + job_name + '*'\n\ntotal_epochs = 50\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.007\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_no_safeguard/' + job_name + '*'\n\ntotal_epochs = 19\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_no_safeguard/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.001\nargs_model = 'vgg16'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*'\n\ntotal_epochs = 5\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n def on_epoch_end(self, epoch, logs=None):\n open('epoch/' + job_name + '.txt', 'a').close()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n param_dict = {}\n modify = False\n with open('param_lock.json', 'r') as fp:\n param_dict = json.load(fp)\n if job_name not in param_dict:\n param_dict[job_name] = trainable_count\n modify = True\n elif param_dict[job_name] != trainable_count:\n param_dict[job_name] = trainable_count\n modify = True\n if modify:\n json_file = json.dumps(param_dict)\n with open('param_lock.json', 'w') as fp:\n fp.write(json_file)\n os.rename('param_lock.json', 'param.json')\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nload_start = time.time()\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.004\nargs_model = 'densenet169'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'\n\ntotal_epochs = 46\nstarting_epoch = 0\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess():\n save_start = time.time()\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n save_time = int(time.time() - save_start)\n message = job_name + ' save ' + str(save_time)\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n\nload_time = int(time.time() - load_start)\nif args.resume:\n message = job_name + ' load ' + str(load_time)\n send_signal.send(args.node, 10002, message)\n # Score trained model.\n scores = model.evaluate(x_test, y_test, verbose=1)\n print('Test loss:', scores[0])\n print('Test accuracy:', scores[1])\n # send signal to indicate job has finished\n message = job_name + ' finish'\n send_signal.send(args.node, 10002, message)\n sys.exit()\n\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=1,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\nif not args.resume:\n terminateProcess()\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.004\nargs_model = 'densenet169'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_v100_only/' + job_name + '*'\n\ntotal_epochs = 46\nstarting_epoch = 0\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_v100_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.0015\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1_inverse/' + job_name + '*'\n\ntotal_epochs = 83\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1_inverse/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\nfrom random import randrange\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.003\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_true_random/' + job_name + '*'\n\ntotal_epochs = 110 \nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_true_random/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n # randomly assign it a value\n trainable_count = randrange(1000) \n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\nfrom random import randrange\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_true_random/' + job_name + '*'\n\ntotal_epochs = 44\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_true_random/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n # randomly assign it a value\n trainable_count = randrange(1000) \n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.003\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_k80_only/' + job_name + '*'\n\ntotal_epochs = 65\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_k80_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0035\nargs_model = 'densenet201'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_pwr/' + job_name + '*'\n\ntotal_epochs = 130\nstarting_epoch = 0\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_pwr/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch\n #verbose=0\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwith open('finish.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\nwith open('finish.json', 'w') as fp:\n json.dump(finish_dict, fp)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.008\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback/' + job_name + '*'\n\ntotal_epochs = 8\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0007\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '*'\n\ntotal_epochs = 45\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*'\n\ntotal_epochs = 7\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('-b', '--batch_size', default=256, type=int,\n metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\nparser.add_argument('--model', metavar='MODEL', type=str, help='specific model name')\nparser.add_argument('--lr', metavar='LEARNING_RATE', type=float, help='learning rate')\nargs = parser.parse_args()\n\n# Training parameters\nbatch_size = args.batch_size # orig paper trained all networks with batch_size=128\nepochs = 50\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'K80_DenseNet121_he_4_' + str(batch_size)\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n\ndef lr_schedule(epoch):\n \"\"\"Learning Rate Schedule\n\n Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.\n Called automatically every epoch as part of callbacks during training.\n\n # Arguments\n epoch (int): The number of epochs\n\n # Returns\n lr (float32): learning rate\n \"\"\"\n lr = args.lr #1e-3\n print('Learning rate: ', lr)\n return lr\n\nmodel = models.Sequential()\n\nif '121' in args.model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\nelif '169' in args.model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\nelif '201' in args.model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n\n#base_model.summary()\n\n#pdb.set_trace()\n\n#model.add(layers.UpSampling2D((2,2)))\n#model.add(layers.UpSampling2D((2,2)))\n#model.add(layers.UpSampling2D((2,2)))\nmodel.add(base_model)\n#model.add(layers.Flatten())\n#model.add(layers.BatchNormalization())\n#model.add(layers.Dense(128, activation='relu'))\n#model.add(layers.Dropout(0.5))\n#model.add(layers.BatchNormalization())\n#model.add(layers.Dense(64, activation='relu'))\n#model.add(layers.Dropout(0.5))\n#model.add(layers.BatchNormalization())\nmodel.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=lr_schedule(0)),\n metrics=['accuracy'])\n\n#def get_flops(model):\n# run_meta = tf.RunMetadata()\n# opts = tf.profiler.ProfileOptionBuilder.float_operation()\n#\n# # We use the Keras session graph in the call to the profiler.\n# flops = tf.profiler.profile(graph=K.get_session().graph,\n# run_meta=run_meta, cmd='op', options=opts)\n#\n# return flops.total_float_ops # Prints the \"flops\" of the model.\n#\n#pdb.set_trace()\n#model.summary()\n#print(get_flops(model))\n\nprint(model_type)\n\n#pdb.set_trace()\n\n# Prepare model saving directory.\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nmodel_name = 'my_test_model.{epoch:03d}.h5'\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nfilepath = os.path.join(save_dir, model_name)\n\n# Prepare callbacks for model saving and for learning rate adjustment.\n\n# Saves the model after each epoch. Saved to the filepath, the latest best \n# model according to the quantity monitored will not be overwritten\ncheckpoint = ModelCheckpoint(filepath=filepath,\n monitor='val_acc',\n verbose=1,\n save_best_only=True)\n\nlr_scheduler = LearningRateScheduler(lr_schedule)\n\nlr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),\n cooldown=0,\n patience=5,\n min_lr=0.5e-6)\n\n###logdir = '/scratch/li.baol/tsrbrd_log/learning_rate' + str(lr_schedule(epochs)) #+ datetime.now().strftime(\"%Y%m%d-%H%M%S\")\nlogdir = '/scratch/li.baol/tsrbrd_log/pwr_meas/' + model_type #+ datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\ncallbacks = [tensorboard_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks)\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0015\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final3/' + job_name + '*'\n\ntotal_epochs = 70\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final3/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0007\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '*'\n\ntotal_epochs = 90\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.0008\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4_3level/' + job_name + '*'\n\ntotal_epochs = 49\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4_3level/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'vgg19'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'\n\ntotal_epochs = 6\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.002\nargs_model = 'mnasnet'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'\n\ntotal_epochs = 143\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\nimport pathlib\nfrom scipy.stats import variation\nimport math\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.002\nargs_model = 'mnasnet'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/dl_checkpoints/' + args.tc + '/' + job_name + '_*'\n\ntotal_epochs = 50\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[5].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\nbatch_time = []\nbatch_begin = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n pathlib.Path('/scratch/li.baol/dl_checkpoints/'+args.tc+'/').mkdir(parents=True, exist_ok=True)\n model.save('/scratch/li.baol/dl_checkpoints/'+args.tc+'/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\nbatches_per_epoch = math.ceil(y_train.shape[0] / batch_size)\nstable_batch = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_batch_begin(self, batch, logs=None):\n global batch_begin\n batch_begin = time.time()\n def on_batch_end(self, batch, logs=None):\n global batch_time, batch_begin, stable_batch\n batch_time.append(float(time.time() - batch_begin))\n # when collected 100 batch times, calculate to see if it's stable\n if len(batch_time) == 100:\n if stable_batch == 0:\n stable_batch = round(np.median(batch_time), 3) \n message = job_name + ' batch_time ' + str(stable_batch)\n send_signal.send(args.node, 10002, message)\n # collect wasted time right after migration\n wasted_time = round(np.sum(batch_time) - stable_batch * 100, 2)\n message = job_name + ' 1st_ovhd ' + str(wasted_time)\n send_signal.send(args.node, 10002, message)\n batch_time = []\n self.remaining_batches -= 100\n message = job_name + ' remain_batch ' + str(self.remaining_batches)\n send_signal.send(args.node, 10002, message)\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n self.remaining_batches = (round(total_epochs/2)-current_epoch)*batches_per_epoch\n message = job_name + ' total_batch ' + str(self.remaining_batches)\n send_signal.send(args.node, 10002, message)\n message = job_name + ' epoch_begin ' + str(current_epoch)\n send_signal.send(args.node, 10002, message)\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4_3level/' + job_name + '*'\n\ntotal_epochs = 52\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4_3level/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*'\n\ntotal_epochs = 87\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n param_dict = {}\n modify = False\n with open('param_lock.json', 'r') as fp:\n param_dict = json.load(fp)\n if job_name not in param_dict:\n param_dict[job_name] = trainable_count\n modify = True\n elif param_dict[job_name] != trainable_count:\n param_dict[job_name] = trainable_count\n modify = True\n if modify:\n json_file = json.dumps(param_dict)\n with open('param_lock.json', 'w') as fp:\n fp.write(json_file)\n os.rename('param_lock.json', 'param.json')\n\n# creates an file if job qualified for checkpoint\nopen('ckpt_qual/' + job_name + '.txt', 'a').close()\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n try:\n os.rename('finish.json', 'finish_lock.json')\n break\n except Exception:\n pass\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.002\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4/' + job_name + '*'\n\ntotal_epochs = 67\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n time.sleep(100)\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0005\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback/' + job_name + '*'\n\ntotal_epochs = 14\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback/' + job_name + '*'\n\ntotal_epochs = 44\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "import pandas\nimport pdb\nfrom datetime import datetime\nimport matplotlib\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport glob\nimport sys\nfrom matplotlib.ticker import MultipleLocator\n\ntc_list = ['resnet50_0.001', 'resnet50_0.005', 'resnet50_0.01', 'resnet50_0.05']\n\nvc_pct = [] # variational coefficient in %\nspread = []\n\nfor testcase in tc_list:\n print(testcase)\n \n pwr_dir = '/scratch/li.baol/GPU_pwr_meas/tensorflow/csv/K80_' + testcase + '.csv' # /scratch/li.baol/GPU_pwr_meas/tensorflow/K80_resnet19_32_*/\n time_dir = '/scratch/li.baol/GPU_time_meas/tensorflow/csv/K80_' + testcase + '.csv' # /scratch/li.baol/GPU_pwr_meas/tensorflow/K80_resnet19_32_*/\n\n power = pandas.read_csv(pwr_dir)\n power_array = np.asarray(power[power.columns[0]].tolist())\n\n time = pandas.read_csv(time_dir)\n time_array = np.asarray(time[time.columns[0]].tolist())\n\n energy_array = power_array * time_array\n\n mean = np.mean(energy_array)\n stdev = np.std(energy_array)\n vc_pct.append(stdev / mean * 100)\n spread.append((np.amax(energy_array) - np.amin(energy_array)) / np.amin(energy_array))\n\n#------------- plot variation coefficient ---------------#\n\nwidth = 0.55\n\nfig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))\nfig.suptitle(\"GPU energy variation coefficient (%) during training\")\nfig.subplots_adjust(bottom=0.2)\n\nx = np.arange(len(tc_list))\naxs.bar(x, vc_pct, width)\naxs.set_xticks(x)\naxs.set_xticklabels(tc_list, rotation=45, ha=\"right\")\naxs.set_xlabel('test cases')\naxs.set_ylabel('variation coefficient (%)')\n#axs.set_yticks(minor=True)\naxs.get_yaxis().set_minor_locator(MultipleLocator(1))\n#axs.legend()\n\naxs.grid(which='both', axis='y', linestyle=':', color='black')\nplt.savefig(\"lr/resnet_energy_variation.png\")\n\n#------------- plot spread ---------------#\n\nfig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))\nfig.suptitle(\"GPU energy spread during training\")\nfig.subplots_adjust(bottom=0.2)\n\nx = np.arange(len(tc_list))\naxs.bar(x, spread, width)\naxs.set_xticks(x)\naxs.set_xticklabels(tc_list, rotation=45, ha=\"right\")\naxs.set_xlabel('test cases')\naxs.set_ylabel('spread')\n#axs.set_yticks(minor=True)\n#axs.get_yaxis().set_minor_locator(MultipleLocator(1))\n#axs.legend()\n\naxs.grid(which='both', axis='y', linestyle=':', color='black')\n#plt.show()\nplt.savefig(\"lr/resnet_energy_spread.png\")\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\nargs_model = 'resnet152'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback_fair/' + job_name + '*'\n\ntotal_epochs = 41\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback_fair/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.007\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_min_param/' + job_name + '*'\n\ntotal_epochs = 19\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_min_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.005\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_pwr/' + job_name + '*'\n\ntotal_epochs = 87\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_pwr/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_pwr/' + job_name + '*'\n\ntotal_epochs = 44\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_pwr/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.008\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final3/' + job_name + '*'\n\ntotal_epochs = 8\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final3/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0023\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_pwr/' + job_name + '*'\n\ntotal_epochs = 78\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_pwr/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0035\nargs_model = 'densenet201'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_k80_only/' + job_name + '*'\n\ntotal_epochs = 130\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_k80_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.003\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final3/' + job_name + '*'\n\ntotal_epochs = 65\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final3/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.0005\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4/' + job_name + '*'\n\ntotal_epochs = 6\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n time.sleep(50)\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.001\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*'\n\ntotal_epochs = 5\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\nfrom random import randrange\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0014\nargs_model = 'resnet101'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_true_random/' + job_name + '*'\n\ntotal_epochs = 134\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_true_random/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n # randomly assign it a value\n trainable_count = randrange(1000) \n # send signal 'jobxx param xxxxx'\n message = job_name + ' param ' + str(trainable_count)\n send_signal.send(args.node, 10002, message)\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.004\nargs_model = 'densenet169'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final4/' + job_name + '*'\n\ntotal_epochs = 46\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n time.sleep(100)\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final4/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.01\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random/' + job_name + '*'\n\ntotal_epochs = 6\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0015\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1/' + job_name + '*'\n\ntotal_epochs = 70\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random2/' + job_name + '*'\n\ntotal_epochs = 44\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0012\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_unaware/' + job_name + '*'\n\ntotal_epochs = 130\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_unaware/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.002\nargs_model = 'mnasnet'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random2/' + job_name + '*'\n\ntotal_epochs = 143\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n# creates an file if job qualified for checkpoint\nopen('ckpt_qual/' + job_name + '.txt', 'a').close()\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n try:\n os.rename('finish.json', 'finish_lock.json')\n break\n except Exception:\n pass\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nfrom keras.utils import multi_gpu_model\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\nimport pathlib\nfrom scipy.stats import variation\nimport math\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\nargs_model = 'resnet152'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/dl_checkpoints/' + args.tc + '/' + job_name + '_*'\n\ntotal_epochs = 214\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[5].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nwith tf.device('/cpu:0'):\n if args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\n else:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \nparallel_model = multi_gpu_model(model, gpus=2, cpu_merge=True)\n\nparallel_model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n\n#model.summary()\nprint(model_type)\n\n#pdb.set_trace()\n\nbatch_time = []\nbatch_begin = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n pathlib.Path('/scratch/li.baol/dl_checkpoints/'+args.tc+'/').mkdir(parents=True, exist_ok=True)\n model.save('/scratch/li.baol/dl_checkpoints/'+args.tc+'/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\nbatches_per_epoch = math.ceil(y_train.shape[0] / batch_size)\nstable_batch = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_batch_begin(self, batch, logs=None):\n global batch_begin\n batch_begin = time.time()\n def on_batch_end(self, batch, logs=None):\n global batch_time, batch_begin, stable_batch\n batch_time.append(float(time.time() - batch_begin))\n # when collected 100 batch times, calculate to see if it's stable\n if len(batch_time) == 100:\n if stable_batch == 0:\n stable_batch = round(np.median(batch_time), 3) \n message = job_name + ' batch_time ' + str(stable_batch)\n send_signal.send(args.node, 10002, message)\n # collect wasted time right after migration\n wasted_time = round(np.sum(batch_time) - stable_batch * 100, 2)\n message = job_name + ' 1st_ovhd ' + str(wasted_time)\n send_signal.send(args.node, 10002, message)\n batch_time = []\n self.remaining_batches -= 100\n message = job_name + ' remain_batch ' + str(self.remaining_batches)\n send_signal.send(args.node, 10002, message)\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n self.remaining_batches = (round(total_epochs/2)-current_epoch)*batches_per_epoch\n message = job_name + ' total_batch ' + str(self.remaining_batches)\n send_signal.send(args.node, 10002, message)\n message = job_name + ' epoch_begin ' + str(current_epoch)\n send_signal.send(args.node, 10002, message)\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nparallel_model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = parallel_model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'resnet50'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'\n\ntotal_epochs = 4\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\n# Run training\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.005\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_feedback_fair/' + job_name + '*'\n\ntotal_epochs = 9\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_feedback_fair/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.003\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '*'\n\ntotal_epochs = 110 \nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.005\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_random2/' + job_name + '*'\n\ntotal_epochs = 9\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_random2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.002\nargs_model = 'vgg19'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_oracle/' + job_name + '*'\n\ntotal_epochs = 67\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_oracle/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.002\nargs_model = 'vgg19'\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*'\n\ntotal_epochs = 67\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\nif not args.resume:\n trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))\n param_dict = {}\n modify = False\n with open('param_lock.json', 'r') as fp:\n param_dict = json.load(fp)\n if job_name not in param_dict:\n param_dict[job_name] = trainable_count\n modify = True\n elif param_dict[job_name] != trainable_count:\n param_dict[job_name] = trainable_count\n modify = True\n if modify:\n json_file = json.dumps(param_dict)\n with open('param_lock.json', 'w') as fp:\n fp.write(json_file)\n os.rename('param_lock.json', 'param.json')\n\nckpt_qual_dict = {}\nwhile True:\n if os.path.exists('ckpt_qual.json'):\n os.rename('ckpt_qual.json', 'ckpt_qual_lock.json')\n break\n else:\n time.sleep(1)\nwith open('ckpt_qual_lock.json', 'r') as fp:\n ckpt_qual_dict = json.load(fp)\nckpt_qual_dict[job_name] = 1\njson_file2 = json.dumps(ckpt_qual_dict)\nwith open('ckpt_qual_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('ckpt_qual_lock.json', 'ckpt_qual.json')\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=total_epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\nfinish_dict = {}\nwhile True:\n if os.path.exists('finish.json'):\n os.rename('finish.json', 'finish_lock.json')\n break\n else:\n time.sleep(1)\nwith open('finish_lock.json', 'r') as fp:\n finish_dict = json.load(fp)\nfinish_dict[job_name] = 1\njson_file2 = json.dumps(finish_dict)\nwith open('finish_lock.json', 'w') as fp:\n fp.write(json_file2)\nos.rename('finish_lock.json', 'finish.json')\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 128\nargs_lr = 0.005\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_k80_only/' + job_name + '*'\n\ntotal_epochs = 83\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_k80_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.007\nargs_model = 'densenet121'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_oracle/' + job_name + '*'\n\ntotal_epochs = 19\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '121' in args_model:\n base_model = DenseNet121(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '169' in args_model:\n base_model = DenseNet169(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n elif '201' in args_model:\n base_model = DenseNet201(weights=None, include_top=False, input_shape=(32, 32, 3), pooling='avg')\n \n \n model.add(base_model)\n #model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_oracle/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'resnet50'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_oracle/' + job_name + '*'\n\ntotal_epochs = 4\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_oracle/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n def on_epoch_end(self, epoch, logs=None):\n # send message of epoch end\n message = job_name + ' epoch_end'\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'resnet50'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_no_threshold/' + job_name + '*'\n\ntotal_epochs = 4\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_no_threshold/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.003\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_knn/' + job_name + '*'\n\ntotal_epochs = 18\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_knn/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "import pdb\nimport time\nimport os\nimport subprocess\nimport re\nimport random\nimport json\nimport numpy as np\nimport glob\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\nimport socket\nimport argparse\nimport threading\nimport _thread\nimport signal\nfrom datetime import datetime\nimport csv\n\nparser = argparse.ArgumentParser(description='TCP client')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='select testcase')\nargs = parser.parse_args()\n\nwith open('job_queue.json', 'r') as fp:\n queue = json.load(fp)\nqueue_dict = {}\narrival_time = 0 \nfor item in queue:\n arrival_time += np.random.poisson(30)\n queue_dict[item] = arrival_time\nqueue_timer = time.time()\nqueue_delay = {}\nfor item in queue:\n queue_delay[str(item)] = 0\n\njob_start = {} #{'49': time1, '15': time2...}\nJCT = {}\nfor item in queue:\n JCT[str(item)] = 0\ncompletion = {}\nfor item in queue:\n completion[str(item)] = 0\noverhead = {} # initialize so that every job starts with 0s overhead time\nfor item in queue:\n overhead[str(item)] = 0\novhd_start = {} # initialize this to 0 as well\nfor item in queue:\n ovhd_start[str(item)] = 0\nb_start = {} # initialize this to 0 as well\nfor item in queue:\n b_start[str(item)] = 0\nc_start = {} # initialize this to 0 as well\nfor item in queue:\n c_start[str(item)] = 0\nd_start = {} # initialize this to 0 as well\nfor item in queue:\n d_start[str(item)] = 0\n\novhd_a = {} # {1: [10, 12, ...], 2: [xx]} \nfor item in queue:\n ovhd_a[str(item)] = []\novhd_b = {} # {1: [10, 12, ...], 2: [xx]} \nfor item in queue:\n ovhd_b[str(item)] = []\novhd_c = {} # {1: [10, 12, ...], 2: [xx]} \nfor item in queue:\n ovhd_c[str(item)] = []\novhd_d = {} # {1: [10, 12, ...], 2: [xx]} \nfor item in queue:\n ovhd_d[str(item)] = []\novhd_total = {} # {1: [10, 12, ...], 2: [xx]} \nfor item in queue:\n ovhd_total[str(item)] = []\nk80_1st = {}\nfor item in queue:\n k80_1st[str(item)] = []\nv100_1st = {}\nfor item in queue:\n v100_1st[str(item)] = []\n\nnum_mig = {} # initialize migration time to 0\nfor item in queue:\n num_mig[str(item)] = 0\nqueue_start = {} # initialize this to 0 as well\nfor item in queue:\n queue_start[str(item)] = 0\nqueue_time = {} # initialize this to 0 as well\nfor item in queue:\n queue_time[str(item)] = 0\nV100_epoch_time = {}\nfor item in queue:\n V100_epoch_time[str(item)] = 0\nK80_start_time = {}\nfor item in queue:\n K80_start_time[str(item)] = 0\nV100_start_time = {}\nfor item in queue:\n V100_start_time[str(item)] = 0\nK80_time = {}\nfor item in queue:\n K80_time[str(item)] = 0\nV100_time = {}\nfor item in queue:\n V100_time[str(item)] = 0\ngpu_usage_time = [] # don't initialize this\ngpu_usage = []\ngpu_usage_completion = []\nqualified_job = []\n\nspeedup_dict = {}\nfor item in queue:\n speedup_dict[str(item)] = 0\n\nindex = 0\nall_jobs_started = False\n\nK80_cap = 16\nV100_cap = 8\nK80_used = 0\nV100_used = 0\n\nK80_job = {}\nfor i in range(K80_cap):\n K80_job[str(i)] = 'idle'\nV100_job = {}\nfor i in range(V100_cap):\n V100_job[str(i)] = 'idle'\nstep1_job = []\nstep2_job = []\npc_job = []\n\nK80_node = ['c2179', 'c2183']\nV100_node = ['d1020', 'd1018']\nhost_node = 'c0177'\ntestcase = args.tc\n### also, change .h5 file folder in jobs ###\n\nINTERVAL = 30 # make decision every 30s\n\ndef K80_LUT(gpu):\n quotient = int(gpu) // 8\n remainder = int(gpu) % 8\n real_node = K80_node[quotient]\n real_gpu = str(remainder)\n return real_node, real_gpu\ndef V100_LUT(gpu):\n quotient = int(gpu) // 4\n remainder = int(gpu) % 4\n real_node = V100_node[quotient]\n real_gpu = str(remainder)\n return real_node, real_gpu\n\ndef send_signal(node, cmd):\n # Create a TCP/IP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n port = 10000\n # Connect the socket to the port where the server is listening\n server_address = (node, int(port))\n\n print('connecting to {} port {}'.format(*server_address))\n sock.connect(server_address)\n\n try:\n # Send data\n message = cmd.encode('utf-8') #b'save 35' #b'start 35 gpu 6'#b'save 35'\n \n print('sending {!r}'.format(message))\n sock.sendall(message)\n while True:\n data = sock.recv(32)\n if 'success' in data.decode('utf-8'):\n# print('received {!r}'.format(data))\n break\n else:\n print('waiting for success signal')\n time.sleep(1)\n finally:\n #print('closing socket')\n sock.close()\n\ndef max_speedup_promotion(K80_free, V100_free, V100_job, promote_list, demote_list):\n num_promote = len(promote_list) \n V100_vacant = len(demote_list) + V100_free\n K80_vacant = num_promote + K80_free \n global speedup_dict\n\n # selectively promote among active V100 jobs and promote list jobs\n V100_pool = list(set(demote_list).union(promote_list)) \n if len(V100_pool) <= V100_vacant: # promote all jobs as well\n return promote_list[:], []\n else: # promote the top 4 jobs \n pool_dict = {}\n for job in V100_pool:\n if job in speedup_dict:\n pool_dict[job] = speedup_dict[job] \n sorted_pool = sorted(pool_dict, key=pool_dict.get, reverse=True)[:V100_vacant] \n promotion_list = list(set(promote_list).intersection(sorted_pool)) \n demotion_list = list(set(demote_list).difference(sorted_pool))\n return promotion_list, demotion_list\n\ndef min_speedup_demotion(K80_job, demote_list):\n num_demote = len(demote_list)\n global speedup_dict\n\n # selectively demote among active K80 jobs and demote list jobs\n K80_qual = list(set(list(K80_job.values())))\n if 'idle' in K80_qual:\n K80_qual.remove('idle')\n K80_pool = list(set(K80_qual).union(demote_list)) \n if len(K80_pool) <= K80_cap: # demote all jobs, no promotion\n return [], demote_list\n else: # promote the top 4 jobs \n pool_dict = {}\n for job in K80_pool:\n if job in speedup_dict:\n pool_dict[job] = speedup_dict[job] \n sorted_pool = sorted(pool_dict, key=pool_dict.get, reverse=False)[:K80_cap] # 8 least speedup jobs\n demotion_list = list(set(demote_list).intersection(sorted_pool))\n promotion_list = list(set(list(K80_job.values())).difference(sorted_pool))\n if 'idle' in promotion_list:\n promotion_list.remove('idle') # this includes force demotion\n return promotion_list, demotion_list\n\ndef save_job(node, job): # save_job('c2176', '50')\n # first wait for the job to be qualified for checkpointing\n while True: # wait for ckpt_qual to be available\n global ckpt_qual_dict\n if ckpt_qual_dict['job'+job] == 1:\n ckpt_qual_dict['job'+job] = 0\n break\n time.sleep(5)\n \n global pid_dict\n pid = pid_dict['job'+job]\n send_signal(node, 'save ' + job + ' pid ' + pid) # 'save 50 pid 10000'\n\n global ovhd_start\n ovhd_start[job] = time.time()\n\n time.sleep(3) # in case epoch_waste is communicate too frequently\n\n# resume job\ndef resume_job(node, gpu, job): # resume_job('c2176', '3', '50')\n cmd = 'resume ' + job + ' gpu ' + gpu\n send_signal(node, cmd)\n\n# start job\ndef start_job(node, gpu, job):\n cmd = 'start ' + job + ' gpu ' + gpu\n send_signal(node, cmd) \n\n# function that checks the tensorboard log of currently running jobs and logs jobs that have finished the first epoch\n# in a global list. Once it's done, it will be in a queue to be promoted to V100 for 3 more epochs.\ndef check_step1_complete(job_list):\n log_path = '/scratch/li.baol/tsrbrd_log/job_runs/' + testcase + '/'\n global step1_job\n global V100_epoch_time\n for job in job_list:\n if job not in step1_job and job != 'idle':\n log_dir = log_path + 'job' + job + '/*'\n dirs = glob.glob(log_dir)\n dirs.sort()\n if len(dirs) > 0:\n tc = dirs[0]\n iterator = EventAccumulator(tc).Reload()\n tag = 'loss'\n try:\n if len(iterator.Scalars(tag)) > 2: # this way we can collect one epoch time\n wall_time = [t.wall_time for t in iterator.Scalars(tag)]\n V100_epoch_time[job] = wall_time[1] - wall_time[0]\n step1_job.append(job)\n print('job' + job + ' has reached step1 complete')\n except Exception:\n pass\n\ndef check_step2_complete(job_list):\n log_path = '/scratch/li.baol/tsrbrd_log/job_runs/' + testcase + '/'\n global step1_job\n global step2_job\n global V100_epoch_time\n global speedup_dict\n\n for job in job_list:\n if job in step1_job and job not in step2_job and job != 'idle':\n log_dir = log_path + 'job' + job + '/*'\n dirs = glob.glob(log_dir)\n dirs.sort()\n if len(dirs) > 1:\n tc = dirs[1]\n iterator = EventAccumulator(tc).Reload()\n tag = 'loss'\n try:\n if len(iterator.Scalars(tag)) > 2: # this way we can collect one epoch time\n wall_time = [t.wall_time for t in iterator.Scalars(tag)]\n V100_time_step2 = V100_epoch_time[job]\n K80_time_step2 = wall_time[1] - wall_time[0]\n speedup = (K80_time_step2 - V100_time_step2) / K80_time_step2\n speedup_dict[job] = speedup\n step2_job.append(job)\n print('job' + job + ' has reached step2 complete')\n except Exception:\n pass\n\n\n############### first clear finish status of all jobs ####################\n\npid_dict = {}\nfor i in range(len(queue)):\n job_name = 'job' + str(i + 1)\n pid_dict[job_name] = 0\n\ncheckpoint_dict = {}\nfor i in range(len(queue)):\n job_name = 'job' + str(i + 1)\n checkpoint_dict[job_name] = 0\n\nckpt_qual_dict = {}\nfor i in range(len(queue)):\n job_name = 'job' + str(i + 1)\n ckpt_qual_dict[job_name] = 0\n\nfinish_dict = {}\nfor i in range(len(queue)):\n job_name = 'job' + str(i + 1)\n finish_dict[job_name] = 0\n\nepoch_waste_dict = {}\nfor i in range(len(queue)):\n job_name = 'job' + str(i + 1)\n epoch_waste_dict[job_name] = 0\n\n#################### background thread running TCP socket ########################\n\ndef thread_function():\n # here listen on the socket \n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = (host_node, 10002)\n print('starting up on {} port {}'.format(*server_address))\n sock.bind(server_address)\n sock.listen(5) \n while True:\n # Wait for a connection\n connection, client_address = sock.accept() \n try:\n while True:\n data = connection.recv(32)\n if data: \n data_str = data.decode('utf-8')\n global K80_start_time\n global V100_start_time\n global K80_job\n global V100_job\n global K80_time\n global V100_time\n global ovhd_a, ovhd_b, ovhd_c, ovhd_d, k80_1st, v100_1st, ovhd_start, overhead, ovhd_total\n global b_start, c_start, d_start, completion\n if 'ckpt_qual' in data_str:\n global ckpt_qual_dict\n job_name = data_str.split(' ')[0]\n ckpt_qual_dict[job_name] = 1\n elif 'finish' in data_str:\n global finish_dict\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n finish_dict[job_name] = 1\n JCT[job] = int(time.time() - job_start[job])\n if job in list(K80_job.values()):\n K80_time[job] += int(time.time() - K80_start_time[job])\n elif job in list(V100_job.values()):\n V100_time[job] += int(time.time() - V100_start_time[job])\n elif 'pid' in data_str:\n global pid_dict\n job_name = data_str.split(' ')[0]\n pid = data_str.split(' ')[2]\n pid_dict[job_name] = pid\n elif 'checkpoint' in data_str: # can only be received after save signal is sent\n global checkpoint_dict\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','') \n checkpoint_dict[job_name] = 1\n ovhd_a[job].append(int(time.time() - ovhd_start[job]))\n b_start[job] = time.time()\n elif 'waste' in data_str:\n global epoch_waste_dict\n job_name = data_str.split(' ')[0]\n epoch_waste_time = data_str.split(' ')[2]\n epoch_waste_dict[job_name] += int(epoch_waste_time)\n elif 'b_end' in data_str:\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n ovhd_b[job].append(int(time.time() - b_start[job]))\n c_start[job] = time.time()\n elif 'c_end' in data_str:\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n ovhd_c[job].append(int(time.time() - c_start[job]))\n d_start[job] = time.time()\n elif 'd_end' in data_str:\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n ovhd_d[job].append(int(time.time() - d_start[job]))\n ovhd_total[job].append(int(time.time() - ovhd_start[job]))\n if ovhd_start[job] != 0:\n overhead[job] += int(time.time() - ovhd_start[job])\n ovhd_start[job] = 0 \n if job in list(K80_job.values()):\n K80_start_time[job] = time.time()\n elif job in list(V100_job.values()):\n V100_start_time[job] = time.time()\n elif '1st_epoch' in data_str: # 'job50 1st_epoch 35'\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n epoch_time = int(data_str.split(' ')[2])\n if job in list(K80_job.values()):\n k80_1st[job].append(epoch_time)\n elif job in list(V100_job.values()):\n v100_1st[job].append(epoch_time)\n elif 'completion' in data_str: # 'job50 completion 0.33'\n job_name = data_str.split(' ')[0]\n job = job_name.replace('job','')\n completion_portion = float(data_str.split(' ')[2])\n completion[job] = completion_portion\n #if 'ckpt_qual' in data_str or 'finish' in data_str or 'checkpoint' in data_str:\n # print('received ' + data_str)\n connection.sendall(b'success')\n #time.sleep(5)\n else:\n break\n finally:\n connection.close()\n\nx = threading.Thread(target=thread_function, daemon=True)\nx.start()\n\n###############################################################################\n\n######################################################################\n\nwhile True:\n \n # termination condition: \n # all the jobs have finished\n\n ################### check for finished jobs on K80 and V100 ##############################\n\n for gpu, job in K80_job.items():\n if job != 'idle':\n if finish_dict['job'+job] == 1:\n K80_used -= 1 \n K80_job[gpu] = 'idle'\n print('K80 finished job: ' + job)\n\n for gpu, job in V100_job.items():\n if job != 'idle':\n if finish_dict['job'+job] == 1:\n V100_used -= 1 \n V100_job[gpu] = 'idle'\n print('V100 finished job: ' + job)\n\n ################ check step1 finished job of K80 jobs and step 2 of V100 #################\n\n check_step1_complete(list(V100_job.values()))\n check_step2_complete(list(K80_job.values())) \n\n for job in list(V100_job.values()):\n if job not in qualified_job and job != 'idle':\n if job in step1_job:\n qualified_job.append(job)\n print('job' + job + ' has been qualified for demotion')\n\n ############### record number of newly arrived jobs ################\n\n new_arrival = 0\n index_cpy = index\n while True:\n time_passed = int(time.time() - queue_timer)\n if index_cpy >= len(queue):\n break\n elif time_passed >= queue_dict[queue[index_cpy]]:\n new_arrival += 1\n index_cpy += 1\n elif time_passed < queue_dict[queue[index_cpy]]:\n break\n\n ################ make promotion decisions ########################\n\n V100_free = V100_cap - V100_used\n K80_free = K80_cap - K80_used\n if new_arrival == 0:\n # this returns available jobs for promotion. Has to be qualified, and currently in K80, but not practically complete\n promote_list = list(set(qualified_job).intersection(list(K80_job.values())).difference(pc_job))\n demote_list = list(set(qualified_job).intersection(list(V100_job.values())))\n else:\n demote_list = list(set(qualified_job).intersection(list(V100_job.values())))\n promote_list = []\n\n if len(promote_list) > 0 or len(demote_list) > 0:\n if new_arrival == 0:\n promoted, demoted = max_speedup_promotion(K80_free, V100_free, V100_job, promote_list, demote_list)\n else:\n promoted, demoted = min_speedup_demotion(K80_job, demote_list)\n if len(demoted) - len(promoted) > new_arrival - V100_free:\n # demote only # of new arrivals + # of promoted\n print('some demoted canceled because more demoted than new arrival + promoted, arrival = ' +\n str(new_arrival))\n print('original demotion: ' + str(demoted))\n demoted_pool = {}\n for job in demoted:\n if job in speedup_dict:\n demoted_pool[job] = speedup_dict[job]\n demoted = sorted(demoted_pool, key=demoted_pool.get, reverse=False)[:(len(promoted)+new_arrival-V100_free)]\n print('new demotion: ' + str(demoted))\n\n if len(promoted) > 0:\n if new_arrival == 0:\n print('no new job arrivals')\n print('promoted jobs: ', promoted)\n if len(demoted) > 0:\n print('demoted jobs: ', demoted)\n # stop all promoted jobs on K80\n checkpoint_finish_check = []\n for gpu, job in K80_job.items():\n if job in promoted:\n real_node, real_gpu = K80_LUT(gpu)\n save_job(real_node, job)\n if finish_dict['job'+job] != 1:\n K80_time[job] += int(time.time() - K80_start_time[job])\n checkpoint_finish_check.append(job)\n K80_job[gpu] = 'idle'\n K80_used -= 1\n \n # stop all demoted jobs on V100\n for gpu, job in V100_job.items():\n if job in demoted:\n # make sure demoted step1 job doesn't get promoted back before finishing profiling\n if job in step1_job and job not in step2_job:\n speedup_dict[job] = -1 \n real_node, real_gpu = V100_LUT(gpu)\n save_job(real_node, job)\n if finish_dict['job'+job] != 1:\n V100_time[job] += int(time.time() - V100_start_time[job])\n checkpoint_finish_check.append(job)\n V100_job[gpu] = 'idle'\n V100_used -= 1\n\n # wait for all GPUs to be available\n if len(checkpoint_finish_check) > 0:\n while True:\n time.sleep(5)\n for job in checkpoint_finish_check[:]:\n if checkpoint_dict['job'+job] == 1: # checkpoint has finished, gpu is free\n print(job + ' checkpointed successfully')\n checkpoint_dict['job'+job] = 0 # reset it\n checkpoint_finish_check.remove(job)\n # also check if job already finished before sending checkpoint signal\n elif finish_dict['job'+job] == 1:\n print(job + ' finished before receiving checkpoint signal')\n checkpoint_finish_check.remove(job)\n if len(checkpoint_finish_check) == 0:\n break\n\n # resume promoted jobs on V100, make sure the gpu is idle\n for job_new in promoted[:]:\n if finish_dict['job'+job_new] != 1:\n for gpu, job in V100_job.items():\n if job == 'idle': # if gpu idle, schedule new job here\n V100_job[gpu] = job_new\n real_node, real_gpu = V100_LUT(gpu) \n resume_job(real_node, real_gpu, job_new)\n num_mig[job_new] += 1\n promoted.remove(job_new)\n V100_used += 1\n break\n else: # job has already finished before checkpointing\n promoted.remove(job_new)\n\n # resume demoted jobs on K80, make sure the gpu is idle\n for job_new in demoted[:]:\n if finish_dict['job'+job_new] != 1:\n for gpu, job in K80_job.items():\n if job == 'idle': # if gpu idle, schedule new job here\n real_node, real_gpu = K80_LUT(gpu)\n resume_job(real_node, real_gpu, job_new)\n num_mig[job_new] += 1\n K80_job[gpu] = job_new\n demoted.remove(job_new)\n K80_used += 1\n break\n else: # job has already finished before checkpointing\n demoted.remove(job_new)\n\n # perform a check, make sure all promoted/demoted jobs are scheduled\n if len(promoted) > 0 or len(demoted) > 0:\n raise ValueError('Bug with promotion scheme, more jobs than free gpus')\n\n ################ submit new jobs to vacant K80 GPUs ############################\n\n # check if there are vacant K80s\n ## yes: submit jobs from queue\n ## no: do nothing\n if not all_jobs_started:\n if V100_used < V100_cap:\n V100_free = V100_cap - V100_used\n for i in range(V100_free):\n time_passed = int(time.time() - queue_timer)\n if index < len(queue) and queue_dict[queue[index]] < time_passed: # make sure job has arrived in the queue\n job_new = str(queue[index])\n for gpu, job in V100_job.items():\n if job == 'idle': # schedule new job here if idle\n real_node, real_gpu = V100_LUT(gpu)\n start_job(real_node, real_gpu, job_new)\n V100_job[gpu] = job_new\n job_start[job_new] = time.time()\n queue_delay[job_new] = int(time_passed - queue_dict[queue[index]]) \n V100_start_time[job_new] = time.time()\n index += 1\n V100_used += 1\n time.sleep(5) # don't communicate too often\n break\n elif index >= len(queue):\n all_jobs_started = True\n\n ############## monitor GPU usage ############\n\n usage = K80_used + V100_used\n time_stamp = int(time.time() - queue_timer)\n gpu_usage_time.append(time_stamp)\n gpu_usage.append(usage)\n total_completion = np.sum(list(completion.values()))\n gpu_usage_completion.append(total_completion)\n\n ############### wait for next iteration\n\n time.sleep(INTERVAL)\n\n ################ check if termination condition is met ################\n\n K80_idle_num = sum(value == 'idle' for value in K80_job.values())\n V100_idle_num = sum(value == 'idle' for value in V100_job.values())\n if K80_idle_num == K80_cap and V100_idle_num == V100_cap and index == len(queue):\n print('all jobs are finished!')\n break\n\n\n# get average JCT\naverage_JCT = np.average(list(JCT.values()))\nJCT['average'] = average_JCT\n\naverage_overhead = np.average(list(overhead.values()))\noverhead['average'] = average_overhead\n\naverage_queue_delay = np.average(list(queue_delay.values()))\nqueue_delay['average'] = average_queue_delay\n\n# after everything is finished\n\nprint('finished all runs')\nJCT_name = testcase + '_JCT.json'\noverhead_name = testcase + '_overhead.json'\nnum_mig_name = testcase + '_num_mig.json'\nepoch_waste_name = testcase + '_epoch_waste.json'\nckpt_qual_name = 'ckpt_qual.json'\nfinish_name = 'finish.json'\nK80_time_name = testcase + '_K80_time.json'\nV100_time_name = testcase + '_V100_time.json'\ngpu_usage_name = testcase + '_gpu_usage.csv'\novhd_a_name = testcase + '_ovhd_a.json'\novhd_b_name = testcase + '_ovhd_b.json'\novhd_c_name = testcase + '_ovhd_c.json'\novhd_d_name = testcase + '_ovhd_d.json'\novhd_total_name = testcase + '_ovhd_total.json'\nk80_1st_name = testcase + '_k80_1st.json'\nv100_1st_name = testcase + '_v100_1st.json'\nspeedup_name = 'speedup.json'\ncompletion_name = 'completion.json'\nqueue_delay_name = testcase + '_queue_delay.json'\n\nwith open(JCT_name, 'w') as fp1:\n json.dump(JCT, fp1, sort_keys=True, indent=4)\nwith open(overhead_name, 'w') as fp3:\n json.dump(overhead, fp3, sort_keys=True, indent=4)\nwith open(num_mig_name, 'w') as fp3:\n json.dump(num_mig, fp3, sort_keys=True, indent=4)\nwith open(epoch_waste_name, 'w') as fp3:\n json.dump(epoch_waste_dict, fp3, sort_keys=True, indent=4)\nwith open(ckpt_qual_name, 'w') as fp1:\n json.dump(ckpt_qual_dict, fp1, sort_keys=True, indent=4)\nwith open(finish_name, 'w') as fp1:\n json.dump(finish_dict, fp1, sort_keys=True, indent=4)\nwith open(K80_time_name, 'w') as fp3:\n json.dump(K80_time, fp3, sort_keys=True, indent=4)\nwith open(V100_time_name, 'w') as fp3:\n json.dump(V100_time, fp3, sort_keys=True, indent=4)\nwith open(ovhd_a_name, 'w') as fp3:\n json.dump(ovhd_a, fp3, sort_keys=True, indent=4)\nwith open(ovhd_b_name, 'w') as fp3:\n json.dump(ovhd_b, fp3, sort_keys=True, indent=4)\nwith open(ovhd_c_name, 'w') as fp3:\n json.dump(ovhd_c, fp3, sort_keys=True, indent=4)\nwith open(ovhd_d_name, 'w') as fp3:\n json.dump(ovhd_d, fp3, sort_keys=True, indent=4)\nwith open(ovhd_total_name, 'w') as fp3:\n json.dump(ovhd_total, fp3, sort_keys=True, indent=4)\nwith open(k80_1st_name, 'w') as fp3:\n json.dump(k80_1st, fp3, sort_keys=True, indent=4)\nwith open(v100_1st_name, 'w') as fp3:\n json.dump(v100_1st, fp3, sort_keys=True, indent=4)\nwith open(speedup_name, 'w') as fp1:\n json.dump(speedup_dict, fp1, sort_keys=True, indent=4)\nwith open(completion_name, 'w') as fp1:\n json.dump(completion, fp1, sort_keys=True, indent=4)\nwith open(queue_delay_name, 'w') as fp1:\n json.dump(queue_delay, fp1, sort_keys=True, indent=4)\n\ngpu_usage_time = np.asarray(gpu_usage_time)\ngpu_usage = np.asarray(gpu_usage)\ngpu_usage_completion = np.asarray(gpu_usage_completion)\nrows = zip(gpu_usage_time, gpu_usage, gpu_usage_completion)\nwith open(gpu_usage_name, 'w') as f:\n writer = csv.writer(f)\n for row in rows:\n writer.writerow(row)\n\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0005\nargs_model = 'resnet101'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1_test/' + job_name + '*'\n\ntotal_epochs = 35\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet101_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch and args.resume:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.002\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '*'\n\ntotal_epochs = 7\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final2_inverse/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.resnet import ResNet50, ResNet101, ResNet152\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 64\nargs_lr = 0.0006\nargs_model = 'resnet50'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final2/' + job_name + '*'\n\ntotal_epochs = 50\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '50' in args_model:\n base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '101' in args_model:\n base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '152' in args_model:\n base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n #model.add(layers.UpSampling2D((2,2)))\n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final2/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.002\nargs_model = 'mnasnet'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1/' + job_name + '*'\n\ntotal_epochs = 50\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n elif epoch == starting_epoch:\n first_epoch_start = time.time() \n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n progress = round((epoch+1) / round(total_epochs/2), 2)\n message = job_name + ' completion ' + str(progress)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.mobilenet_v2 import MobileNetV2\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.0025\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_final1_test/' + job_name + '*'\n\ntotal_epochs = 212\nstarting_epoch = 0\n\n# first step is to update the PID\npid = os.getpid()\nmessage = job_name + ' pid ' + str(pid) # 'job50 pid 3333'\nsend_signal.send(args.node, 10002, message)\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n message = job_name + ' b_end'\n send_signal.send(args.node, 10002, message)\n model = keras.models.load_model(save_file)\n message = job_name + ' c_end'\n send_signal.send(args.node, 10002, message)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'\n if epoch_waste_time > 0:\n send_signal.send(args.node, 10002, message)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_final1_test/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n message = job_name + ' checkpoint'\n send_signal.send(args.node, 10002, message)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nfirst_epoch_start = 0\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch, first_epoch_start\n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n if epoch == starting_epoch and args.resume:\n first_epoch_start = time.time()\n message = job_name + ' d_end'\n send_signal.send(args.node, 10002, message)\n if epoch == starting_epoch:\n # send signal to indicate checkpoint is qualified\n message = job_name + ' ckpt_qual'\n send_signal.send(args.node, 10002, message)\n\n\n def on_epoch_end(self, epoch, logs=None):\n if epoch == starting_epoch and args.resume:\n first_epoch_time = int(time.time() - first_epoch_start)\n message = job_name + ' 1st_epoch ' + str(first_epoch_time)\n send_signal.send(args.node, 10002, message)\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 32\nargs_lr = 0.0015\nargs_model = 'vgg16'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_v100_only/' + job_name + '*'\n\ntotal_epochs = 70\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n if '16' in args_model:\n base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n elif '19' in args_model:\n base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))\n #model.add(layers.Dropout(0.2))\n model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_v100_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n", "\"\"\"\n#Trains a ResNet on the CIFAR10 dataset.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras import models, layers, optimizers\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pdb\nimport sys\nimport argparse\nimport time\nimport signal\nimport glob\nimport json\nimport send_signal\n\nparser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')\nparser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')\nparser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')\nparser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')\nparser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')\nparser.set_defaults(resume=False)\nargs = parser.parse_args()\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu_num\n\n# Training parameters\nbatch_size = 256\nargs_lr = 0.001\nargs_model = 'mnasnet'\n\nepoch_begin_time = 0\n\njob_name = sys.argv[0].split('.')[0]\nsave_files = '/scratch/li.baol/checkpoint_v100_only/' + job_name + '*'\n\ntotal_epochs = 20\nstarting_epoch = 0\n\n# first step is to update the PID\npid_dict = {}\nwith open('pid_lock.json', 'r') as fp:\n pid_dict = json.load(fp)\npid_dict[job_name] = os.getpid()\njson_file = json.dumps(pid_dict)\nwith open('pid_lock.json', 'w') as fp:\n fp.write(json_file) \nos.rename('pid_lock.json', 'pid.json')\n\nif args.resume:\n save_file = glob.glob(save_files)[0]\n# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])\n starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])\n\ndata_augmentation = True\nnum_classes = 10\n\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nn = 3\n\n# Model name, depth and version\nmodel_type = args.tc #'P100_resnet50_he_256_1'\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n# Normalize data.\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\n# If subtract pixel mean is enabled\nif subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint('y_train shape:', y_train.shape)\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nif args.resume:\n print('resume from checkpoint')\n model = keras.models.load_model(save_file)\nelse:\n print('train from start')\n model = models.Sequential()\n \n base_model = NASNetMobile(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)\n \n #base_model.summary()\n \n #pdb.set_trace()\n \n model.add(base_model)\n model.add(layers.Flatten())\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(128, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n #model.add(layers.Dense(64, activation='relu'))\n #model.add(layers.Dropout(0.5))\n #model.add(layers.BatchNormalization())\n model.add(layers.Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=args_lr),\n metrics=['accuracy'])\n \n #model.summary()\n print(model_type)\n\n#pdb.set_trace()\n\ncurrent_epoch = 0\n\n################### connects interrupt signal to the process #####################\n\ndef terminateProcess(signalNumber, frame):\n # first record the wasted epoch time\n global epoch_begin_time\n if epoch_begin_time == 0:\n epoch_waste_time = 0\n else:\n epoch_waste_time = int(time.time() - epoch_begin_time)\n\n epoch_waste_dict = {}\n with open('epoch_waste.json', 'r') as fp:\n epoch_waste_dict = json.load(fp)\n epoch_waste_dict[job_name] += epoch_waste_time\n json_file3 = json.dumps(epoch_waste_dict)\n with open('epoch_waste.json', 'w') as fp:\n fp.write(json_file3)\n\n print('checkpointing the model triggered by kill -15 signal')\n # delete whatever checkpoint that already exists\n for f in glob.glob(save_files):\n os.remove(f)\n model.save('/scratch/li.baol/checkpoint_v100_only/' + job_name + '_' + str(current_epoch) + '.h5')\n print ('(SIGTERM) terminating the process')\n\n checkpoint_dict = {}\n with open('checkpoint.json', 'r') as fp:\n checkpoint_dict = json.load(fp)\n checkpoint_dict[job_name] = 1\n json_file3 = json.dumps(checkpoint_dict)\n with open('checkpoint.json', 'w') as fp:\n fp.write(json_file3)\n\n sys.exit()\n\nsignal.signal(signal.SIGTERM, terminateProcess)\n\n#################################################################################\n\nlogdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name\n\ntensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')\n\nclass PrintEpoch(keras.callbacks.Callback):\n def on_epoch_begin(self, epoch, logs=None):\n global current_epoch \n #remaining_epochs = epochs - epoch\n current_epoch = epoch\n print('current epoch ' + str(current_epoch))\n global epoch_begin_time\n epoch_begin_time = time.time()\n\nmy_callback = PrintEpoch()\n\ncallbacks = [tensorboard_callback, my_callback]\n #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]\n\n# Run training\n\n# send signal to indicate checkpoint is qualified\nmessage = job_name + ' ckpt_qual'\nsend_signal.send(args.node, 10002, message)\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=round(total_epochs/2),\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks,\n initial_epoch=starting_epoch,\n verbose=1\n )\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n\n# send signal to indicate job has finished\nmessage = job_name + ' finish'\nsend_signal.send(args.node, 10002, message)\n" ]
[ [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "pandas.read_csv", "matplotlib.use", "sklearn.model_selection.train_test_split", "sklearn.metrics.mean_squared_error", "sklearn.neighbors.KNeighborsRegressor", "numpy.mean", "sklearn.linear_model.LinearRegression" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "matplotlib.ticker.MultipleLocator", "pandas.read_csv", "numpy.asarray", "matplotlib.use", "matplotlib.pyplot.subplots", "pandas.DataFrame", "numpy.average" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean", "numpy.sqrt" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.median", "numpy.mean", "numpy.sum" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "matplotlib.ticker.MultipleLocator", "pandas.read_csv", "numpy.amax", "numpy.amin", "matplotlib.use", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.std", "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.sum", "tensorflow.device", "numpy.mean", "numpy.median" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.asarray", "numpy.random.poisson" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ], [ "numpy.mean" ] ]
[ { "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": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "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": [] }, { "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": [] }, { "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": [] }, { "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": [] }, { "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": [] }, { "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": [], "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": [] }, { "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": [] }, { "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": [ "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": [], "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": [] }, { "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": [] }, { "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": [] } ]
woanderer/neuroformer
[ "df3462d55977b6c9adcb6753e7c474b8b76e8021", "df3462d55977b6c9adcb6753e7c474b8b76e8021", "df3462d55977b6c9adcb6753e7c474b8b76e8021", "df3462d55977b6c9adcb6753e7c474b8b76e8021" ]
[ ".history/neuroformer/model_perceiver_20220116213408.py", ".history/neuroformer/model_perceiver_20220121144506.py", ".history/neuroformer/model_perceiver_20220121172442.py", ".history/neuroformer/perceiver_20220112195138.py" ]
[ "# from code.transformer_vid.utils import convert_weights\n# import rotary_embedding_torch\nfrom torch.nn.modules.activation import GELU, ReLU\n# from data.OneCombo3.trainer import TrainerConfig\nimport math\nimport numpy as np\nimport itertools\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torchvision.models.video import r3d_18\n# from ResNet3D import r3d_18\n\nfrom scipy.optimize import linear_sum_assignment\n# from rotary_embedding_torch import apply_rotary_emb, RotaryEmbedding\n\nfrom einops.layers.torch import Rearrange\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_weights(model: nn.Module):\n \"\"\"Convert applicable model parameters to fp16\"\"\"\n\n def _convert_weights_to_fp16(l):\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): # nn.Conv3d,\n l.weight.data = l.weight.data.half()\n if l.bias is not None:\n l.bias.data = l.bias.data.half()\n\n if isinstance(l, nn.MultiheadAttention):\n for attr in [*[f\"{s}_proj_weight\" for s in [\"in\", \"q\", \"k\", \"v\"]], \"in_proj_bias\", \"bias_k\", \"bias_v\"]:\n tensor = getattr(l, attr)\n if tensor is not None:\n tensor.data = tensor.data.half()\n\n for name in [\"text_projection\", \"proj\"]:\n if hasattr(l, name):\n attr = getattr(l, name)\n if attr is not None:\n attr.data = attr.data.half()\n\n model.apply(_convert_weights_to_fp16)\n\nclass GPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n embd_pdrop = 0.2\n resid_pdrop = 0.2\n attn_pdrop = 0.2\n pos_pdrop = 0.2\n temp_pdrop = 0.2\n pos_emb = True\n temp_emb = True\n start_prune = 30\n epoch = 0\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\nclass neuralGPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n n = 0.4\n im_drop = 0.2\n id_drop = n\n embd_pdrop = n\n resid_pdrop = n\n attn_pdrop = n\n pos_pdrop = n\n temp_pdrop = n\n pos_emb = True\n temp_emb = True\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass GPT1Config(GPTConfig):\n \"\"\" GPT-1 like network roughly 125M params \"\"\"\n n_layer = 12\n n_head = 12\n n_embd = 768\n\n\nclass VideoFeaturesExtractor(nn.Module):\n \"\"\" \n R3D: (3 x T x H x W)\n H, W = 112\n \"\"\"\n \n def __init__(self):\n super().__init__()\n self.backbone = torch.nn.Sequential(*(list(r3d_18(pretrained=True).children())[:-2]))\n convert_weights(self.backbone)\n # # freeze backbone\n # for k, v in self.backbone.named_parameters():\n # v.requires_grad = False\n\n def forward(self, x):\n # B = Batch, T, C, Fm, H, W\n features = self.backbone(x) # (B, C, T, H, W)\n B, C, T, H, W = features.shape\n features = features.permute(0, 2, 3, 4, 1)\n features = features.view(B, -1, C)\n return features\n\nclass VideoEncoder(nn.Module):\n def __init__(self):\n super().__init__()\n self.to_patch_embedding = nn.Sequential(\n Rearrange('b c t (h p1) (w p2) -> b (t h w) (p1 p2 c)', p1=16, p2=16)\n )\n \n def forward(self, x):\n return self.to_patch_embedding(x)\n\n\nclass CausalSelfAttention(nn.Module):\n \"\"\"\n A vanilla multi-head masked self-attention layer with a projection at the end.\n \n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n assert config.n_embd % config.n_head == 0\n self.config = config\n # key, query, value projections for all heads\n self.key = nn.Linear(config.n_embd, config.n_embd)\n self.query = nn.Linear(config.n_embd, config.n_embd)\n self.value = nn.Linear(config.n_embd, config.n_embd)\n # regularization\n self.attn_drop = nn.Dropout(config.attn_pdrop)\n self.resid_drop = nn.Dropout(config.resid_pdrop)\n # output projection\n self.proj = nn.Linear(config.n_embd, config.n_embd)\n\n self.register_buffer(\"mask\", self.build_mask(config.block_size)) \n self.n_head = config.n_head\n\n self.att = None\n self.T = config.block_size\n\n # self.rotary_embedding = RotarySpatioTemporalEmbedding(config)\n \n def build_mask(self, block_size):\n mask = torch.tril(torch.ones((block_size, block_size)),\n ).view(1, 1, block_size, block_size)\n return mask\n \n def generate_sparse_mask(self, att, p, config):\n \"\"\"\n Generate a sparse mask according to p.\n \"\"\"\n assert p >= 0 and p <= 1, \"p should be in [0, 1]\"\n T = config.block_size\n mask = torch.rand((1, T)) < p\n mask = mask.repeat(T, 1)\n \n mask[0, 0] = False # don't mask 1st step\n # check if any step is fully masked and umask it\n idx_all_true = (True == torch.all(mask, dim=0)).nonzero()\n for step in idx_all_true:\n sampler = torch.distributions.Uniform(low=0, high=step.item()+1)\n idx_false = sampler.sample((1,1)).long()\n mask[step, idx_false] = False\n\n # mask = mask.repeat(T, 1)\n mask = mask.view(1, 1, T, T).cuda() if att.is_cuda else mask.view(1, 1, T, T)\n att = att.masked_fill(mask, float('-inf'))\n return att\n\n def forward(self, x, pad=None, dtx=None):\n # B = Batch, T = Sequence, C = n_embed\n B, T, C = x.size()\n\n # calculate query, key, values for all head in batch and move head forward to the batch dim\n k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n\n # # apply rotary embeddings\n # if dtx is not None:\n # q, k = self.rotary_embedding(q, k, dtx)\n\n # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)\n att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))\n if self.training:\n att = self.generate_sparse_mask(att, 0.25, self.config)\n if pad is not None:\n for idx, i in enumerate(pad):\n att[idx, :, :, self.T - i:] = float('-inf') # only able to see first padding token\n \n att = F.softmax(att, dim=-1)\n att = self.attn_drop(att)\n self.att = att\n y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side\n\n # output projection\n y = self.resid_drop(self.proj(y))\n return y\n\n\nclass PositionalEmbedding(nn.Module):\n \"\"\" Implement the PE function. \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\n# class RotarySpatioTemporalEmbedding(nn.Module):\n# \"\"\" Rotary temporal embeddings - block_size = id_blk_sz \"\"\"\n# def __init__(self, config):\n# super().__init__()\n# self.frame_block_size = config.frame_block_size\n# self.id_block_size = config.id_block_size\n# self.emb = RotaryEmbedding(dim=32)\n\n# def forward(self, q, k, t):\n# b = t.shape[0]\n# tf = self.frame_block_size\n# queries = []\n# keys = []\n# for B in range(b):\n# im_temp_emb = torch.tensor([-0.5] * (tf//2) + [0.5] * (tf//2))\n# im_pos_emb = torch.arange(self.frame_block_size)\n# im_emb = torch.stack([im_temp_emb, im_pos_emb], dim=0)\n# id_temp_emb = self.temp_emb(t[B], cache_key=self.block_size)\n# freqs = self.emb(torch.cat(im_emb, id_temp_emb))\n# queries.append(apply_rotary_emb(freqs, q[B][None, ...]))\n# keys.append(apply_rotary_emb(freqs, k[B][None, ...]))\n# q, k = torch.cat(queries), torch.cat(keys)\n# return q, k\n\n\nclass TemporalEmbedding(nn.Module):\n \"\"\" encoding temporal information using fourrier signals \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\nclass LearntTemporalEmbedding(nn.Module):\n \"\"\"\n Project B x T x 1 time sequence to\n B x T x C\n \"\"\"\n def __init__(self, block_sz, n_embd, p_drop=0.2):\n super().__init__()\n self.temp_emb = nn.Sequential(\n nn.Linear(1, n_embd // 2),\n nn.GELU(),\n nn.Linear(n_embd // 2, n_embd),\n nn.Dropout(p_drop)\n )\n \n def forward(self, x):\n return self.temp_emb(x.unsqueeze(-1))\n\n\nclass Decoder(nn.Module):\n\n def __init__(self, config):\n super().__init__()\n # decoder_layer = nn.TransformerDecoderLayer(config.n_embd, config.n_head, \n # activation='gelu', dropout=0.2, batch_first=True)\n # self.decoder = nn.TransformerDecoder(decoder_layer, config.n_layer)\n self.decoder = nn.Transformer(d_model=config.n_embd, nhead=config.n_head, \n num_encoder_layers=3, num_decoder_layers=config.n_layer,\n activation=\"gelu\", dropout=0.4, batch_first=True)\n self.register_buffer(\"tgt_mask\", self.generate_square_subsequent_mask(config.id_block_size))\n # self.register_buffer(\"tgt_pad_mask\", self.generate_padding_mask(config.ids_block_size))\n self.T = config.id_block_size\n\n def generate_square_subsequent_mask(self, sz: int, pad=None):\n r\"\"\"Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n Unmasked positions are filled with float(0.0).\n \"\"\"\n mask = (torch.triu(torch.ones(sz, sz), diagonal=0) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n \n def generate_padding_mask(self, sz: int, pad=None):\n r\"\"\"Build a (B x T) mask that resides on the GPU and can be \n manipulated by build_padding_mask according to padded sequence\n \"\"\"\n mask = torch.zeros(1, sz, dtype=torch.bool)\n return mask\n\n def generate_sparse_mask(self, sz: int, pad=None):\n r\"\"\" Build a square mask that employs \n teacher forcing according to P\n \"\"\"\n rand_mat = torch.rand(1, sz)\n k = round(0.75 * sz)\n k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]\n bool_tensor = rand_mat <= k_th_quant\n mask = torch.where(bool_tensor, torch.tensor(1), torch.tensor(0)).repeat(sz, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask.cuda(self.tgt_mask.get_device()) if self.tgt_mask.is_cuda else mask\n \n def build_padding_mask(self, tgt, pad):\n # mask = self.tgt_pad_mask.repeat(tgt.shape[0], 1)\n mask = torch.zeros(tgt.shape[0], self.T, dtype=torch.bool)\n for B, P in enumerate(pad):\n mask[B, self.T - P:] = True\n return mask # .to(torch.cuda.current_device())\n\n def forward(self, tgt, memory, pad):\n # padding_mask = self.build_padding_mask(tgt, pad)\n # tgt_mask = self.generate_sparse_mask(self.T) if self.training else self.tgt_mask\n return self.decoder(src=memory, tgt=tgt, tgt_mask=self.tgt_mask, \n tgt_key_padding_mask=None)\n\n\nclass ProjectNorm(nn.Module):\n\n def __init__(self, feat_size, target_size):\n super().__init__()\n self.ln = nn.LayerNorm(feat_size)\n self.mlp = nn.Sequential(\n nn.Linear(feat_size, math.floor(2 * feat_size), bias=False),\n nn.GELU(),\n nn.Linear(math.floor(2 * feat_size), target_size, bias=False),\n )\n\n def forward(self, x):\n return self.mlp(self.ln(x))\n\n\nclass TimeProjection(nn.Module):\n \n def __init__(self, seq_size, id_seq_size, feat_size, target_size):\n super().__init__()\n self.mlp_seq = nn.Sequential(\n nn.Linear(seq_size, id_seq_size),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(id_seq_size, id_seq_size)\n )\n self.mlp_t = nn.Sequential(\n nn.Linear(feat_size, feat_size // 2),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(feat_size // 2, target_size)\n )\n \n def forward(self, x):\n x = x.permute(0, 2, 1) # B, T, C -> B, C, T\n x = self.mlp_seq(x) # B, C, T / 2\n x = x.permute(0, 2, 1) # B, T / 2, C\n return self.mlp_t(x) # B, T / 2, 1\n\n\nclass PSTHProjection(nn.Module):\n \"\"\"Takes Last Output of Block -> (B, C) \n Builds PSTH table \n \"\"\"\n def __init__(self, config):\n super().__init__()\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd, bias=False),\n nn.Dropout(p=0.2),\n nn.GELU(),\n nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n )\n \n def forward(self, x):\n return self.mlp(x)\n\n\n# class PSTHProjection(nn.Module):\n \n# def __init__(self, config):\n# super().__init__()\n# self.mlp_seq = nn.Sequential(\n# nn.Linear(config.id_block_size, config.id_block_size // 2, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.id_block_size // 2, 1, bias=False)\n# )\n# self.mlp_t = nn.Sequential(\n# nn.Linear(config.n_embd, config.n_embd * 4, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n# )\n \n# def forward(self, x):\n# x = x.transpose(-1, -2) # B, T, C -> B, C, T\n# x = self.mlp_seq(x) # B, C, 1\n# x = x.transpose(-2, -1) # B, 1, Vocab_id\n# return self.mlp_t(x)\n\n\nclass TimeRNN(nn.Module):\n def __init__(self, feat_size, target_size):\n super().__init__()\n\n\nclass Block(nn.Module):\n \"\"\" an unassuming Transformer block \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.ln1 = nn.LayerNorm(config.n_embd)\n self.ln2 = nn.LayerNorm(config.n_embd)\n self.attn = CausalSelfAttention(config)\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd),\n nn.GELU(),\n nn.Linear(4 * config.n_embd, config.n_embd),\n nn.Dropout(config.resid_pdrop),\n )\n\n def forward(self, x, pad=None, dtx=None):\n x = x + self.attn(self.ln1(x), pad)\n x = x + self.mlp(self.ln2(x))\n return x\n\n\nclass BlockSequential(nn.Sequential):\n def forward(self, x, pad=None, dtx=None):\n for module in self._modules.values():\n x = module(x, pad, dtx)\n return x\n\n\nclass DiceLossPSTH(nn.Module):\n def __init__(self, size_average=True, smooth=1):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets, smooth=1, class_weights=None):\n total_logits = F.layer_norm(torch.sum(logits, dim=-2), [logits.size()[-1]])\n # probs = F.log_softmax(logits, dim=-1)\n probs = F.softmax(total_logits, dim=-1)\n # logits = F.gelu(logits)\n # probs = logits / (logits.max(dim=-1).values.unsqueeze(-1))\n # flatten label and prediction tensors\n outputs = probs.contiguous().view(-1)\n targets = targets.contiguous().view(-1)\n labels = torch.zeros_like(outputs)\n labels[targets] = 1 / len(targets)\n # intersection = (outputs * labels).sum()\n # dice = (2. * intersection + smooth) / (outputs.sum() + labels.sum() + smooth)\n return self.cross_entropy(outputs[None, ...], labels[None, ...])\n\n\nclass SetLoss(nn.Module):\n def __init__(self):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets):\n targets = targets.contiguous().view(-1)\n loss = 0\n for n_step, n_logits in enumerate(logits):\n n_logits = F.softmax(n_logits, dim=-1)\n n_target = targets[n_step:]\n n_target_dist = torch.zeros_like(n_logits)\n if len(n_target) != 0:\n n_target_dist[n_target] = 1 / len(n_target)\n loss += self.cross_entropy(n_logits[None,...], n_target_dist[None, ...])\n return loss / len(logits)\n\n\nclass TruncatedLoss(nn.Module):\n\n def __init__(self, q=0.8, k=0.2, trainset_size=50000):\n super(TruncatedLoss, self).__init__()\n self.q = q\n self.k = k\n self.weight = torch.nn.Parameter(data=torch.ones(trainset_size, 1), requires_grad=False)\n \n def forward(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n\n loss = ((1-(Yg**self.q))/self.q)*self.weight[indexes] - ((1-(self.k**self.q))/self.q)*self.weight[indexes]\n loss = torch.mean(loss)\n\n return loss\n\n def update_weight(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n Lq = ((1-(Yg**self.q))/self.q)\n Lqk = np.repeat(((1-(self.k**self.q))/self.q), targets.size(0))\n Lqk = torch.from_numpy(Lqk).type(torch.cuda.FloatTensor)\n Lqk = torch.unsqueeze(Lqk, 1)\n \n condition = torch.gt(Lqk, Lq)\n self.weight[indexes] = condition.type(torch.cuda.FloatTensor)\n\n\n# class PSTHLOSS(nn.Module):\n# def __init__(self):\n# super().__init__()\n\n# def forward(self, logits, targets):\n# total_logits = torch.sum(logits, dim=-2) # sum over sequence dimension\n# probs = F.softmax(total_logits, dim=-1)\n# outptu\n\n\nclass HungarianMatcher(nn.Module):\n def __init__(self):\n super().__init__()\n \n @torch.no_grad()\n def forward(self, logits, targets):\n T, C = logits.size()\n probs = F.softmax(logits, dim=-1)\n cost_id = (1 - probs[:, targets]).cpu().view(T, -1).unsqueeze(0)\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_id.split(len(targets), -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\nclass KLDivLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n self.KLdiv = nn.KLDivLoss()\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.KLdiv(log_probs.long(), targets)\n\n\nclass PoissonCrossEntropyLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n # self.softmax = nn.Softmax(dim=-1)\n self.nll_poisson = nn.PoissonNLLLoss()\n # self.nll_poisson = nn.NLLLoss()\n\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.nll_poisson(log_probs, targets)\n\n\nclass GPT(nn.Module):\n \"\"\" the full GPT language model, with a context size of block_size \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n self.device = 'cpu'\n if torch.cuda.is_available():\n self.device = torch.cuda.current_device()\n\n self.config = config\n # input embedding stem\n self.n_embd = config.n_embd\n self.tok_emb = nn.Embedding(config.id_vocab_size, config.n_embd)\n self.pos_emb = PositionalEmbedding(config.n_embd, p_drop=0.2)\n # self.pos_emb_id = nn.Parameter(torch.zeros(1, config.id_block_size, config.n_embd))\n self.pos_emb_frames = nn.Parameter(torch.zeros(1, config.frame_block_size, config.n_embd))\n # self.temp_emb = TemporalEmbedding(config.n_embd, p_drop=0.2)\n # self.temp_emb = RotaryTemporalEmbedding(config.id_block_size)\n self.temp_emb = LearntTemporalEmbedding(config.id_block_size, config.n_embd)\n self.frame_temp_emb = LearntTemporalEmbedding(config.frame_block_size, config.n_embd)\n self.id_drop = nn.Dropout(config.id_drop)\n self.im_drop = nn.Dropout(config.im_drop)\n self.drop = nn.Dropout(config.embd_pdrop)\n\n # -- Visual Backbone -- #\n # self.visual_backbone = VideoFeaturesExtractor()\n self.video_encoder = VideoEncoder()\n frame_temp_emb = torch.tensor(list(itertools.chain(*[[n * 0.05] * (config.frame_block_size//20) for n in range(20)]))).unsqueeze(0)\n self.register_buffer(\"frame_temp_emb_seq\", frame_temp_emb)\n\n # -- Contrastive Loss -- ##\n # self.proj_id = ProjectNorm(config.n_embd, config.n_embd)\n # self.proj_vid = VidProjectNorm(config.n_embd, config.n_embd) # im_shape\n \n ## -- IM_Decoder -- ##\n # self.blocks_id = BlockSequential(*[Block(config) for _ in range(2)])\n # self.blocks_im = BlockSequential(*[Block(config) for _ in range(2)])\n # self.ln_f_id = nn.LayerNorm(config.n_embd)\n # self.ln_f_im = nn.LayerNorm(config.n_embd)\n\n ## -- Decoder -- ##\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## GPT\n # self.blocks = BlockSequential(*[Block(config) for _ in range(config.n_layer)])\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## enc_dec\n self.state_decoder = Decoder(config)\n self.ln_f_state_dec = nn.LayerNorm(config.n_embd)\n self.stimulus_decoder = Decoder(config)\n self.ln_f_stimulus_dec = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n \n ## -- Time -- ##\n # self.proj_time = TimeProjection(config.block_size, config.id_block_size, config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, 1)\n \n ## -- PSTH -- ##\n # self.proj_psth = PSTHProjection(config)\n\n # Loss\n # self.dice_loss = DiceLossPSTH()\n # self.poisson_loss = PoissonCrossEntropyLoss()\n # self.hungarian_matcher = HungarianMatcher()\n # self.kldiv_loss = KLDivLoss()\n # self.truncated_loss = TruncatedLoss(trainset_size=config.data_size)\n # self.set_loss = SetLoss()\n # self.a = torch.tensor(0.5, requires_grad=True)\n\n self.block_size = config.block_size\n self.apply(self._init_weights)\n \n if config.class_weights is not None:\n self.register_buffer(\"class_weights\", config.class_weights) \n \n logger.info(\"number of parameters: %e\", sum(p.numel() for p in self.parameters()))\n\n def get_block_size(self):\n return self.block_size\n\n def _init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def configure_optimizers(self, train_config):\n \"\"\"\n Separates parameters into those who will experience weight decay and those that will not\n \"\"\"\n if train_config.decay_weights:\n decay = set()\n no_decay = set()\n whitelist_weight_modules = (torch.nn.Linear, )\n blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)\n for mn, m in self.named_modules():\n for pn, p in m.named_parameters():\n fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n if pn.endswith('bias'):\n # all biases will not be decayed\n no_decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):\n # weights of whitelist modules will be weight decayed\n decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):\n # weights of blacklist modules will NOT be weight decayed\n no_decay.add(fpn)\n else: no_decay.add(fpn)\n\n # special case the position embedding parameter in the root GPT module as not decayed\n black_list_mods = ['pos_emb', 'temp_emb']\n for mods in black_list_mods:\n for name, param in self.named_parameters():\n if mods in name:\n no_decay.add(name) # also pos_emb\n \n # validate that we considered every parameter\n param_dict = {pn: p for pn, p in self.named_parameters()}\n no_decay -= decay & no_decay\n inter_params = decay & no_decay\n union_params = decay | no_decay\n\n assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n % (str(param_dict.keys() - union_params), )\n\n \n # create the pytorch optimizer object\n optim_groups = [\n {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": train_config.weight_decay},\n {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n ]\n optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)\n \n else:\n parameters = self.parameters()\n optimizer = torch.optim.Adam(parameters, lr=train_config.learning_rate)\n \n return optimizer\n \n def process_features(self, x):\n # batch, block_size, feature\n p_idx = x['id_prev']\n idx = x['id']\n dtx = x['dt']\n dtx_prev = x['dt_prev']\n frames = self.video_encoder(x['frames'])\n pad = x['pad']\n\n b, t = idx.size()\n # b_p, t_p = p_idx.size()\n bf, tf = frames.size()[0:2]\n\n # forward the GPT model\n ''' \n positional and temporal embeddings implemented in multiple ways, learnt, \n fourrier decomposition and in the case of time, just passed as is. \n '''\n # # Embeddings\n prev_id_position_embeddings = 0 # self.pos_emb(p_idx)\n prev_id_temporal_embeddings = self.temp_emb(dtx_prev.float())\n id_position_embeddings = 0 # self.pos_emb(idx) \n im_position_embeddings = self.pos_emb_frames\n temporal_embeddings = self.temp_emb(dtx.float())\n \n # Extract ID features\n prev_token_embeddings = self.id_drop(self.tok_emb(p_idx) + prev_id_temporal_embeddings + prev_id_position_embeddings)\n token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector\n token_embeddings = token_embeddings + temporal_embeddings + id_position_embeddings\n token_embeddings = self.id_drop(token_embeddings)\n\n # Extract image features and add time embeddings\n im_temporal_embeddings = self.frame_temp_emb(self.frame_temp_emb_seq)\n im_embeddings = frames # self.tok_emb(frames)\n im_embeddings = im_embeddings + im_position_embeddings + im_temporal_embeddings\n im_embeddings = self.im_drop(im_embeddings) # separate pos emb?\n \n # Tidy up\n features = dict()\n features['id_prev'] = prev_token_embeddings\n features['id'] = token_embeddings\n features['frames'] = im_embeddings\n \n return features, pad\n\n def perceiver(self, features, pad):\n x = self.state_decoder(tgt=features['id'], memory=features['id_prev'], pad=pad)\n x = self.ln_f_state_dec(x)\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def enc_dec(self, features, pad):\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def GPTdecoder(self, features, pad, dtx=None):\n # image + neural features\n x = torch.cat((features['frames'], features['id']), dim=1)\n\n # Decoder\n x = self.blocks(x, pad, dtx) # (B, T, C)\n x = self.ln_f(x)\n logits = self.head(x)\n\n # print(logits.shape) # (B, T, Vocab)\n # logits_psth = x[:, -1] # (B, C)\n\n return logits, x\n\n def forward(self, x, targets=None):\n idx = x['id']\n dtx = x['dt']\n frames = x['frames']\n pad = x['pad']\n\n b, t = idx.size()\n # b, t = x['id'].shape[0], x['id'].shape[1] + x['id_prev'].shape[1]\n bf, tf = frames.size()[0:2]\n tf = self.config.frame_block_size\n # assert t + tf == self.config.block_size, f\"{tf} {t}\"\n # assert t <= self.block_size, \"Cannot forward, model block size is exhausted\"\n \n features, pad = self.process_features(x)\n logits, x = self.perceiver(features, pad)\n # logits, x = self.enc_dec(features, pad)\n # logits, x = self.GPTdecoder(features, pad)\n # time = self.proj_time(x) # (B, T_id, 1)\n\n # print(x[:, 0].shape)\n # psth = self.proj_psth(x) # (B, Vocab_id)\n\n # if targets, calculate loss\n # calculate loss on logits up to padding token for each batch\n loss = None\n loss_frames = 0\n loss_id = []\n loss_time = []\n loss_dice = []\n loss_psth = []\n loss_hungarian = []\n if targets is not None:\n # loss_psth = self.dice_loss(psth, targets['modes'][:, tf:]) \n for B, P in enumerate(pad):\n tf = 0\n # im_logits = logits[B, :tf]\n # im_targets = targets['frames'][B, :tf]\n # loss_frames += F.cross_entropy(im_logits.view(-1, im_logits.size(-1)), im_targets.view(-1))\n id_logits = logits[B, tf:tf + t - P]\n id_targets = targets['id'][B, :t - P]\n\n loss_id_ = F.cross_entropy(id_logits.view(-1, id_logits.size(-1)), id_targets.view(-1))\n # if self.config.epoch >= 15:\n # self.truncated_loss.update_weight(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # loss_id_ = self.truncated_loss(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # time_preds = time[B, :t - P]\n # time_targets = targets['dt'][B, :t - P]\n # loss_time_ = F.cross_entropy(time_preds.view(-1, time_preds.size(-1)), time_targets.view(-1))\n # loss_time_ = F.mse_loss(time_preds.squeeze(-1), time_targets)\n # loss_id_ = self.poisson_loss(id_logits.view(-1, id_logits.size(-1)), F.one_hot(id_targets, self.config.vocab_size))\n # if len(id_targets) > 0:\n # indices = self.hungarian_matcher(id_logits, id_targets)\n # probs_matching, targets_matching = id_logits[indices[0][0]], id_targets[indices[0][1]]\n # loss_hungarian_ = F.cross_entropy(probs_matching, targets_matching, weight=self.class_weights).to(self.device)\n # loss_hungarian.append(loss_hungarian_)\n # # psth = self.proj_psth(x[B, -1]) # from the EOS position\n \n # loss_psth.append(torch.nan_to_num(self.set_loss(id_logits, id_targets)))\n # loss_psth_ = self.dice_loss(id_logits, id_targets)\n # loss_psth.append(torch.nan_to_num(loss_psth_))\n \n # loss_time.append(torch.nan_to_num(loss_time_))\n loss_id.append(torch.nan_to_num(loss_id_))\n \n loss = dict()\n # loss['frames'] = loss_frames / (b / 3)\n loss['id'] = sum(loss_id) / (b) # sum(loss_id) / (b * 2) # / len(loss_id)\n # loss['time'] = sum(loss_time) / (b * 2)\n # loss['dice'] = sum(loss_dice) / len(loss_dice)\n # loss['dt'] = loss_time / (b * 50)\n # loss['hungarian'] = sum(loss_hungarian) / (b * 2)\n # loss['psth'] = sum(loss_psth) / (b * 2)\n\n for key in list(loss):\n if isinstance(loss[key], float):\n del loss[key]\n \n preds = dict()\n preds['logits'] = logits # [:, tf:] # only id logits\n # preds['dt'] = time\n\n return preds, features, loss", "# from code.transformer_vid.utils import convert_weights\n# import rotary_embedding_torch\nfrom torch.nn.modules.activation import GELU, ReLU\n# from data.OneCombo3.trainer import TrainerConfig\nimport math\nimport numpy as np\nimport itertools\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torchvision.models.video import r3d_18\n# from ResNet3D import r3d_18\n\nfrom scipy.optimize import linear_sum_assignment\n# from rotary_embedding_torch import apply_rotary_emb, RotaryEmbedding\n\nfrom einops.layers.torch import Rearrange\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_weights(model: nn.Module):\n \"\"\"Convert applicable model parameters to fp16\"\"\"\n\n def _convert_weights_to_fp16(l):\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): # nn.Conv3d,\n l.weight.data = l.weight.data.half()\n if l.bias is not None:\n l.bias.data = l.bias.data.half()\n\n if isinstance(l, nn.MultiheadAttention):\n for attr in [*[f\"{s}_proj_weight\" for s in [\"in\", \"q\", \"k\", \"v\"]], \"in_proj_bias\", \"bias_k\", \"bias_v\"]:\n tensor = getattr(l, attr)\n if tensor is not None:\n tensor.data = tensor.data.half()\n\n for name in [\"text_projection\", \"proj\"]:\n if hasattr(l, name):\n attr = getattr(l, name)\n if attr is not None:\n attr.data = attr.data.half()\n\n model.apply(_convert_weights_to_fp16)\n\nclass GPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n embd_pdrop = 0.2\n resid_pdrop = 0.2\n attn_pdrop = 0.2\n pos_pdrop = 0.2\n temp_pdrop = 0.2\n pos_emb = True\n temp_emb = True\n start_prune = 30\n epoch = 0\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\nclass neuralGPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n n = 0.4\n im_drop = 0.2\n id_drop = n\n embd_pdrop = n\n resid_pdrop = n\n attn_pdrop = n\n pos_pdrop = n\n temp_pdrop = n\n pos_emb = True\n temp_emb = True\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass GPT1Config(GPTConfig):\n \"\"\" GPT-1 like network roughly 125M params \"\"\"\n n_layer = 12\n n_head = 12\n n_embd = 768\n\n\nclass VideoFeaturesExtractor(nn.Module):\n \"\"\" \n R3D: (3 x T x H x W)\n H, W = 112\n \"\"\"\n \n def __init__(self):\n super().__init__()\n self.backbone = torch.nn.Sequential(*(list(r3d_18(pretrained=True).children())[:-2]))\n convert_weights(self.backbone)\n # # freeze backbone\n # for k, v in self.backbone.named_parameters():\n # v.requires_grad = False\n\n def forward(self, x):\n # B = Batch, T, C, Fm, H, W\n features = self.backbone(x) # (B, C, T, H, W)\n B, C, T, H, W = features.shape\n features = features.permute(0, 2, 3, 4, 1)\n features = features.view(B, -1, C)\n return features\n\nclass VideoEncoder(nn.Module):\n def __init__(self, n_embd):\n super().__init__()\n p1, p2 = 16\n \n assert n_embd % (p1 * p2) == 0, \"n_embd must be divisible by p1 * p2\"\n \n c = n_embd // (p1 * p2) \n self.to_patch_embedding = nn.Sequential(\n Rearrange(f'b {c} t (h {p1}) (w {p2}) -> b (t h w) (p1 p2 {c})', p1=16, p2=16)\n )\n \n def forward(self, x):\n return self.to_patch_embedding(x)\n\n\nclass CausalSelfAttention(nn.Module):\n \"\"\"\n A vanilla multi-head masked self-attention layer with a projection at the end.\n \n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n assert config.n_embd % config.n_head == 0\n self.config = config\n # key, query, value projections for all heads\n self.key = nn.Linear(config.n_embd, config.n_embd)\n self.query = nn.Linear(config.n_embd, config.n_embd)\n self.value = nn.Linear(config.n_embd, config.n_embd)\n # regularization\n self.attn_drop = nn.Dropout(config.attn_pdrop)\n self.resid_drop = nn.Dropout(config.resid_pdrop)\n # output projection\n self.proj = nn.Linear(config.n_embd, config.n_embd)\n\n self.register_buffer(\"mask\", self.build_mask(config.block_size)) \n self.n_head = config.n_head\n\n self.att = None\n self.T = config.block_size\n\n # self.rotary_embedding = RotarySpatioTemporalEmbedding(config)\n \n def build_mask(self, block_size):\n mask = torch.tril(torch.ones((block_size, block_size)),\n ).view(1, 1, block_size, block_size)\n return mask\n \n def generate_sparse_mask(self, att, p, config):\n \"\"\"\n Generate a sparse mask according to p.\n \"\"\"\n assert p >= 0 and p <= 1, \"p should be in [0, 1]\"\n T = config.block_size\n mask = torch.rand((1, T)) < p\n mask = mask.repeat(T, 1)\n \n mask[0, 0] = False # don't mask 1st step\n # check if any step is fully masked and umask it\n idx_all_true = (True == torch.all(mask, dim=0)).nonzero()\n for step in idx_all_true:\n sampler = torch.distributions.Uniform(low=0, high=step.item()+1)\n idx_false = sampler.sample((1,1)).long()\n mask[step, idx_false] = False\n\n # mask = mask.repeat(T, 1)\n mask = mask.view(1, 1, T, T).cuda() if att.is_cuda else mask.view(1, 1, T, T)\n att = att.masked_fill(mask, float('-inf'))\n return att\n\n def forward(self, x, pad=None, dtx=None):\n # B = Batch, T = Sequence, C = n_embed\n B, T, C = x.size()\n\n # calculate query, key, values for all head in batch and move head forward to the batch dim\n k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n\n # # apply rotary embeddings\n # if dtx is not None:\n # q, k = self.rotary_embedding(q, k, dtx)\n\n # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)\n att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))\n if self.training:\n att = self.generate_sparse_mask(att, 0.25, self.config)\n if pad is not None:\n for idx, i in enumerate(pad):\n att[idx, :, :, self.T - i:] = float('-inf') # only able to see first padding token\n \n att = F.softmax(att, dim=-1)\n att = self.attn_drop(att)\n self.att = att\n y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side\n\n # output projection\n y = self.resid_drop(self.proj(y))\n return y\n\n\nclass PositionalEmbedding(nn.Module):\n \"\"\" Implement the PE function. \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\n# class RotarySpatioTemporalEmbedding(nn.Module):\n# \"\"\" Rotary temporal embeddings - block_size = id_blk_sz \"\"\"\n# def __init__(self, config):\n# super().__init__()\n# self.frame_block_size = config.frame_block_size\n# self.id_block_size = config.id_block_size\n# self.emb = RotaryEmbedding(dim=32)\n\n# def forward(self, q, k, t):\n# b = t.shape[0]\n# tf = self.frame_block_size\n# queries = []\n# keys = []\n# for B in range(b):\n# im_temp_emb = torch.tensor([-0.5] * (tf//2) + [0.5] * (tf//2))\n# im_pos_emb = torch.arange(self.frame_block_size)\n# im_emb = torch.stack([im_temp_emb, im_pos_emb], dim=0)\n# id_temp_emb = self.temp_emb(t[B], cache_key=self.block_size)\n# freqs = self.emb(torch.cat(im_emb, id_temp_emb))\n# queries.append(apply_rotary_emb(freqs, q[B][None, ...]))\n# keys.append(apply_rotary_emb(freqs, k[B][None, ...]))\n# q, k = torch.cat(queries), torch.cat(keys)\n# return q, k\n\n\nclass TemporalEmbedding(nn.Module):\n \"\"\" encoding temporal information using fourrier signals \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\nclass LearntTemporalEmbedding(nn.Module):\n \"\"\"\n Project B x T x 1 time sequence to\n B x T x C\n \"\"\"\n def __init__(self, block_sz, n_embd, p_drop=0.2):\n super().__init__()\n self.temp_emb = nn.Sequential(\n nn.Linear(1, n_embd // 2),\n nn.GELU(),\n nn.Linear(n_embd // 2, n_embd),\n nn.Dropout(p_drop)\n )\n \n def forward(self, x):\n return self.temp_emb(x.unsqueeze(-1))\n\n\nclass Decoder(nn.Module):\n\n def __init__(self, config):\n super().__init__()\n # decoder_layer = nn.TransformerDecoderLayer(config.n_embd, config.n_head, \n # activation='gelu', dropout=0.2, batch_first=True)\n # self.decoder = nn.TransformerDecoder(decoder_layer, config.n_layer)\n self.decoder = nn.Transformer(d_model=config.n_embd, nhead=config.n_head, \n num_encoder_layers=3, num_decoder_layers=config.n_layer,\n activation=\"gelu\", dropout=0.4, batch_first=True)\n self.register_buffer(\"tgt_mask\", self.generate_square_subsequent_mask(config.id_block_size))\n # self.register_buffer(\"tgt_pad_mask\", self.generate_padding_mask(config.ids_block_size))\n self.T = config.id_block_size\n\n def generate_square_subsequent_mask(self, sz: int, pad=None):\n r\"\"\"Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n Unmasked positions are filled with float(0.0).\n \"\"\"\n mask = (torch.triu(torch.ones(sz, sz), diagonal=0) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n \n def generate_padding_mask(self, sz: int, pad=None):\n r\"\"\"Build a (B x T) mask that resides on the GPU and can be \n manipulated by build_padding_mask according to padded sequence\n \"\"\"\n mask = torch.zeros(1, sz, dtype=torch.bool)\n return mask\n\n def generate_sparse_mask(self, sz: int, pad=None):\n r\"\"\" Build a square mask that employs \n teacher forcing according to P\n \"\"\"\n rand_mat = torch.rand(1, sz)\n k = round(0.75 * sz)\n k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]\n bool_tensor = rand_mat <= k_th_quant\n mask = torch.where(bool_tensor, torch.tensor(1), torch.tensor(0)).repeat(sz, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask.cuda(self.tgt_mask.get_device()) if self.tgt_mask.is_cuda else mask\n \n def build_padding_mask(self, tgt, pad):\n # mask = self.tgt_pad_mask.repeat(tgt.shape[0], 1)\n mask = torch.zeros(tgt.shape[0], self.T, dtype=torch.bool)\n for B, P in enumerate(pad):\n mask[B, self.T - P:] = True\n return mask # .to(torch.cuda.current_device())\n\n def forward(self, tgt, memory, pad):\n # padding_mask = self.build_padding_mask(tgt, pad)\n # tgt_mask = self.generate_sparse_mask(self.T) if self.training else self.tgt_mask\n return self.decoder(src=memory, tgt=tgt, tgt_mask=self.tgt_mask, \n tgt_key_padding_mask=None)\n\n\nclass ProjectNorm(nn.Module):\n\n def __init__(self, feat_size, target_size):\n super().__init__()\n self.ln = nn.LayerNorm(feat_size)\n self.mlp = nn.Sequential(\n nn.Linear(feat_size, math.floor(2 * feat_size), bias=False),\n nn.GELU(),\n nn.Linear(math.floor(2 * feat_size), target_size, bias=False),\n )\n\n def forward(self, x):\n return self.mlp(self.ln(x))\n\n\nclass TimeProjection(nn.Module):\n \n def __init__(self, seq_size, id_seq_size, feat_size, target_size):\n super().__init__()\n self.mlp_seq = nn.Sequential(\n nn.Linear(seq_size, id_seq_size),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(id_seq_size, id_seq_size)\n )\n self.mlp_t = nn.Sequential(\n nn.Linear(feat_size, feat_size // 2),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(feat_size // 2, target_size)\n )\n \n def forward(self, x):\n x = x.permute(0, 2, 1) # B, T, C -> B, C, T\n x = self.mlp_seq(x) # B, C, T / 2\n x = x.permute(0, 2, 1) # B, T / 2, C\n return self.mlp_t(x) # B, T / 2, 1\n\n\nclass PSTHProjection(nn.Module):\n \"\"\"Takes Last Output of Block -> (B, C) \n Builds PSTH table \n \"\"\"\n def __init__(self, config):\n super().__init__()\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd, bias=False),\n nn.Dropout(p=0.2),\n nn.GELU(),\n nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n )\n \n def forward(self, x):\n return self.mlp(x)\n\n\n# class PSTHProjection(nn.Module):\n \n# def __init__(self, config):\n# super().__init__()\n# self.mlp_seq = nn.Sequential(\n# nn.Linear(config.id_block_size, config.id_block_size // 2, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.id_block_size // 2, 1, bias=False)\n# )\n# self.mlp_t = nn.Sequential(\n# nn.Linear(config.n_embd, config.n_embd * 4, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n# )\n \n# def forward(self, x):\n# x = x.transpose(-1, -2) # B, T, C -> B, C, T\n# x = self.mlp_seq(x) # B, C, 1\n# x = x.transpose(-2, -1) # B, 1, Vocab_id\n# return self.mlp_t(x)\n\n\nclass TimeRNN(nn.Module):\n def __init__(self, feat_size, target_size):\n super().__init__()\n\n\nclass Block(nn.Module):\n \"\"\" an unassuming Transformer block \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.ln1 = nn.LayerNorm(config.n_embd)\n self.ln2 = nn.LayerNorm(config.n_embd)\n self.attn = CausalSelfAttention(config)\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd),\n nn.GELU(),\n nn.Linear(4 * config.n_embd, config.n_embd),\n nn.Dropout(config.resid_pdrop),\n )\n\n def forward(self, x, pad=None, dtx=None):\n x = x + self.attn(self.ln1(x), pad)\n x = x + self.mlp(self.ln2(x))\n return x\n\n\nclass BlockSequential(nn.Sequential):\n def forward(self, x, pad=None, dtx=None):\n for module in self._modules.values():\n x = module(x, pad, dtx)\n return x\n\n\nclass DiceLossPSTH(nn.Module):\n def __init__(self, size_average=True, smooth=1):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets, smooth=1, class_weights=None):\n total_logits = F.layer_norm(torch.sum(logits, dim=-2), [logits.size()[-1]])\n # probs = F.log_softmax(logits, dim=-1)\n probs = F.softmax(total_logits, dim=-1)\n # logits = F.gelu(logits)\n # probs = logits / (logits.max(dim=-1).values.unsqueeze(-1))\n # flatten label and prediction tensors\n outputs = probs.contiguous().view(-1)\n targets = targets.contiguous().view(-1)\n labels = torch.zeros_like(outputs)\n labels[targets] = 1 / len(targets)\n # intersection = (outputs * labels).sum()\n # dice = (2. * intersection + smooth) / (outputs.sum() + labels.sum() + smooth)\n return self.cross_entropy(outputs[None, ...], labels[None, ...])\n\n\nclass SetLoss(nn.Module):\n def __init__(self):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets):\n targets = targets.contiguous().view(-1)\n loss = 0\n for n_step, n_logits in enumerate(logits):\n n_logits = F.softmax(n_logits, dim=-1)\n n_target = targets[n_step:]\n n_target_dist = torch.zeros_like(n_logits)\n if len(n_target) != 0:\n n_target_dist[n_target] = 1 / len(n_target)\n loss += self.cross_entropy(n_logits[None,...], n_target_dist[None, ...])\n return loss / len(logits)\n\n\nclass TruncatedLoss(nn.Module):\n\n def __init__(self, q=0.8, k=0.2, trainset_size=50000):\n super(TruncatedLoss, self).__init__()\n self.q = q\n self.k = k\n self.weight = torch.nn.Parameter(data=torch.ones(trainset_size, 1), requires_grad=False)\n \n def forward(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n\n loss = ((1-(Yg**self.q))/self.q)*self.weight[indexes] - ((1-(self.k**self.q))/self.q)*self.weight[indexes]\n loss = torch.mean(loss)\n\n return loss\n\n def update_weight(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n Lq = ((1-(Yg**self.q))/self.q)\n Lqk = np.repeat(((1-(self.k**self.q))/self.q), targets.size(0))\n Lqk = torch.from_numpy(Lqk).type(torch.cuda.FloatTensor)\n Lqk = torch.unsqueeze(Lqk, 1)\n \n condition = torch.gt(Lqk, Lq)\n self.weight[indexes] = condition.type(torch.cuda.FloatTensor)\n\n\n# class PSTHLOSS(nn.Module):\n# def __init__(self):\n# super().__init__()\n\n# def forward(self, logits, targets):\n# total_logits = torch.sum(logits, dim=-2) # sum over sequence dimension\n# probs = F.softmax(total_logits, dim=-1)\n# outptu\n\n\nclass HungarianMatcher(nn.Module):\n def __init__(self):\n super().__init__()\n \n @torch.no_grad()\n def forward(self, logits, targets):\n T, C = logits.size()\n probs = F.softmax(logits, dim=-1)\n cost_id = (1 - probs[:, targets]).cpu().view(T, -1).unsqueeze(0)\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_id.split(len(targets), -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\nclass KLDivLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n self.KLdiv = nn.KLDivLoss()\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.KLdiv(log_probs.long(), targets)\n\n\nclass PoissonCrossEntropyLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n # self.softmax = nn.Softmax(dim=-1)\n self.nll_poisson = nn.PoissonNLLLoss()\n # self.nll_poisson = nn.NLLLoss()\n\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.nll_poisson(log_probs, targets)\n\n\nclass GPT(nn.Module):\n \"\"\" the full GPT language model, with a context size of block_size \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n self.device = 'cpu'\n if torch.cuda.is_available():\n self.device = torch.cuda.current_device()\n\n self.config = config\n # input embedding stem\n self.n_embd = config.n_embd\n self.tok_emb = nn.Embedding(config.id_vocab_size, config.n_embd)\n self.pos_emb = PositionalEmbedding(config.n_embd, p_drop=0.2)\n # self.pos_emb_id = nn.Parameter(torch.zeros(1, config.id_block_size, config.n_embd))\n self.pos_emb_frames = nn.Parameter(torch.zeros(1, config.frame_block_size, config.n_embd))\n # self.temp_emb = TemporalEmbedding(config.n_embd, p_drop=0.2)\n # self.temp_emb = RotaryTemporalEmbedding(config.id_block_size)\n self.temp_emb = LearntTemporalEmbedding(config.id_block_size, config.n_embd)\n self.frame_temp_emb = LearntTemporalEmbedding(config.frame_block_size, config.n_embd)\n self.id_drop = nn.Dropout(config.id_drop)\n self.im_drop = nn.Dropout(config.im_drop)\n self.drop = nn.Dropout(config.embd_pdrop)\n\n # -- Visual Backbone -- #\n # self.visual_backbone = VideoFeaturesExtractor()\n self.video_encoder = VideoEncoder()\n frame_temp_emb = torch.tensor(list(itertools.chain(*[[n * 0.05] * (config.frame_block_size//20) for n in range(20)]))).unsqueeze(0)\n self.register_buffer(\"frame_temp_emb_seq\", frame_temp_emb)\n\n # -- Contrastive Loss -- ##\n # self.proj_id = ProjectNorm(config.n_embd, config.n_embd)\n # self.proj_vid = VidProjectNorm(config.n_embd, config.n_embd) # im_shape\n \n ## -- IM_Decoder -- ##\n # self.blocks_id = BlockSequential(*[Block(config) for _ in range(2)])\n # self.blocks_im = BlockSequential(*[Block(config) for _ in range(2)])\n # self.ln_f_id = nn.LayerNorm(config.n_embd)\n # self.ln_f_im = nn.LayerNorm(config.n_embd)\n\n ## -- Decoder -- ##\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## GPT\n # self.blocks = BlockSequential(*[Block(config) for _ in range(config.n_layer)])\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## enc_dec\n self.state_decoder = Decoder(config)\n self.ln_f_state_dec = nn.LayerNorm(config.n_embd)\n self.stimulus_decoder = Decoder(config)\n self.ln_f_stimulus_dec = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n \n ## -- Time -- ##\n # self.proj_time = TimeProjection(config.block_size, config.id_block_size, config.n_embd, config.n_dt)\n self.proj_time = ProjectNorm(config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, 1)\n \n ## -- PSTH -- ##\n # self.proj_psth = PSTHProjection(config)\n\n # Loss\n # self.dice_loss = DiceLossPSTH()\n # self.poisson_loss = PoissonCrossEntropyLoss()\n # self.hungarian_matcher = HungarianMatcher()\n # self.kldiv_loss = KLDivLoss()\n # self.truncated_loss = TruncatedLoss(trainset_size=config.data_size)\n # self.set_loss = SetLoss()\n # self.a = torch.tensor(0.5, requires_grad=True)\n\n self.block_size = config.block_size\n self.apply(self._init_weights)\n \n if config.class_weights is not None:\n for key in config.class_weights.keys():\n self.register_buffer(f\"class_weights_{key}\", config.class_weights[key]) \n \n logger.info(\"number of parameters: %e\", sum(p.numel() for p in self.parameters()))\n\n def get_block_size(self):\n return self.block_size\n\n def _init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def configure_optimizers(self, train_config):\n \"\"\"\n Separates parameters into those who will experience weight decay and those that will not\n \"\"\"\n if train_config.decay_weights:\n decay = set()\n no_decay = set()\n whitelist_weight_modules = (torch.nn.Linear, )\n blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)\n for mn, m in self.named_modules():\n for pn, p in m.named_parameters():\n fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n if pn.endswith('bias'):\n # all biases will not be decayed\n no_decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):\n # weights of whitelist modules will be weight decayed\n decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):\n # weights of blacklist modules will NOT be weight decayed\n no_decay.add(fpn)\n else: no_decay.add(fpn)\n\n # special case the position embedding parameter in the root GPT module as not decayed\n black_list_mods = ['pos_emb', 'temp_emb']\n for mods in black_list_mods:\n for name, param in self.named_parameters():\n if mods in name:\n no_decay.add(name) # also pos_emb\n \n # validate that we considered every parameter\n param_dict = {pn: p for pn, p in self.named_parameters()}\n no_decay -= decay & no_decay\n inter_params = decay & no_decay\n union_params = decay | no_decay\n\n assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n % (str(param_dict.keys() - union_params), )\n\n \n # create the pytorch optimizer object\n optim_groups = [\n {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": train_config.weight_decay},\n {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n ]\n optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)\n \n else:\n parameters = self.parameters()\n optimizer = torch.optim.Adam(parameters, lr=train_config.learning_rate)\n \n return optimizer\n \n def process_features(self, x):\n # batch, block_size, feature\n p_idx = x['id_prev']\n idx = x['id']\n dtx = x['dt']\n dtx_prev = x['dt_prev']\n frames = self.video_encoder(x['frames'])\n pad = x['pad']\n\n b, t = idx.size()\n # b_p, t_p = p_idx.size()\n bf, tf = frames.size()[0:2]\n\n # forward the GPT model\n ''' \n positional and temporal embeddings implemented in multiple ways, learnt, \n fourrier decomposition and in the case of time, just passed as is. \n '''\n # # Embeddings\n prev_id_position_embeddings = self.pos_emb(p_idx)\n prev_id_temporal_embeddings = self.temp_emb(dtx_prev.float())\n id_position_embeddings = self.pos_emb(idx) \n im_position_embeddings = self.pos_emb_frames\n temporal_embeddings = self.temp_emb(dtx.float())\n \n # Extract ID features\n prev_token_embeddings = self.id_drop(self.tok_emb(p_idx) + prev_id_temporal_embeddings + prev_id_position_embeddings)\n token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector\n token_embeddings = token_embeddings + temporal_embeddings + id_position_embeddings\n token_embeddings = self.id_drop(token_embeddings)\n\n # Extract image features and add time embeddings\n im_temporal_embeddings = self.frame_temp_emb(self.frame_temp_emb_seq)\n im_embeddings = frames # self.tok_emb(frames)\n im_embeddings = im_embeddings + im_position_embeddings + im_temporal_embeddings\n im_embeddings = self.im_drop(im_embeddings) # separate pos emb?\n \n # Tidy up\n features = dict()\n features['id_prev'] = prev_token_embeddings\n features['id'] = token_embeddings\n features['frames'] = im_embeddings\n \n return features, pad\n\n def perceiver(self, features, pad):\n x = self.state_decoder(tgt=features['id'], memory=features['id_prev'], pad=pad)\n x = self.ln_f_state_dec(x)\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def enc_dec(self, features, pad):\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def GPTdecoder(self, features, pad, dtx=None):\n # image + neural features\n x = torch.cat((features['frames'], features['id']), dim=1)\n\n # Decoder\n x = self.blocks(x, pad, dtx) # (B, T, C)\n x = self.ln_f(x)\n logits = self.head(x)\n\n # print(logits.shape) # (B, T, Vocab)\n # logits_psth = x[:, -1] # (B, C)\n\n return logits, x\n\n def forward(self, x, targets=None):\n idx = x['id']\n dtx = x['dt']\n frames = x['frames']\n pad = x['pad']\n\n b, t = idx.size()\n # b, t = x['id'].shape[0], x['id'].shape[1] + x['id_prev'].shape[1]\n bf, tf = frames.size()[0:2]\n tf = self.config.frame_block_size\n # assert t + tf == self.config.block_size, f\"{tf} {t}\"\n # assert t <= self.block_size, \"Cannot forward, model block size is exhausted\"\n \n features, pad = self.process_features(x)\n logits, x = self.perceiver(features, pad)\n # logits, x = self.enc_dec(features, pad)\n # logits, x = self.GPTdecoder(features, pad)\n time = self.proj_time(x) # (B, T_id, 1)\n\n # print(x[:, 0].shape)\n # psth = self.proj_psth(x) # (B, Vocab_id)\n\n # if targets, calculate loss\n # calculate loss on logits up to padding token for each batch\n loss = None\n loss_frames = 0\n loss_id = []\n loss_time = []\n loss_dice = []\n loss_psth = []\n loss_hungarian = []\n if targets is not None:\n # loss_psth = self.dice_loss(psth, targets['modes'][:, tf:]) \n for B, P in enumerate(pad):\n tf = 0\n # im_logits = logits[B, :tf]\n # im_targets = targets['frames'][B, :tf]\n # loss_frames += F.cross_entropy(im_logits.view(-1, im_logits.size(-1)), im_targets.view(-1))\n id_logits = logits[B, tf:tf + t - P]\n id_targets = targets['id'][B, :t - P]\n\n loss_id_ = F.cross_entropy(id_logits.view(-1, id_logits.size(-1)), id_targets.view(-1), weight=self.class_weights_id)\n # if self.config.epoch >= 15:\n # self.truncated_loss.update_weight(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # loss_id_ = self.truncated_loss(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n time_preds = time[B, :t - P]\n time_targets = targets['dt'][B, :t - P]\n loss_time_ = F.cross_entropy(time_preds.view(-1, time_preds.size(-1)), time_targets.view(-1), weight=self.class_weights_dt)\n # loss_time_ = F.mse_loss(time_preds.squeeze(-1), time_targets)\n # loss_id_ = self.poisson_loss(id_logits.view(-1, id_logits.size(-1)), F.one_hot(id_targets, self.config.vocab_size))\n # if len(id_targets) > 0:\n # indices = self.hungarian_matcher(id_logits, id_targets)\n # probs_matching, targets_matching = id_logits[indices[0][0]], id_targets[indices[0][1]]\n # loss_hungarian_ = F.cross_entropy(probs_matching, targets_matching, weight=self.class_weights).to(self.device)\n # loss_hungarian.append(loss_hungarian_)\n # # psth = self.proj_psth(x[B, -1]) # from the EOS position\n \n # loss_psth.append(torch.nan_to_num(self.set_loss(id_logits, id_targets)))\n # loss_psth_ = self.dice_loss(id_logits, id_targets)\n # loss_psth.append(torch.nan_to_num(loss_psth_))\n \n loss_time.append(torch.nan_to_num(loss_time_))\n loss_id.append(torch.nan_to_num(loss_id_))\n \n loss = dict()\n # loss['frames'] = loss_frames / (b / 3)\n loss['id'] = sum(loss_id) / (b * 2) # sum(loss_id) / (b * 2) # / len(loss_id)\n loss['time'] = sum(loss_time) / (b * 2)\n # loss['dice'] = sum(loss_dice) / len(loss_dice)\n # loss['dt'] = loss_time / (b * 50)\n # loss['hungarian'] = sum(loss_hungarian) / (b * 2)\n # loss['psth'] = sum(loss_psth) / (b * 2)\n\n for key in list(loss):\n if isinstance(loss[key], float):\n del loss[key]\n \n preds = dict()\n preds['id'] = logits # [:, tf:] # only id logits\n preds['dt'] = time\n\n return preds, features, loss", "# from code.transformer_vid.utils import convert_weights\n# import rotary_embedding_torch\nfrom torch.nn.modules.activation import GELU, ReLU\n# from data.OneCombo3.trainer import TrainerConfig\nimport math\nimport numpy as np\nimport itertools\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torchvision.models.video import r3d_18\n# from ResNet3D import r3d_18\n\nfrom scipy.optimize import linear_sum_assignment\n# from rotary_embedding_torch import apply_rotary_emb, RotaryEmbedding\n\nfrom einops.layers.torch import Rearrange\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_weights(model: nn.Module):\n \"\"\"Convert applicable model parameters to fp16\"\"\"\n\n def _convert_weights_to_fp16(l):\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): # nn.Conv3d,\n l.weight.data = l.weight.data.half()\n if l.bias is not None:\n l.bias.data = l.bias.data.half()\n\n if isinstance(l, nn.MultiheadAttention):\n for attr in [*[f\"{s}_proj_weight\" for s in [\"in\", \"q\", \"k\", \"v\"]], \"in_proj_bias\", \"bias_k\", \"bias_v\"]:\n tensor = getattr(l, attr)\n if tensor is not None:\n tensor.data = tensor.data.half()\n\n for name in [\"text_projection\", \"proj\"]:\n if hasattr(l, name):\n attr = getattr(l, name)\n if attr is not None:\n attr.data = attr.data.half()\n\n model.apply(_convert_weights_to_fp16)\n\nclass GPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n embd_pdrop = 0.2\n resid_pdrop = 0.2\n attn_pdrop = 0.2\n pos_pdrop = 0.2\n temp_pdrop = 0.2\n pos_emb = True\n temp_emb = True\n start_prune = 30\n epoch = 0\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\nclass neuralGPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n n = 0.4\n im_drop = 0.2\n id_drop = n\n embd_pdrop = n\n resid_pdrop = n\n attn_pdrop = n\n pos_pdrop = n\n temp_pdrop = n\n pos_emb = True\n temp_emb = True\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass GPT1Config(GPTConfig):\n \"\"\" GPT-1 like network roughly 125M params \"\"\"\n n_layer = 12\n n_head = 12\n n_embd = 768\n\n\nclass VideoFeaturesExtractor(nn.Module):\n \"\"\" \n R3D: (3 x T x H x W)\n H, W = 112\n \"\"\"\n \n def __init__(self):\n super().__init__()\n self.backbone = torch.nn.Sequential(*(list(r3d_18(pretrained=True).children())[:-2]))\n convert_weights(self.backbone)\n # # freeze backbone\n # for k, v in self.backbone.named_parameters():\n # v.requires_grad = False\n\n def forward(self, x):\n # B = Batch, T, C, Fm, H, W\n features = self.backbone(x) # (B, C, T, H, W)\n B, C, T, H, W = features.shape\n features = features.permute(0, 2, 3, 4, 1)\n features = features.view(B, -1, C)\n return features\n\nclass VideoEncoder(nn.Module):\n def __init__(self, n_embd):\n super().__init__()\n # p1, p2 = 16, 16\n \n # assert n_embd % (p1 * p2) == 0, \"n_embd must be divisible by p1 * p2\"\n \n # c = n_embd // (p1 * p2) \n # self.to_patch_embedding = nn.Sequential(\n # Rearrange(f'b {c} t (h {p1}) (w {p2}) -> b (t h w) ({p1} {p2} {c})', p1=p1, p2=p2)\n # )\n self.to_patch_embedding = nn.Sequential(\n Rearrange(f'b c t (h {p1}) (w {p2}) -> b (t h w) ({p1} {p2} {c})', p1=p1, p2=p2)\n )\n\n def forward(self, x):\n return self.to_patch_embedding(x)\n\n\nclass CausalSelfAttention(nn.Module):\n \"\"\"\n A vanilla multi-head masked self-attention layer with a projection at the end.\n \n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n assert config.n_embd % config.n_head == 0\n self.config = config\n # key, query, value projections for all heads\n self.key = nn.Linear(config.n_embd, config.n_embd)\n self.query = nn.Linear(config.n_embd, config.n_embd)\n self.value = nn.Linear(config.n_embd, config.n_embd)\n # regularization\n self.attn_drop = nn.Dropout(config.attn_pdrop)\n self.resid_drop = nn.Dropout(config.resid_pdrop)\n # output projection\n self.proj = nn.Linear(config.n_embd, config.n_embd)\n\n self.register_buffer(\"mask\", self.build_mask(config.block_size)) \n self.n_head = config.n_head\n\n self.att = None\n self.T = config.block_size\n\n # self.rotary_embedding = RotarySpatioTemporalEmbedding(config)\n \n def build_mask(self, block_size):\n mask = torch.tril(torch.ones((block_size, block_size)),\n ).view(1, 1, block_size, block_size)\n return mask\n \n def generate_sparse_mask(self, att, p, config):\n \"\"\"\n Generate a sparse mask according to p.\n \"\"\"\n assert p >= 0 and p <= 1, \"p should be in [0, 1]\"\n T = config.block_size\n mask = torch.rand((1, T)) < p\n mask = mask.repeat(T, 1)\n \n mask[0, 0] = False # don't mask 1st step\n # check if any step is fully masked and umask it\n idx_all_true = (True == torch.all(mask, dim=0)).nonzero()\n for step in idx_all_true:\n sampler = torch.distributions.Uniform(low=0, high=step.item()+1)\n idx_false = sampler.sample((1,1)).long()\n mask[step, idx_false] = False\n\n # mask = mask.repeat(T, 1)\n mask = mask.view(1, 1, T, T).cuda() if att.is_cuda else mask.view(1, 1, T, T)\n att = att.masked_fill(mask, float('-inf'))\n return att\n\n def forward(self, x, pad=None, dtx=None):\n # B = Batch, T = Sequence, C = n_embed\n B, T, C = x.size()\n\n # calculate query, key, values for all head in batch and move head forward to the batch dim\n k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n\n # # apply rotary embeddings\n # if dtx is not None:\n # q, k = self.rotary_embedding(q, k, dtx)\n\n # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)\n att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))\n if self.training:\n att = self.generate_sparse_mask(att, 0.25, self.config)\n if pad is not None:\n for idx, i in enumerate(pad):\n att[idx, :, :, self.T - i:] = float('-inf') # only able to see first padding token\n \n att = F.softmax(att, dim=-1)\n att = self.attn_drop(att)\n self.att = att\n y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side\n\n # output projection\n y = self.resid_drop(self.proj(y))\n return y\n\n\nclass PositionalEmbedding(nn.Module):\n \"\"\" Implement the PE function. \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\n# class RotarySpatioTemporalEmbedding(nn.Module):\n# \"\"\" Rotary temporal embeddings - block_size = id_blk_sz \"\"\"\n# def __init__(self, config):\n# super().__init__()\n# self.frame_block_size = config.frame_block_size\n# self.id_block_size = config.id_block_size\n# self.emb = RotaryEmbedding(dim=32)\n\n# def forward(self, q, k, t):\n# b = t.shape[0]\n# tf = self.frame_block_size\n# queries = []\n# keys = []\n# for B in range(b):\n# im_temp_emb = torch.tensor([-0.5] * (tf//2) + [0.5] * (tf//2))\n# im_pos_emb = torch.arange(self.frame_block_size)\n# im_emb = torch.stack([im_temp_emb, im_pos_emb], dim=0)\n# id_temp_emb = self.temp_emb(t[B], cache_key=self.block_size)\n# freqs = self.emb(torch.cat(im_emb, id_temp_emb))\n# queries.append(apply_rotary_emb(freqs, q[B][None, ...]))\n# keys.append(apply_rotary_emb(freqs, k[B][None, ...]))\n# q, k = torch.cat(queries), torch.cat(keys)\n# return q, k\n\n\nclass TemporalEmbedding(nn.Module):\n \"\"\" encoding temporal information using fourrier signals \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\nclass LearntTemporalEmbedding(nn.Module):\n \"\"\"\n Project B x T x 1 time sequence to\n B x T x C\n \"\"\"\n def __init__(self, block_sz, n_embd, p_drop=0.2):\n super().__init__()\n self.temp_emb = nn.Sequential(\n nn.Linear(1, n_embd // 2),\n nn.GELU(),\n nn.Linear(n_embd // 2, n_embd),\n nn.Dropout(p_drop)\n )\n \n def forward(self, x):\n return self.temp_emb(x.unsqueeze(-1))\n\n\nclass Decoder(nn.Module):\n\n def __init__(self, config):\n super().__init__()\n # decoder_layer = nn.TransformerDecoderLayer(config.n_embd, config.n_head, \n # activation='gelu', dropout=0.2, batch_first=True)\n # self.decoder = nn.TransformerDecoder(decoder_layer, config.n_layer)\n self.decoder = nn.Transformer(d_model=config.n_embd, nhead=config.n_head, \n num_encoder_layers=3, num_decoder_layers=config.n_layer,\n activation=\"gelu\", dropout=0.4, batch_first=True)\n self.register_buffer(\"tgt_mask\", self.generate_square_subsequent_mask(config.id_block_size))\n # self.register_buffer(\"tgt_pad_mask\", self.generate_padding_mask(config.ids_block_size))\n self.T = config.id_block_size\n\n def generate_square_subsequent_mask(self, sz: int, pad=None):\n r\"\"\"Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n Unmasked positions are filled with float(0.0).\n \"\"\"\n mask = (torch.triu(torch.ones(sz, sz), diagonal=0) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n \n def generate_padding_mask(self, sz: int, pad=None):\n r\"\"\"Build a (B x T) mask that resides on the GPU and can be \n manipulated by build_padding_mask according to padded sequence\n \"\"\"\n mask = torch.zeros(1, sz, dtype=torch.bool)\n return mask\n\n def generate_sparse_mask(self, sz: int, pad=None):\n r\"\"\" Build a square mask that employs \n teacher forcing according to P\n \"\"\"\n rand_mat = torch.rand(1, sz)\n k = round(0.75 * sz)\n k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]\n bool_tensor = rand_mat <= k_th_quant\n mask = torch.where(bool_tensor, torch.tensor(1), torch.tensor(0)).repeat(sz, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask.cuda(self.tgt_mask.get_device()) if self.tgt_mask.is_cuda else mask\n \n def build_padding_mask(self, tgt, pad):\n # mask = self.tgt_pad_mask.repeat(tgt.shape[0], 1)\n mask = torch.zeros(tgt.shape[0], self.T, dtype=torch.bool)\n for B, P in enumerate(pad):\n mask[B, self.T - P:] = True\n return mask # .to(torch.cuda.current_device())\n\n def forward(self, tgt, memory, pad):\n # padding_mask = self.build_padding_mask(tgt, pad)\n # tgt_mask = self.generate_sparse_mask(self.T) if self.training else self.tgt_mask\n return self.decoder(src=memory, tgt=tgt, tgt_mask=self.tgt_mask, \n tgt_key_padding_mask=None)\n\n\nclass ProjectNorm(nn.Module):\n\n def __init__(self, feat_size, target_size):\n super().__init__()\n self.ln = nn.LayerNorm(feat_size)\n self.mlp = nn.Sequential(\n nn.Linear(feat_size, math.floor(2 * feat_size), bias=False),\n nn.GELU(),\n nn.Linear(math.floor(2 * feat_size), target_size, bias=False),\n )\n\n def forward(self, x):\n return self.mlp(self.ln(x))\n\n\nclass TimeProjection(nn.Module):\n \n def __init__(self, seq_size, id_seq_size, feat_size, target_size):\n super().__init__()\n self.mlp_seq = nn.Sequential(\n nn.Linear(seq_size, id_seq_size),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(id_seq_size, id_seq_size)\n )\n self.mlp_t = nn.Sequential(\n nn.Linear(feat_size, feat_size // 2),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(feat_size // 2, target_size)\n )\n \n def forward(self, x):\n x = x.permute(0, 2, 1) # B, T, C -> B, C, T\n x = self.mlp_seq(x) # B, C, T / 2\n x = x.permute(0, 2, 1) # B, T / 2, C\n return self.mlp_t(x) # B, T / 2, 1\n\n\nclass PSTHProjection(nn.Module):\n \"\"\"Takes Last Output of Block -> (B, C) \n Builds PSTH table \n \"\"\"\n def __init__(self, config):\n super().__init__()\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd, bias=False),\n nn.Dropout(p=0.2),\n nn.GELU(),\n nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n )\n \n def forward(self, x):\n return self.mlp(x)\n\n\n# class PSTHProjection(nn.Module):\n \n# def __init__(self, config):\n# super().__init__()\n# self.mlp_seq = nn.Sequential(\n# nn.Linear(config.id_block_size, config.id_block_size // 2, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.id_block_size // 2, 1, bias=False)\n# )\n# self.mlp_t = nn.Sequential(\n# nn.Linear(config.n_embd, config.n_embd * 4, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n# )\n \n# def forward(self, x):\n# x = x.transpose(-1, -2) # B, T, C -> B, C, T\n# x = self.mlp_seq(x) # B, C, 1\n# x = x.transpose(-2, -1) # B, 1, Vocab_id\n# return self.mlp_t(x)\n\n\nclass TimeRNN(nn.Module):\n def __init__(self, feat_size, target_size):\n super().__init__()\n\n\nclass Block(nn.Module):\n \"\"\" an unassuming Transformer block \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.ln1 = nn.LayerNorm(config.n_embd)\n self.ln2 = nn.LayerNorm(config.n_embd)\n self.attn = CausalSelfAttention(config)\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd),\n nn.GELU(),\n nn.Linear(4 * config.n_embd, config.n_embd),\n nn.Dropout(config.resid_pdrop),\n )\n\n def forward(self, x, pad=None, dtx=None):\n x = x + self.attn(self.ln1(x), pad)\n x = x + self.mlp(self.ln2(x))\n return x\n\n\nclass BlockSequential(nn.Sequential):\n def forward(self, x, pad=None, dtx=None):\n for module in self._modules.values():\n x = module(x, pad, dtx)\n return x\n\n\nclass DiceLossPSTH(nn.Module):\n def __init__(self, size_average=True, smooth=1):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets, smooth=1, class_weights=None):\n total_logits = F.layer_norm(torch.sum(logits, dim=-2), [logits.size()[-1]])\n # probs = F.log_softmax(logits, dim=-1)\n probs = F.softmax(total_logits, dim=-1)\n # logits = F.gelu(logits)\n # probs = logits / (logits.max(dim=-1).values.unsqueeze(-1))\n # flatten label and prediction tensors\n outputs = probs.contiguous().view(-1)\n targets = targets.contiguous().view(-1)\n labels = torch.zeros_like(outputs)\n labels[targets] = 1 / len(targets)\n # intersection = (outputs * labels).sum()\n # dice = (2. * intersection + smooth) / (outputs.sum() + labels.sum() + smooth)\n return self.cross_entropy(outputs[None, ...], labels[None, ...])\n\n\nclass SetLoss(nn.Module):\n def __init__(self):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets):\n targets = targets.contiguous().view(-1)\n loss = 0\n for n_step, n_logits in enumerate(logits):\n n_logits = F.softmax(n_logits, dim=-1)\n n_target = targets[n_step:]\n n_target_dist = torch.zeros_like(n_logits)\n if len(n_target) != 0:\n n_target_dist[n_target] = 1 / len(n_target)\n loss += self.cross_entropy(n_logits[None,...], n_target_dist[None, ...])\n return loss / len(logits)\n\n\nclass TruncatedLoss(nn.Module):\n\n def __init__(self, q=0.8, k=0.2, trainset_size=50000):\n super(TruncatedLoss, self).__init__()\n self.q = q\n self.k = k\n self.weight = torch.nn.Parameter(data=torch.ones(trainset_size, 1), requires_grad=False)\n \n def forward(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n\n loss = ((1-(Yg**self.q))/self.q)*self.weight[indexes] - ((1-(self.k**self.q))/self.q)*self.weight[indexes]\n loss = torch.mean(loss)\n\n return loss\n\n def update_weight(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n Lq = ((1-(Yg**self.q))/self.q)\n Lqk = np.repeat(((1-(self.k**self.q))/self.q), targets.size(0))\n Lqk = torch.from_numpy(Lqk).type(torch.cuda.FloatTensor)\n Lqk = torch.unsqueeze(Lqk, 1)\n \n condition = torch.gt(Lqk, Lq)\n self.weight[indexes] = condition.type(torch.cuda.FloatTensor)\n\n\n# class PSTHLOSS(nn.Module):\n# def __init__(self):\n# super().__init__()\n\n# def forward(self, logits, targets):\n# total_logits = torch.sum(logits, dim=-2) # sum over sequence dimension\n# probs = F.softmax(total_logits, dim=-1)\n# outptu\n\n\nclass HungarianMatcher(nn.Module):\n def __init__(self):\n super().__init__()\n \n @torch.no_grad()\n def forward(self, logits, targets):\n T, C = logits.size()\n probs = F.softmax(logits, dim=-1)\n cost_id = (1 - probs[:, targets]).cpu().view(T, -1).unsqueeze(0)\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_id.split(len(targets), -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\nclass KLDivLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n self.KLdiv = nn.KLDivLoss()\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.KLdiv(log_probs.long(), targets)\n\n\nclass PoissonCrossEntropyLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n # self.softmax = nn.Softmax(dim=-1)\n self.nll_poisson = nn.PoissonNLLLoss()\n # self.nll_poisson = nn.NLLLoss()\n\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.nll_poisson(log_probs, targets)\n\n\nclass GPT(nn.Module):\n \"\"\" the full GPT language model, with a context size of block_size \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n self.device = 'cpu'\n if torch.cuda.is_available():\n self.device = torch.cuda.current_device()\n\n self.config = config\n # input embedding stem\n self.n_embd = config.n_embd\n self.tok_emb = nn.Embedding(config.id_vocab_size, config.n_embd)\n self.pos_emb = PositionalEmbedding(config.n_embd, p_drop=0.2)\n # self.pos_emb_id = nn.Parameter(torch.zeros(1, config.id_block_size, config.n_embd))\n self.pos_emb_frames = nn.Parameter(torch.zeros(1, config.frame_block_size, config.n_embd))\n # self.temp_emb = TemporalEmbedding(config.n_embd, p_drop=0.2)\n # self.temp_emb = RotaryTemporalEmbedding(config.id_block_size)\n self.temp_emb = LearntTemporalEmbedding(config.id_block_size, config.n_embd)\n self.frame_temp_emb = LearntTemporalEmbedding(config.frame_block_size, config.n_embd)\n self.id_drop = nn.Dropout(config.id_drop)\n self.im_drop = nn.Dropout(config.im_drop)\n self.drop = nn.Dropout(config.embd_pdrop)\n\n # -- Visual Backbone -- #\n # self.visual_backbone = VideoFeaturesExtractor()\n self.video_encoder = VideoEncoder(config.n_embd)\n frame_temp_emb = torch.tensor(list(itertools.chain(*[[n * 0.05] * (config.frame_block_size//20) for n in range(20)]))).unsqueeze(0)\n self.register_buffer(\"frame_temp_emb_seq\", frame_temp_emb)\n\n # -- Contrastive Loss -- ##\n # self.proj_id = ProjectNorm(config.n_embd, config.n_embd)\n # self.proj_vid = VidProjectNorm(config.n_embd, config.n_embd) # im_shape\n \n ## -- IM_Decoder -- ##\n # self.blocks_id = BlockSequential(*[Block(config) for _ in range(2)])\n # self.blocks_im = BlockSequential(*[Block(config) for _ in range(2)])\n # self.ln_f_id = nn.LayerNorm(config.n_embd)\n # self.ln_f_im = nn.LayerNorm(config.n_embd)\n\n ## -- Decoder -- ##\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## GPT\n # self.blocks = BlockSequential(*[Block(config) for _ in range(config.n_layer)])\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## enc_dec\n self.state_decoder = Decoder(config)\n self.ln_f_state_dec = nn.LayerNorm(config.n_embd)\n self.stimulus_decoder = Decoder(config)\n self.ln_f_stimulus_dec = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n \n ## -- Time -- ##\n # self.proj_time = TimeProjection(config.block_size, config.id_block_size, config.n_embd, config.n_dt)\n self.proj_time = ProjectNorm(config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, 1)\n \n ## -- PSTH -- ##\n # self.proj_psth = PSTHProjection(config)\n\n # Loss\n # self.dice_loss = DiceLossPSTH()\n # self.poisson_loss = PoissonCrossEntropyLoss()\n # self.hungarian_matcher = HungarianMatcher()\n # self.kldiv_loss = KLDivLoss()\n # self.truncated_loss = TruncatedLoss(trainset_size=config.data_size)\n # self.set_loss = SetLoss()\n # self.a = torch.tensor(0.5, requires_grad=True)\n\n self.block_size = config.block_size\n self.apply(self._init_weights)\n \n if config.class_weights is not None:\n for key in config.class_weights.keys():\n self.register_buffer(f\"class_weights_{key}\", config.class_weights[key]) \n \n logger.info(\"number of parameters: %e\", sum(p.numel() for p in self.parameters()))\n\n def get_block_size(self):\n return self.block_size\n\n def _init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def configure_optimizers(self, train_config):\n \"\"\"\n Separates parameters into those who will experience weight decay and those that will not\n \"\"\"\n if train_config.decay_weights:\n decay = set()\n no_decay = set()\n whitelist_weight_modules = (torch.nn.Linear, )\n blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)\n for mn, m in self.named_modules():\n for pn, p in m.named_parameters():\n fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n if pn.endswith('bias'):\n # all biases will not be decayed\n no_decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):\n # weights of whitelist modules will be weight decayed\n decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):\n # weights of blacklist modules will NOT be weight decayed\n no_decay.add(fpn)\n else: no_decay.add(fpn)\n\n # special case the position embedding parameter in the root GPT module as not decayed\n black_list_mods = ['pos_emb', 'temp_emb']\n for mods in black_list_mods:\n for name, param in self.named_parameters():\n if mods in name:\n no_decay.add(name) # also pos_emb\n \n # validate that we considered every parameter\n param_dict = {pn: p for pn, p in self.named_parameters()}\n no_decay -= decay & no_decay\n inter_params = decay & no_decay\n union_params = decay | no_decay\n\n assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n % (str(param_dict.keys() - union_params), )\n\n \n # create the pytorch optimizer object\n optim_groups = [\n {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": train_config.weight_decay},\n {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n ]\n optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)\n \n else:\n parameters = self.parameters()\n optimizer = torch.optim.Adam(parameters, lr=train_config.learning_rate)\n \n return optimizer\n \n def process_features(self, x):\n # batch, block_size, feature\n p_idx = x['id_prev']\n idx = x['id']\n dtx = x['dt']\n dtx_prev = x['dt_prev']\n frames = self.video_encoder(x['frames'])\n pad = x['pad']\n\n b, t = idx.size()\n # b_p, t_p = p_idx.size()\n bf, tf = frames.size()[0:2]\n\n # forward the GPT model\n ''' \n positional and temporal embeddings implemented in multiple ways, learnt, \n fourrier decomposition and in the case of time, just passed as is. \n '''\n # # Embeddings\n prev_id_position_embeddings = self.pos_emb(p_idx)\n prev_id_temporal_embeddings = self.temp_emb(dtx_prev.float())\n id_position_embeddings = self.pos_emb(idx) \n im_position_embeddings = self.pos_emb_frames\n temporal_embeddings = self.temp_emb(dtx.float())\n \n # Extract ID features\n prev_token_embeddings = self.id_drop(self.tok_emb(p_idx) + prev_id_temporal_embeddings + prev_id_position_embeddings)\n token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector\n token_embeddings = token_embeddings + temporal_embeddings + id_position_embeddings\n token_embeddings = self.id_drop(token_embeddings)\n\n # Extract image features and add time embeddings\n im_temporal_embeddings = self.frame_temp_emb(self.frame_temp_emb_seq)\n im_embeddings = frames # self.tok_emb(frames)\n im_embeddings = im_embeddings + im_position_embeddings + im_temporal_embeddings\n im_embeddings = self.im_drop(im_embeddings) # separate pos emb?\n \n # Tidy up\n features = dict()\n features['id_prev'] = prev_token_embeddings\n features['id'] = token_embeddings\n features['frames'] = im_embeddings\n \n return features, pad\n\n def perceiver(self, features, pad):\n x = self.state_decoder(tgt=features['id'], memory=features['id_prev'], pad=pad)\n x = self.ln_f_state_dec(x)\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def enc_dec(self, features, pad):\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def GPTdecoder(self, features, pad, dtx=None):\n # image + neural features\n x = torch.cat((features['frames'], features['id']), dim=1)\n\n # Decoder\n x = self.blocks(x, pad, dtx) # (B, T, C)\n x = self.ln_f(x)\n logits = self.head(x)\n\n # print(logits.shape) # (B, T, Vocab)\n # logits_psth = x[:, -1] # (B, C)\n\n return logits, x\n\n def forward(self, x, targets=None):\n idx = x['id']\n dtx = x['dt']\n frames = x['frames']\n pad = x['pad']\n\n b, t = idx.size()\n # b, t = x['id'].shape[0], x['id'].shape[1] + x['id_prev'].shape[1]\n bf, tf = frames.size()[0:2]\n tf = self.config.frame_block_size\n # assert t + tf == self.config.block_size, f\"{tf} {t}\"\n # assert t <= self.block_size, \"Cannot forward, model block size is exhausted\"\n \n features, pad = self.process_features(x)\n logits, x = self.perceiver(features, pad)\n # logits, x = self.enc_dec(features, pad)\n # logits, x = self.GPTdecoder(features, pad)\n time = self.proj_time(x) # (B, T_id, 1)\n\n # print(x[:, 0].shape)\n # psth = self.proj_psth(x) # (B, Vocab_id)\n\n # if targets, calculate loss\n # calculate loss on logits up to padding token for each batch\n loss = None\n loss_frames = 0\n loss_id = []\n loss_time = []\n loss_dice = []\n loss_psth = []\n loss_hungarian = []\n if targets is not None:\n # loss_psth = self.dice_loss(psth, targets['modes'][:, tf:]) \n for B, P in enumerate(pad):\n tf = 0\n # im_logits = logits[B, :tf]\n # im_targets = targets['frames'][B, :tf]\n # loss_frames += F.cross_entropy(im_logits.view(-1, im_logits.size(-1)), im_targets.view(-1))\n id_logits = logits[B, tf:tf + t - P]\n id_targets = targets['id'][B, :t - P]\n\n loss_id_ = F.cross_entropy(id_logits.view(-1, id_logits.size(-1)), id_targets.view(-1)) # weight=self.class_weights_id)\n # if self.config.epoch >= 15:\n # self.truncated_loss.update_weight(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # loss_id_ = self.truncated_loss(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n time_preds = time[B, :t - P]\n time_targets = targets['dt'][B, :t - P]\n loss_time_ = F.cross_entropy(time_preds.view(-1, time_preds.size(-1)), time_targets.view(-1)) # weight=self.class_weights_dt)\n # loss_time_ = F.mse_loss(time_preds.squeeze(-1), time_targets)\n # loss_id_ = self.poisson_loss(id_logits.view(-1, id_logits.size(-1)), F.one_hot(id_targets, self.config.vocab_size))\n # if len(id_targets) > 0:\n # indices = self.hungarian_matcher(id_logits, id_targets)\n # probs_matching, targets_matching = id_logits[indices[0][0]], id_targets[indices[0][1]]\n # loss_hungarian_ = F.cross_entropy(probs_matching, targets_matching, weight=self.class_weights).to(self.device)\n # loss_hungarian.append(loss_hungarian_)\n # # psth = self.proj_psth(x[B, -1]) # from the EOS position\n \n # loss_psth.append(torch.nan_to_num(self.set_loss(id_logits, id_targets)))\n # loss_psth_ = self.dice_loss(id_logits, id_targets)\n # loss_psth.append(torch.nan_to_num(loss_psth_))\n \n loss_time.append(torch.nan_to_num(loss_time_))\n loss_id.append(torch.nan_to_num(loss_id_))\n \n loss = dict()\n # loss['frames'] = loss_frames / (b / 3)\n loss['id'] = sum(loss_id) / (b * 2) # sum(loss_id) / (b * 2) # / len(loss_id)\n loss['time'] = sum(loss_time) / (b * 2)\n # loss['dice'] = sum(loss_dice) / len(loss_dice)\n # loss['dt'] = loss_time / (b * 50)\n # loss['hungarian'] = sum(loss_hungarian) / (b * 2)\n # loss['psth'] = sum(loss_psth) / (b * 2)\n\n for key in list(loss):\n if isinstance(loss[key], float):\n del loss[key]\n \n preds = dict()\n preds['id'] = logits # [:, tf:] # only id logits\n preds['dt'] = time\n\n return preds, features, loss", "# from code.transformer_vid.utils import convert_weights\nimport rotary_embedding_torch\nfrom torch.nn.modules.activation import GELU, ReLU\n# from data.OneCombo3.trainer import TrainerConfig\nimport math\nimport numpy as np\nimport itertools\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torchvision.models.video import r3d_18\n# from ResNet3D import r3d_18\n\nfrom scipy.optimize import linear_sum_assignment\nfrom rotary_embedding_torch import apply_rotary_emb, RotaryEmbedding\n\nfrom einops.layers.torch import Rearrange\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_weights(model: nn.Module):\n \"\"\"Convert applicable model parameters to fp16\"\"\"\n\n def _convert_weights_to_fp16(l):\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): # nn.Conv3d,\n l.weight.data = l.weight.data.half()\n if l.bias is not None:\n l.bias.data = l.bias.data.half()\n\n if isinstance(l, nn.MultiheadAttention):\n for attr in [*[f\"{s}_proj_weight\" for s in [\"in\", \"q\", \"k\", \"v\"]], \"in_proj_bias\", \"bias_k\", \"bias_v\"]:\n tensor = getattr(l, attr)\n if tensor is not None:\n tensor.data = tensor.data.half()\n\n for name in [\"text_projection\", \"proj\"]:\n if hasattr(l, name):\n attr = getattr(l, name)\n if attr is not None:\n attr.data = attr.data.half()\n\n model.apply(_convert_weights_to_fp16)\n\nclass GPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n embd_pdrop = 0.2\n resid_pdrop = 0.2\n attn_pdrop = 0.2\n pos_pdrop = 0.2\n temp_pdrop = 0.2\n pos_emb = True\n temp_emb = True\n start_prune = 30\n epoch = 0\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\nclass neuralGPTConfig:\n \"\"\" base GPT config, params common to all GPT versions \"\"\"\n n = 0.4\n im_drop = 0.2\n id_drop = n\n embd_pdrop = n\n resid_pdrop = n\n attn_pdrop = n\n pos_pdrop = n\n temp_pdrop = n\n pos_emb = True\n temp_emb = True\n\n def __init__(self, vocab_size, block_size, **kwargs):\n self.vocab_size = vocab_size\n self.block_size = block_size\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass GPT1Config(GPTConfig):\n \"\"\" GPT-1 like network roughly 125M params \"\"\"\n n_layer = 12\n n_head = 12\n n_embd = 768\n\n\nclass VideoFeaturesExtractor(nn.Module):\n \"\"\" \n R3D: (3 x T x H x W)\n H, W = 112\n \"\"\"\n \n def __init__(self):\n super().__init__()\n self.backbone = torch.nn.Sequential(*(list(r3d_18(pretrained=True).children())[:-2]))\n convert_weights(self.backbone)\n # # freeze backbone\n # for k, v in self.backbone.named_parameters():\n # v.requires_grad = False\n\n def forward(self, x):\n # B = Batch, T, C, Fm, H, W\n features = self.backbone(x) # (B, C, T, H, W)\n B, C, T, H, W = features.shape\n features = features.permute(0, 2, 3, 4, 1)\n features = features.view(B, -1, C)\n return features\n\nclass VideoEncoder(nn.Module):\n def __init__(self):\n super().__init__()\n self.to_patch_embedding = nn.Sequential(\n Rearrange('b c t (h p1) (w p2) -> b (t h w) (p1 p2 c)', p1=16, p2=16)\n )\n \n def forward(self, x):\n return self.to_patch_embedding(x)\n\n\nclass CausalSelfAttention(nn.Module):\n \"\"\"\n A vanilla multi-head masked self-attention layer with a projection at the end.\n \n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n assert config.n_embd % config.n_head == 0\n # key, query, value projections for all heads\n self.key = nn.Linear(config.n_embd, config.n_embd)\n self.query = nn.Linear(config.n_embd, config.n_embd)\n self.value = nn.Linear(config.n_embd, config.n_embd)\n # regularization\n self.attn_drop = nn.Dropout(config.attn_pdrop)\n self.resid_drop = nn.Dropout(config.resid_pdrop)\n # output projection\n self.proj = nn.Linear(config.n_embd, config.n_embd)\n\n self.register_buffer(\"mask\", self.build_mask(config.block_size)) \n self.n_head = config.n_head\n\n self.att = None\n self.T = config.block_size\n\n # self.rotary_embedding = RotarySpatioTemporalEmbedding(config)\n \n def build_mask(self, block_size):\n mask = torch.tril(torch.ones((block_size, block_size)),\n ).view(1, 1, block_size, block_size)\n return mask\n\n def forward(self, x, pad=None, dtx=None):\n # B = Batch, T = Sequence, C = n_embed\n B, T, C = x.size()\n\n # calculate query, key, values for all head in batch and move head forward to the batch dim\n k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)\n\n # # apply rotary embeddings\n # if dtx is not None:\n # q, k = self.rotary_embedding(q, k, dtx)\n\n # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)\n att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))\n # if pad is not None:\n # for idx, i in enumerate(pad):\n # att[idx, :, :, self.T - i:] = float('-inf') # only able to see first padding token\n \n att = F.softmax(att, dim=-1)\n att = self.attn_drop(att)\n self.att = att\n y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side\n\n # output projection\n y = self.resid_drop(self.proj(y))\n return y\n\n\nclass PositionalEmbedding(nn.Module):\n \"\"\" Implement the PE function. \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\nclass RotarySpatioTemporalEmbedding(nn.Module):\n \"\"\" Rotary temporal embeddings - block_size = id_blk_sz \"\"\"\n def __init__(self, config):\n super().__init__()\n self.frame_block_size = config.frame_block_size\n self.id_block_size = config.id_block_size\n self.emb = RotaryEmbedding(dim=32)\n\n def forward(self, q, k, t):\n b = t.shape[0]\n tf = self.frame_block_size\n queries = []\n keys = []\n for B in range(b):\n im_temp_emb = torch.tensor([-0.5] * (tf//2) + [0.5] * (tf//2))\n im_pos_emb = torch.arange(self.frame_block_size)\n im_emb = torch.stack([im_temp_emb, im_pos_emb], dim=0)\n id_temp_emb = self.temp_emb(t[B], cache_key=self.block_size)\n freqs = self.emb(torch.cat(im_emb, id_temp_emb))\n queries.append(apply_rotary_emb(freqs, q[B][None, ...]))\n keys.append(apply_rotary_emb(freqs, k[B][None, ...]))\n q, k = torch.cat(queries), torch.cat(keys)\n return q, k\n\n\nclass TemporalEmbedding(nn.Module):\n \"\"\" encoding temporal information using fourrier signals \"\"\"\n def __init__(self, n_embd, p_drop, max_len=1500):\n super().__init__()\n self.dropout = nn.Dropout(p=p_drop)\n \n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, n_embd)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, n_embd, 2) *\n -(math.log(10000.0) / n_embd))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n \n def forward(self, x):\n x = Variable(self.pe[:, :x.size(1)], \n requires_grad=False)\n return self.dropout(x)\n\n\nclass LearntTemporalEmbedding(nn.Module):\n \"\"\"\n Project B x T x 1 time sequence to\n B x T x C\n \"\"\"\n def __init__(self, block_sz, n_embd, p_drop=0.2):\n super().__init__()\n self.temp_emb = nn.Sequential(\n nn.Linear(1, n_embd // 2),\n nn.GELU(),\n nn.Linear(n_embd // 2, n_embd),\n nn.Dropout(p_drop)\n )\n \n def forward(self, x):\n return self.temp_emb(x.unsqueeze(-1))\n\n\nclass Decoder(nn.Module):\n\n def __init__(self, config):\n super().__init__()\n # decoder_layer = nn.TransformerDecoderLayer(config.n_embd, config.n_head, \n # activation='gelu', dropout=0.2, batch_first=True)\n # self.decoder = nn.TransformerDecoder(decoder_layer, config.n_layer)\n self.decoder = nn.Transformer(d_model=config.n_embd, nhead=config.n_head, \n num_encoder_layers=3, num_decoder_layers=config.n_layer,\n activation=\"gelu\", dropout=0.4, batch_first=True)\n self.register_buffer(\"tgt_mask\", self.generate_square_subsequent_mask(config.id_block_size))\n # self.register_buffer(\"tgt_pad_mask\", self.generate_padding_mask(config.ids_block_size))\n self.T = config.id_block_size\n\n def generate_square_subsequent_mask(self, sz: int, pad=None):\n r\"\"\"Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n Unmasked positions are filled with float(0.0).\n \"\"\"\n mask = (torch.triu(torch.ones(sz, sz), diagonal=0) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n \n def generate_padding_mask(self, sz: int, pad=None):\n r\"\"\"Build a (B x T) mask that resides on the GPU and can be \n manipulated by build_padding_mask according to padded sequence\n \"\"\"\n mask = torch.zeros(1, sz, dtype=torch.bool)\n return mask\n\n def generate_sparse_mask(self, sz: int, pad=None):\n r\"\"\" Build a square mask that employs \n teacher forcing according to P\n \"\"\"\n rand_mat = torch.rand(1, sz)\n k = round(0.75 * sz)\n k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]\n bool_tensor = rand_mat <= k_th_quant\n mask = torch.where(bool_tensor, torch.tensor(1), torch.tensor(0)).repeat(sz, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask.cuda(self.tgt_mask.get_device()) if self.tgt_mask.is_cuda else mask\n \n def build_padding_mask(self, tgt, pad):\n # mask = self.tgt_pad_mask.repeat(tgt.shape[0], 1)\n mask = torch.zeros(tgt.shape[0], self.T, dtype=torch.bool)\n # print(mask.shape)\n # print(pad.shape)\n for B, P in enumerate(pad):\n mask[B, self.T - P:] = True\n return mask # .to(torch.cuda.current_device())\n\n def forward(self, tgt, memory, pad):\n # padding_mask = self.build_padding_mask(tgt, pad)\n # print(padding_mask)\n # print(pad)\n # tgt_mask = self.generate_sparse_mask(self.T) if self.training else self.tgt_mask\n return self.decoder(src=memory, tgt=tgt, tgt_mask=self.tgt_mask, \n tgt_key_padding_mask=None)\n\n\nclass ProjectNorm(nn.Module):\n\n def __init__(self, feat_size, target_size):\n super().__init__()\n self.ln = nn.LayerNorm(feat_size)\n self.mlp = nn.Sequential(\n nn.Linear(feat_size, math.floor(2 * feat_size), bias=False),\n nn.GELU(),\n nn.Linear(math.floor(2 * feat_size), target_size, bias=False),\n )\n\n def forward(self, x):\n return self.mlp(self.ln(x))\n\n\nclass TimeProjection(nn.Module):\n \n def __init__(self, seq_size, id_seq_size, feat_size, target_size):\n super().__init__()\n self.mlp_seq = nn.Sequential(\n nn.Linear(seq_size, id_seq_size),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(id_seq_size, id_seq_size)\n )\n self.mlp_t = nn.Sequential(\n nn.Linear(feat_size, feat_size // 2),\n nn.ReLU(),\n nn.Dropout(p=0.3),\n nn.Linear(feat_size // 2, target_size)\n )\n \n def forward(self, x):\n x = x.permute(0, 2, 1) # B, T, C -> B, C, T\n x = self.mlp_seq(x) # B, C, T / 2\n x = x.permute(0, 2, 1) # B, T / 2, C\n return self.mlp_t(x) # B, T / 2, 1\n\n\nclass PSTHProjection(nn.Module):\n \"\"\"Takes Last Output of Block -> (B, C) \n Builds PSTH table \n \"\"\"\n def __init__(self, config):\n super().__init__()\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd, bias=False),\n nn.Dropout(p=0.2),\n nn.GELU(),\n nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n )\n \n def forward(self, x):\n return self.mlp(x)\n\n\n# class PSTHProjection(nn.Module):\n \n# def __init__(self, config):\n# super().__init__()\n# self.mlp_seq = nn.Sequential(\n# nn.Linear(config.id_block_size, config.id_block_size // 2, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.id_block_size // 2, 1, bias=False)\n# )\n# self.mlp_t = nn.Sequential(\n# nn.Linear(config.n_embd, config.n_embd * 4, bias=False),\n# nn.GELU(),\n# nn.Dropout(p=0.2),\n# nn.Linear(config.n_embd * 4, config.id_vocab_size, bias=False)\n# )\n \n# def forward(self, x):\n# x = x.transpose(-1, -2) # B, T, C -> B, C, T\n# x = self.mlp_seq(x) # B, C, 1\n# x = x.transpose(-2, -1) # B, 1, Vocab_id\n# return self.mlp_t(x)\n\n\nclass TimeRNN(nn.Module):\n def __init__(self, feat_size, target_size):\n super().__init__()\n\n\nclass Block(nn.Module):\n \"\"\" an unassuming Transformer block \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.ln1 = nn.LayerNorm(config.n_embd)\n self.ln2 = nn.LayerNorm(config.n_embd)\n self.attn = CausalSelfAttention(config)\n self.mlp = nn.Sequential(\n nn.Linear(config.n_embd, 4 * config.n_embd),\n nn.GELU(),\n nn.Linear(4 * config.n_embd, config.n_embd),\n nn.Dropout(config.resid_pdrop),\n )\n\n def forward(self, x, pad=None, dtx=None):\n x = x + self.attn(self.ln1(x), pad)\n x = x + self.mlp(self.ln2(x))\n return x\n\n\nclass BlockSequential(nn.Sequential):\n def forward(self, x, pad=None, dtx=None):\n for module in self._modules.values():\n x = module(x, pad, dtx)\n return x\n\n\nclass DiceLossPSTH(nn.Module):\n def __init__(self, size_average=True, smooth=1):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets, smooth=1, class_weights=None):\n total_logits = F.layer_norm(torch.sum(logits, dim=-2), [logits.size()[-1]])\n # probs = F.log_softmax(logits, dim=-1)\n probs = F.softmax(total_logits, dim=-1)\n # logits = F.gelu(logits)\n # probs = logits / (logits.max(dim=-1).values.unsqueeze(-1))\n # flatten label and prediction tensors\n outputs = probs.contiguous().view(-1)\n targets = targets.contiguous().view(-1)\n labels = torch.zeros_like(outputs)\n labels[targets] = 1 / len(targets)\n # intersection = (outputs * labels).sum()\n # dice = (2. * intersection + smooth) / (outputs.sum() + labels.sum() + smooth)\n return self.cross_entropy(outputs[None, ...], labels[None, ...])\n\n\nclass SetLoss(nn.Module):\n def __init__(self):\n super().__init__()\n \n def cross_entropy(self, input, target):\n return torch.mean(-torch.sum(target * torch.log(input), 1))\n \n def forward(self, logits, targets):\n targets = targets.contiguous().view(-1)\n loss = 0\n for n_step, n_logits in enumerate(logits):\n n_logits = F.softmax(n_logits, dim=-1)\n n_target = targets[n_step:]\n n_target_dist = torch.zeros_like(n_logits)\n if len(n_target) != 0:\n n_target_dist[n_target] = 1 / len(n_target)\n loss += self.cross_entropy(n_logits[None,...], n_target_dist[None, ...])\n return loss / len(logits)\n\n\nclass TruncatedLoss(nn.Module):\n\n def __init__(self, q=0.8, k=0.2, trainset_size=50000):\n super(TruncatedLoss, self).__init__()\n self.q = q\n self.k = k\n self.weight = torch.nn.Parameter(data=torch.ones(trainset_size, 1), requires_grad=False)\n \n def forward(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n\n loss = ((1-(Yg**self.q))/self.q)*self.weight[indexes] - ((1-(self.k**self.q))/self.q)*self.weight[indexes]\n loss = torch.mean(loss)\n\n return loss\n\n def update_weight(self, logits, targets, indexes):\n p = F.softmax(logits, dim=-1)\n Yg = torch.gather(p, 2, targets.unsqueeze(2))\n Lq = ((1-(Yg**self.q))/self.q)\n Lqk = np.repeat(((1-(self.k**self.q))/self.q), targets.size(0))\n Lqk = torch.from_numpy(Lqk).type(torch.cuda.FloatTensor)\n Lqk = torch.unsqueeze(Lqk, 1)\n \n condition = torch.gt(Lqk, Lq)\n self.weight[indexes] = condition.type(torch.cuda.FloatTensor)\n\n\n# class PSTHLOSS(nn.Module):\n# def __init__(self):\n# super().__init__()\n\n# def forward(self, logits, targets):\n# total_logits = torch.sum(logits, dim=-2) # sum over sequence dimension\n# probs = F.softmax(total_logits, dim=-1)\n# outptu\n\n\nclass HungarianMatcher(nn.Module):\n def __init__(self):\n super().__init__()\n \n @torch.no_grad()\n def forward(self, logits, targets):\n T, C = logits.size()\n probs = F.softmax(logits, dim=-1)\n cost_id = (1 - probs[:, targets]).cpu().view(T, -1).unsqueeze(0)\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_id.split(len(targets), -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\nclass KLDivLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n self.KLdiv = nn.KLDivLoss()\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.KLdiv(log_probs.long(), targets)\n\n\nclass PoissonCrossEntropyLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.log_softmax = nn.LogSoftmax(dim=-1)\n # self.softmax = nn.Softmax(dim=-1)\n self.nll_poisson = nn.PoissonNLLLoss()\n # self.nll_poisson = nn.NLLLoss()\n\n def forward(self, logits, targets):\n log_probs = self.log_softmax(logits)\n return self.nll_poisson(log_probs, targets)\n\n\nclass GPT(nn.Module):\n \"\"\" the full GPT language model, with a context size of block_size \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n self.device = 'cpu'\n if torch.cuda.is_available():\n self.device = torch.cuda.current_device()\n\n self.config = config\n # input embedding stem\n self.n_embd = config.n_embd\n self.tok_emb = nn.Embedding(config.id_vocab_size, config.n_embd)\n self.pos_emb = PositionalEmbedding(config.n_embd, p_drop=0.2)\n # self.pos_emb_id = nn.Parameter(torch.zeros(1, config.id_block_size, config.n_embd))\n self.pos_emb_frames = nn.Parameter(torch.zeros(1, config.frame_block_size, config.n_embd))\n # self.temp_emb = TemporalEmbedding(config.n_embd, p_drop=0.2)\n # self.temp_emb = RotaryTemporalEmbedding(config.id_block_size)\n self.temp_emb = LearntTemporalEmbedding(config.id_block_size, config.n_embd)\n self.frame_temp_emb = LearntTemporalEmbedding(config.frame_block_size, config.n_embd)\n self.id_drop = nn.Dropout(config.id_drop)\n self.im_drop = nn.Dropout(config.im_drop)\n self.drop = nn.Dropout(config.embd_pdrop)\n\n # -- Visual Backbone -- #\n # self.visual_backbone = VideoFeaturesExtractor()\n self.video_encoder = VideoEncoder()\n frame_temp_emb = torch.tensor(list(itertools.chain(*[[n * 0.05] * (config.frame_block_size//20) for n in range(20)]))).unsqueeze(0)\n self.register_buffer(\"frame_temp_emb_seq\", frame_temp_emb)\n\n # -- Contrastive Loss -- ##\n # self.proj_id = ProjectNorm(config.n_embd, config.n_embd)\n # self.proj_vid = VidProjectNorm(config.n_embd, config.n_embd) # im_shape\n \n ## -- IM_Decoder -- ##\n # self.blocks_id = BlockSequential(*[Block(config) for _ in range(2)])\n # self.blocks_im = BlockSequential(*[Block(config) for _ in range(2)])\n # self.ln_f_id = nn.LayerNorm(config.n_embd)\n # self.ln_f_im = nn.LayerNorm(config.n_embd)\n\n ## -- Decoder -- ##\n # self.ln_f = nn.LayerNorm(config.n_embd)\n ## GPT\n self.stimulus_blocks = BlockSequential(*[Block(config) for _ in range(config.n_layer)])\n self.ln_f = nn.LayerNorm(config.n_embd)\n ## enc_dec\n # self.state_decoder = Decoder(config)\n # self.ln_f_state_dec = nn.LayerNorm(config.n_embd)\n # self.stimulus_decoder = Decoder(config)\n # self.ln_f_stimulus_dec = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n \n ## -- Time -- ##\n # self.proj_time = TimeProjection(config.block_size, config.id_block_size, config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, config.n_dt)\n # self.proj_time = ProjectNorm(config.n_embd, 1)\n \n ## -- PSTH -- ##\n # self.proj_psth = PSTHProjection(config)\n\n # Loss\n # self.dice_loss = DiceLossPSTH()\n # self.poisson_loss = PoissonCrossEntropyLoss()\n # self.hungarian_matcher = HungarianMatcher()\n # self.kldiv_loss = KLDivLoss()\n # self.truncated_loss = TruncatedLoss(trainset_size=config.data_size)\n # self.set_loss = SetLoss()\n # self.a = torch.tensor(0.5, requires_grad=True)\n\n self.block_size = config.block_size\n self.apply(self._init_weights)\n \n if config.class_weights is not None:\n self.register_buffer(\"class_weights\", config.class_weights) \n \n logger.info(\"number of parameters: %e\", sum(p.numel() for p in self.parameters()))\n\n def get_block_size(self):\n return self.block_size\n\n def _init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def configure_optimizers(self, train_config):\n \"\"\"\n Separates parameters into those who will experience weight decay and those that will not\n \"\"\"\n if train_config.decay_weights:\n decay = set()\n no_decay = set()\n whitelist_weight_modules = (torch.nn.Linear, )\n blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)\n for mn, m in self.named_modules():\n for pn, p in m.named_parameters():\n fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n if pn.endswith('bias'):\n # all biases will not be decayed\n no_decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):\n # weights of whitelist modules will be weight decayed\n decay.add(fpn)\n elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):\n # weights of blacklist modules will NOT be weight decayed\n no_decay.add(fpn)\n else: no_decay.add(fpn)\n\n # special case the position embedding parameter in the root GPT module as not decayed\n black_list_mods = ['pos_emb', 'temp_emb']\n for mods in black_list_mods:\n for name, param in self.named_parameters():\n if mods in name:\n no_decay.add(name) # also pos_emb\n \n # validate that we considered every parameter\n param_dict = {pn: p for pn, p in self.named_parameters()}\n no_decay -= decay & no_decay\n inter_params = decay & no_decay\n union_params = decay | no_decay\n\n assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n % (str(param_dict.keys() - union_params), )\n\n \n # create the pytorch optimizer object\n optim_groups = [\n {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": train_config.weight_decay},\n {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n ]\n optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)\n \n else:\n parameters = self.parameters()\n optimizer = torch.optim.Adam(parameters, lr=train_config.learning_rate)\n \n return optimizer\n \n def process_features(self, x):\n # batch, block_size, feature\n # p_idx = x['id_prev']\n idx = x['id']\n dtx = x['dt']\n # dtx_prev = x['dt_prev']\n frames = self.video_encoder(x['frames'])\n pad = x['pad']\n\n b, t = idx.size()\n # b_p, t_p = p_idx.size()\n bf, tf = frames.size()[0:2]\n\n # forward the GPT model\n ''' \n positional and temporal embeddings implemented in multiple ways, learnt, \n fourrier decomposition and in the case of time, just passed as is. \n '''\n # # Embeddings\n # prev_id_position_embeddings = 0 # self.pos_emb(p_idx)\n # prev_id_temporal_embeddings = self.temp_emb(dtx_prev.float())\n id_position_embeddings = 0 # self.pos_emb(idx) \n im_position_embeddings = self.pos_emb_frames\n temporal_embeddings = self.temp_emb(dtx.float())\n \n # Extract ID features\n # prev_token_embeddings = self.id_drop(self.tok_emb(p_idx) + prev_id_temporal_embeddings + prev_id_position_embeddings)\n token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector\n token_embeddings = token_embeddings + temporal_embeddings + id_position_embeddings\n token_embeddings = self.id_drop(token_embeddings)\n\n # Extract image features and add time embeddings\n im_temporal_embeddings = self.frame_temp_emb(self.frame_temp_emb_seq)\n im_embeddings = frames # self.tok_emb(frames)\n im_embeddings = im_embeddings + im_position_embeddings + im_temporal_embeddings\n im_embeddings = self.im_drop(im_embeddings) # separate pos emb?\n \n # Tidy up\n features = dict()\n # features['id_prev'] = prev_token_embeddings\n features['id'] = token_embeddings\n features['frames'] = im_embeddings\n \n return features, pad\n\n def perceiver(self, features, pad):\n x = self.state_decoder(tgt=features['id'], memory=features['id_prev'], pad=pad)\n x = self.ln_f_state_dec(x)\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def enc_dec(self, features, pad):\n x = self.stimulus_decoder(tgt=features['id'], memory=features['frames'], pad=pad)\n x = self.ln_f_stimulus_dec(x)\n logits = self.head(x)\n\n return logits, x\n\n def GPTdecoder(self, features, pad, dtx=None):\n # image + neural features\n x = torch.cat((features['frames'], features['id']), dim=1)\n\n # Decoder\n x = self.blocks(x, pad, dtx) # (B, T, C)\n x = self.ln_f(x)\n logits = self.head(x)\n\n # print(logits.shape) # (B, T, Vocab)\n # logits_psth = x[:, -1] # (B, C)\n\n return logits, x\n\n def forward(self, x, targets=None):\n idx = x['id']\n dtx = x['dt']\n frames = x['frames']\n pad = x['pad']\n\n b, t = idx.size()\n # b, t = x['id'].shape[0], x['id'].shape[1] + x['id_prev'].shape[1]\n bf, tf = frames.size()[0:2]\n tf = self.config.frame_block_size\n # assert t + tf == self.config.block_size, f\"{tf} {t}\"\n # assert t <= self.block_size, \"Cannot forward, model block size is exhausted\"\n \n features, pad = self.process_features(x)\n # logits, x = self.perceiver(features, pad)\n # logits, x = self.enc_dec(features, pad)\n logits, x = self.GPTdecoder(features, pad)\n # time = self.proj_time(x) # (B, T_id, 1)\n\n # print(x[:, 0].shape)\n # psth = self.proj_psth(x) # (B, Vocab_id)\n\n # if targets, calculate loss\n # calculate loss on logits up to padding token for each batch\n loss = None\n loss_frames = 0\n loss_id = []\n loss_time = []\n loss_dice = []\n loss_psth = []\n loss_hungarian = []\n if targets is not None:\n # loss_psth = self.dice_loss(psth, targets['modes'][:, tf:]) \n for B, P in enumerate(pad):\n # im_logits = logits[B, :tf]\n # im_targets = targets['frames'][B, :tf]\n # loss_frames += F.cross_entropy(im_logits.view(-1, im_logits.size(-1)), im_targets.view(-1))\n id_logits = logits[B, tf:tf + t - P]\n id_targets = targets['id'][B, :t - P]\n\n loss_id_ = F.cross_entropy(id_logits.view(-1, id_logits.size(-1)), id_targets.view(-1), weight=self.class_weights)\n # if self.config.epoch >= 15:\n # self.truncated_loss.update_weight(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # loss_id_ = self.truncated_loss(id_logits[None, ...], id_targets[None, ...], id_indexes[None, ...])\n # time_preds = time[B, :t - P]\n # time_targets = targets['dt'][B, :t - P]\n # loss_time_ = F.cross_entropy(time_preds.view(-1, time_preds.size(-1)), time_targets.view(-1))\n # loss_time_ = F.mse_loss(time_preds.squeeze(-1), time_targets)\n # loss_id_ = self.poisson_loss(id_logits.view(-1, id_logits.size(-1)), F.one_hot(id_targets, self.config.vocab_size))\n # if len(id_targets) > 0:\n # indices = self.hungarian_matcher(id_logits, id_targets)\n # probs_matching, targets_matching = id_logits[indices[0][0]], id_targets[indices[0][1]]\n # loss_hungarian_ = F.cross_entropy(probs_matching, targets_matching, weight=self.class_weights).to(self.device)\n # loss_hungarian.append(loss_hungarian_)\n # # psth = self.proj_psth(x[B, -1]) # from the EOS position\n \n # loss_psth.append(torch.nan_to_num(self.set_loss(id_logits, id_targets)))\n # loss_psth_ = self.dice_loss(id_logits, id_targets)\n # loss_psth.append(torch.nan_to_num(loss_psth_))\n \n # loss_time.append(torch.nan_to_num(loss_time_))\n loss_id.append(torch.nan_to_num(loss_id_))\n \n loss = dict()\n # loss['frames'] = loss_frames / (b / 3)\n loss['id'] = sum(loss_id) / (b) # sum(loss_id) / (b * 2) # / len(loss_id)\n # loss['time'] = sum(loss_time) / (b * 2)\n # loss['dice'] = sum(loss_dice) / len(loss_dice)\n # loss['dt'] = loss_time / (b * 50)\n # loss['hungarian'] = sum(loss_hungarian) / (b * 2)\n # loss['psth'] = sum(loss_psth) / (b * 2)\n\n for key in list(loss):\n if isinstance(loss[key], float):\n del loss[key]\n \n preds = dict()\n preds['logits'] = logits # [:, tf:] # only id logits\n # preds['dt'] = time\n\n return preds, features, loss" ]
[ [ "torch.all", "torch.mean", "torch.nn.functional.softmax", "torch.zeros", "torch.sin", "torch.nn.Transformer", "torch.cat", "torch.sum", "torch.nn.Embedding", "torch.no_grad", "torch.cuda.is_available", "torch.topk", "scipy.optimize.linear_sum_assignment", "torch.nn.Dropout", "torch.ones", "torch.from_numpy", "torch.tensor", "torch.rand", "torch.arange", "torch.cos", "torch.optim.Adam", "torch.nn.LogSoftmax", "torch.cuda.current_device", "torch.zeros_like", "torch.unsqueeze", "torch.nn.Linear", "torch.optim.AdamW", "torch.log", "torch.as_tensor", "torch.nn.GELU", "torch.nn.KLDivLoss", "torch.nan_to_num", "torch.nn.PoissonNLLLoss", "torch.nn.LayerNorm", "torch.nn.ReLU", "torch.gt" ], [ "torch.all", "torch.mean", "torch.nn.functional.softmax", "torch.zeros", "torch.sin", "torch.nn.Transformer", "torch.cat", "torch.sum", "torch.nn.Embedding", "torch.no_grad", "torch.cuda.is_available", "torch.topk", "scipy.optimize.linear_sum_assignment", "torch.nn.Dropout", "torch.ones", "torch.from_numpy", "torch.tensor", "torch.rand", "torch.arange", "torch.cos", "torch.optim.Adam", "torch.nn.LogSoftmax", "torch.cuda.current_device", "torch.zeros_like", "torch.unsqueeze", "torch.nn.Linear", "torch.optim.AdamW", "torch.log", "torch.as_tensor", "torch.nn.GELU", "torch.nn.KLDivLoss", "torch.nan_to_num", "torch.nn.PoissonNLLLoss", "torch.nn.LayerNorm", "torch.nn.ReLU", "torch.gt" ], [ "torch.all", "torch.mean", "torch.nn.functional.softmax", "torch.zeros", "torch.sin", "torch.nn.Transformer", "torch.cat", "torch.sum", "torch.nn.Embedding", "torch.no_grad", "torch.cuda.is_available", "torch.topk", "scipy.optimize.linear_sum_assignment", "torch.nn.Dropout", "torch.ones", "torch.from_numpy", "torch.tensor", "torch.rand", "torch.arange", "torch.cos", "torch.optim.Adam", "torch.nn.LogSoftmax", "torch.cuda.current_device", "torch.zeros_like", "torch.unsqueeze", "torch.nn.Linear", "torch.optim.AdamW", "torch.log", "torch.as_tensor", "torch.nn.GELU", "torch.nn.KLDivLoss", "torch.nan_to_num", "torch.nn.PoissonNLLLoss", "torch.nn.LayerNorm", "torch.nn.ReLU", "torch.gt" ], [ "torch.mean", "torch.nn.functional.softmax", "torch.zeros", "torch.sin", "torch.nn.Transformer", "torch.cat", "torch.sum", "torch.nn.Embedding", "torch.no_grad", "torch.cuda.is_available", "torch.topk", "scipy.optimize.linear_sum_assignment", "torch.nn.Dropout", "torch.ones", "torch.from_numpy", "torch.tensor", "torch.rand", "torch.arange", "torch.cos", "torch.optim.Adam", "torch.nn.LogSoftmax", "torch.cuda.current_device", "torch.zeros_like", "torch.unsqueeze", "torch.nn.Linear", "torch.optim.AdamW", "torch.log", "torch.stack", "torch.as_tensor", "torch.nn.GELU", "torch.nn.KLDivLoss", "torch.nan_to_num", "torch.nn.PoissonNLLLoss", "torch.nn.LayerNorm", "torch.nn.ReLU", "torch.gt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
agramfort/pymultifracs
[ "3a8896f3f26180b05ccecb4a905b05a3ebc0308b", "3a8896f3f26180b05ccecb4a905b05a3ebc0308b" ]
[ "pymultifracs/simul/mrw.py", "pymultifracs/structurefunction.py" ]
[ "# Synthesis of multifractal random walk and derived processes.\n#\n# Roberto Fabio Leonarduzzi\n# January, 2019\n\nimport numpy as np\nfrom .fbm import fgn\nfrom .pzutils import gaussian_cme, gaussian_chol\nfrom numpy.fft import fft, ifft\n# import math\n# import matplotlib.pyplot as plt\n\n\ndef mrw(shape, H, lam, L, sigma=1, method='cme', z0=(None, None)):\n '''\n Create a realization of fractional Brownian motion using circulant\n matrix embedding.\n\n Parameters\n ----------\n shape : int | tuple(int)\n If scalar, it is the number of samples. If tuple it is (N, R),\n the number of samples and realizations, respectively.\n H : float\n Hurst exponent\n lam : float\n Lambda, intermittency parameter\n L : float\n Integral scale\n sigma : float\n Variance of process\n\n Returns\n -------\n mrw : ndarray\n Synthesized mrw realizations. If `shape` is scalar,\n fbm is ofshape (N,). Otherwise, it is of shape (N, R).\n\n References\n ----------\n .. [1] Bacry, Delour, Muzy, \"Multifractal Random Walk\", Physical Review E,\n 2001\n '''\n\n try:\n N, R = shape\n do_squeeze = False\n except TypeError: # shape is scalar\n N, R = shape, 1\n do_squeeze = True\n\n # Is 0.5 or 0 the lower bound ? Search biblio\n if not 0 <= H <= 1:\n raise ValueError('H must satisfy 0 <= H <= 1')\n\n if L > N:\n raise ValueError('Integral scale L is larger than data length N')\n\n # 1) Gaussian process w\n w = gaussian_w(N, R, L, lam, 1, method, z0[1])\n\n # Adjust mean to ensure convergence of variance\n r = 1/2 # see Bacry, Delour & Muzy, Phys Rev E, 2001, page 4\n w = w - np.mean(w, axis=0) - r * lam**2 * np.log(L)\n\n # 2) fGn e\n e = fgn((N, R), H, sigma, method=method, z0=z0[0])\n\n # 3) mrw\n mrw = np.cumsum(e * np.exp(w), axis=0)\n\n return mrw.squeeze() if do_squeeze else mrw\n\n\ndef mrw_cumul(shape, c1, c2, L, **kwargs):\n '''\n Wrapper for mrw generation from cumulants.\n\n Parameters\n ----------\n shape : int | tuple(int)\n If scalar, it is the number of samples. If tuple it is (N, R),\n the number of samples and realizations, respectively.\n c1 : float\n First order cumulant\n c2 : float\n Second order cumulant\n L : float\n Integral scale\n kwargs : dict\n Optional parameters passed to :obj:`mrw`\n\n Returns\n -------\n mrw : ndarray\n Synthesized mrw realizations. If `shape` is scalar,\n fbm is ofshape (N,). Otherwise, it is of shape (N, R).\n\n References\n ----------\n .. [1] Bacry, Delour, Muzy, \"Multifractal Random Walk\", Physical Review E,\n 2001\n '''\n\n H = c1 + c2\n lam = np.sqrt(-c2)\n\n return mrw(shape, H, lam, L, **kwargs)\n\n\ndef skewed_mrw(shape, H, lam, L, K0=1, alpha=1, sigma=1, dt=1, beta=1,\n do_mirror=False):\n '''\n Create skewed mrw as in Pochart & Bouchaud\n Assumes :math:`\\\\Delta_t=1`, so no parameter beta is needed.\n '''\n\n try:\n N, R = shape\n do_squeeze = False\n except TypeError: # shape is scalar\n N, R = shape, 1\n do_squeeze = True\n\n # Is 0.5 or 0 the lower bound ? Search biblio\n if not 0 <= H <= 1:\n raise ValueError('H must satisfy 0 <= H <= 1')\n\n if L / dt > N:\n raise ValueError('Integral scale L/dt is larger than data length N')\n\n # 1) Gaussian process w\n w = gaussian_w(N, R, L, lam, dt)\n\n # Adjust mean to ensure convergence of variance\n r = 1 # see Bacry, Delour & Muzy, Phys Rev E, 2001, page 4\n w = w - np.mean(w, axis=0) - r * lam**2 * np.log(L / dt)\n\n # 2) fGn e\n e = fgn((2*N + 1, R), H, sigma, dt)\n\n # 3) Correlate components\n past = skewness_convolution(e, K0, alpha, beta, dt)\n wtilde = w - past\n\n # 4) skewed mrw\n smrw = np.cumsum(e[N:] * np.exp(wtilde), axis=0)\n\n if do_squeeze:\n smrw = smrw.squeeze()\n\n if do_mirror:\n past_mirror = skewness_convolution(-e, K0, alpha, beta, dt)\n wtilde_mirror = w - past_mirror\n smrw_mirror = np.cumsum(-e[N:] * np.exp(wtilde_mirror), axis=0)\n if do_squeeze:\n smrw_mirror = smrw_mirror.squeeze()\n return smrw, smrw_mirror\n else:\n return smrw\n\n\ndef gaussian_w(N, R, L, lam, dt=1, method='cme', z0=None):\n '''\n Auxiliar function to create gaussian process w\n '''\n kmax = int(L / dt)\n k = np.arange(kmax)\n rho = np.ones((N))\n rho[:kmax] = L / (k + 1) / dt\n cov = (lam ** 2) * np.log(rho)\n if method == 'cme':\n w = gaussian_cme(cov, N, R, z0)\n elif method == 'chol':\n w = gaussian_chol(cov, N, R, z0)\n\n return w\n\n\ndef skewness_convolution(e, K0, alpha, beta=1, dt=1):\n '''\n Noise e should be of length 2*N, with \"N false past variables\" at the\n beginning to avoid spurious correlations due to cutoffs in convolution.\n '''\n N, _ = e.shape\n N = N // 2\n\n tau = np.arange(1, N+1)\n Kbar = np.zeros((2*N))\n Kbar[1:N+1] = K0 / (tau**alpha) / (dt**beta)\n skew_conv = np.real(ifft(fft(Kbar[:, None], axis=0) *\n fft(e, axis=0), axis=0))\n return skew_conv[N:]\n\n\ndef skewness_convolution_dumb(e, K0, alpha, beta=1, dt=1):\n '''\n Direct and inefficient calculation for testing purposes.\n Receives \"true\" input noise of size N.\n '''\n N, R = e.shape\n\n def K(i, j):\n return K0 / (j-i)**alpha / dt**beta\n\n scorr = np.zeros((N, R))\n for k in range(N):\n for i in range(k):\n scorr[k, :] += K(i, k) * e[i, :]\n return scorr\n\n\ndef mrw2D(shape, H, lam, L, sigma=1):\n '''\n Create a realization of fractional Brownian motion using circulant\n matrix embedding.\n\n Parameters\n ----------\n shape : int | tuple(int)\n If scalar, it is the number of samples. If tuple it is (N, R),\n the number of samples and realizations, respectively.\n H : float\n Hurst exponent\n lambda : float\n Intermittency parameter\n L : float\n Integral scale\n sigma : float\n Variance of process\n\n Returns\n -------\n mrw : ndarray\n Synthesized mrw realizations. If 'shape' is scalar,\n fbm is of shape (N,). Otherwise, it is of shape (N, N, R).\n\n References\n ----------\n .. [1] Bacry, Delour, Muzy, \"Multifractal Random Walk\", Physical Review E,\n 2001\n '''\n\n try:\n N, R = shape\n # do_squeeze = False\n except TypeError: # shape is scalar\n N, R = shape, 1\n # do_squeeze = True\n\n N = int(2 * np.ceil(N / 2))\n\n # dim = 2\n\n n = np.arange(-N // 2, N // 2)\n d = np.sqrt(n[:, None]**2 + n[None, :]**2)\n\n corr = lam**2 * np.log(np.maximum(L / (1 + d), 1))\n\n L = np.fft.fft2(corr)\n\n z1 = np.random.randn(N, N, R) + 1j * np.random.randn(N, N, R)\n w = np.exp(np.real(np.fft.ifft2(z1 * np.sqrt(L[..., None]), axes=(0, 1))))\n\n # Increment process:\n X = np.random.randn(N, N, R) * w\n\n # Fractional integration to produce motion:\n BX = fract_int_2d(X, H + 1)\n\n return BX, X\n\n\ndef fract_int_2d(x, alpha):\n '''\n Assumes size of x divisible by two\n '''\n N = x.shape[0]\n\n # Create Fourier filter\n k = np.arange(-N/2, N/2)\n\n d = np.sqrt(k[:, None]**2 + k[None, :]**2)\n mini = np.min(d[d != 0])\n d[d == 0] = mini\n filt = 1 / (d ** alpha)\n\n yhat = np.fft.fftshift(np.fft.fft2(x, axes=(0, 1)), axes=(0, 1))\n yhat *= filt[..., None]\n y = np.real(np.fft.ifft2(np.fft.ifftshift(yhat, axes=(0, 1)), axes=(0, 1)))\n return y\n", "\"\"\"\nAuthors: Omar D. Domingues <[email protected]>\n Merlin Dumeur <[email protected]>\n\"\"\"\n\nfrom dataclasses import dataclass, InitVar, field\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom .utils import linear_regression, fast_power\nfrom .multiresquantity import MultiResolutionQuantityBase,\\\n MultiResolutionQuantity\n\n\n@dataclass\nclass StructureFunction(MultiResolutionQuantityBase):\n \"\"\"\n Computes and analyzes structure functions\n\n Parameters\n ----------\n mrq : MultiResolutionQuantity\n Multi resolution quantity to analyze.\n q : ndarray, shape (n_exponents,)\n Exponent for which to compute the structure function\n j1 : int\n Lower-bound of the scale support for the linear regressions.\n j2 : int\n Upper-bound of the scale support for the linear regressions.\n wtype: bool\n Whether to used weighted linear regressions.\n\n Attributes\n ----------\n formalism : str\n Formalism used. Can be any of 'wavelet coefs', 'wavelet leaders',\n or 'wavelet p-leaders'.\n nj : dict(ndarray)\n Number of coefficients at scale j.\n Arrays are of the shape (nrep,)\n j : ndarray, shape (n_scales,)\n List of the j values (scales), in order presented in the value arrays.\n j1 : int\n Lower-bound of the scale support for the linear regressions.\n j2 : int\n Upper-bound of the scale support for the linear regressions.\n wtype : bool\n Whether weighted regression was performed.\n q : ndarray, shape (n_exponents,)\n Exponents for which the structure functions have been computed\n values : ndarray, shape (n_exponents, n_scales, nrep)\n Structure functions : :math:`S(j, q)`\n logvalues : ndarray, shape (n_exponents, n_scales, nrep)\n :math:`\\\\log_2 S(j, q)`\n zeta : ndarray, shape(n_exponents, nrep)\n Scaling function : :math:`\\\\zeta(q)`\n H : ndarray, shape (nrep,) | None\n Estimates of H. Set to None if 2 is not in `q`.\n nrep : int\n Number of realisations\n\n \"\"\"\n mrq: InitVar[MultiResolutionQuantity]\n q: np.array\n j1: int\n j2: int\n wtype: bool\n j: np.array = field(init=False)\n logvalues: np.array = field(init=False)\n zeta: np.array = field(init=False)\n H: np.array = field(init=False)\n\n def __post_init__(self, mrq):\n\n self.formalism = mrq.formalism\n self.gamint = mrq.gamint\n self.nrep = mrq.nrep\n self.j = np.array(list(mrq.values))\n\n self._compute(mrq)\n self._compute_zeta(mrq)\n self.H = self._get_H()\n\n def _compute(self, mrq):\n\n values = np.zeros((len(self.q), len(self.j), self.nrep))\n\n for ind_j, j in enumerate(self.j):\n\n c_j = mrq.values[j]\n s_j = np.zeros((values.shape[0], self.nrep))\n\n for ind_q, q in enumerate(self.q):\n s_j[ind_q, :] = np.nanmean(fast_power(np.abs(c_j), q), axis=0)\n\n values[:, ind_j, :] = s_j\n\n self.logvalues = np.log2(values)\n\n def _compute_zeta(self, mrq):\n \"\"\"\n Compute the value of the scale function zeta(q) for all q\n \"\"\"\n self.zeta = np.zeros((len(self.q), self.nrep))\n self.intercept = np.zeros((len(self.q), self.nrep))\n\n x = np.tile(np.arange(self.j1, self.j2+1)[:, None],\n (1, self.nrep))\n\n if self.wtype:\n nj = mrq.get_nj_interv(self.j1, self.j2)\n else:\n nj = np.ones((len(x), self.nrep))\n\n ind_j1 = self.j1-1\n ind_j2 = self.j2-1\n for ind_q in range(len(self.q)):\n y = self.logvalues[ind_q, ind_j1:ind_j2+1]\n slope, intercept = linear_regression(x, y, nj)\n self.zeta[ind_q] = slope\n self.intercept[ind_q] = intercept\n\n def _get_H(self):\n return (self.zeta[self.q == 2][0] / 2) - self.gamint\n\n def get_intercept(self):\n intercept = self.intercept[self.q == 2]\n\n if len(intercept) > 0:\n return intercept[0]\n\n return None\n\n def plot(self, figlabel='Structure Functions', nrow=4, filename=None,\n ignore_q0=True):\n \"\"\"\n Plots the structure functions.\n \"\"\"\n\n nrow = min(nrow, len(self.q))\n nq = len(self.q) + (-1 if 0.0 in self.q and ignore_q0 else 0)\n\n if nq > 1:\n plot_dim_1 = nrow\n plot_dim_2 = int(np.ceil(nq / nrow))\n\n else:\n plot_dim_1 = 1\n plot_dim_2 = 1\n\n fig, axes = plt.subplots(plot_dim_1,\n plot_dim_2,\n num=figlabel,\n squeeze=False,\n figsize=(30, 10))\n\n fig.suptitle(self.formalism +\n r' - structure functions $\\log_2(S(j,q))$')\n\n x = self.j\n for ind_q, q in enumerate(self.q):\n\n if q == 0.0 and ignore_q0:\n continue\n\n y = self.logvalues[ind_q, :]\n\n ax = axes[ind_q % nrow][ind_q // nrow]\n ax.plot(x, y, 'r--.')\n ax.set_xlabel('j')\n ax.set_ylabel(f'q = {q:.3f}')\n\n if len(self.zeta) > 0:\n # plot regression line\n x0 = self.j1\n x1 = self.j2\n slope = self.zeta[ind_q]\n intercept = self.intercept[ind_q]\n y0 = slope*x0 + intercept\n y1 = slope*x1 + intercept\n legend = 'slope = '+'%.5f' % (slope)\n\n ax.plot([x0, x1], [y0, y1], color='k',\n linestyle='-', linewidth=2, label=legend)\n ax.legend()\n\n for j in range(ind_q + 1, len(axes.flat)):\n fig.delaxes(axes[j % nrow][j // nrow])\n plt.draw()\n\n if filename is not None:\n plt.savefig(filename)\n\n def plot_scaling(self, figlabel='Scaling Function', filename=None):\n\n assert len(self.q) > 1, (\"This plot is only possible if more than 1 q\",\n \" value is used\")\n\n plt.figure(figlabel)\n plt.plot(self.q, self.zeta, 'k--.')\n plt.xlabel('q')\n plt.ylabel(r'$\\zeta(q)$')\n plt.suptitle(self.formalism + ' - scaling function')\n\n plt.draw()\n\n if filename is not None:\n plt.savefig(filename)\n" ]
[ [ "numpy.fft.fft2", "numpy.log", "numpy.maximum", "numpy.sqrt", "numpy.fft.fft", "numpy.min", "numpy.arange", "numpy.ones", "numpy.ceil", "numpy.fft.ifftshift", "numpy.random.randn", "numpy.mean", "numpy.exp", "numpy.zeros" ], [ "numpy.log2", "numpy.abs", "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "matplotlib.pyplot.draw", "matplotlib.pyplot.plot", "numpy.ceil", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.suptitle", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CatTiger/vnpy
[ "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b", "7901a0fb80a5b44d6fc752bd4b2b64ec62c8f84b" ]
[ "venv/lib/python3.7/site-packages/rqdatac/services/stock_status.py", "venv/lib/python3.7/site-packages/rqdatac/services/financial.py", "venv/lib/python3.7/site-packages/rqdatac/services/structured_fund.py", "vnpy/analyze/util/support_resistence.py" ]
[ "# -*- coding: utf-8 -*-\nimport datetime\nimport warnings\n\nimport pandas as pd\nimport numpy as np\n\nfrom rqdatac.utils import to_datetime, to_date\nfrom rqdatac.validators import (\n ensure_date_range,\n ensure_date_or_today_int,\n ensure_list_of_string,\n check_items_in_container,\n ensure_order,\n ensure_order_book_id,\n ensure_order_book_ids,\n ensure_dates_base_on_listed_date,\n ensure_string,\n ensure_date_int\n)\nfrom rqdatac.services.basic import instruments\nfrom rqdatac.services.calendar import (\n get_trading_dates,\n get_previous_trading_date,\n get_trading_dates_in_type,\n)\nfrom rqdatac.client import get_client\nfrom rqdatac.decorators import export_as_api, compatible_with_parm\n\n\n@export_as_api\ndef is_st_stock(order_book_ids, start_date=None, end_date=None, market=\"cn\"):\n \"\"\"判断股票在给定的时间段是否是ST股, 返回值为一个DataFrame\n\n :param order_book_ids: 股票 id\n :param start_date: (Default value = None)\n :param end_date: (Default value = None)\n :param market: (Default value = \"cn\")\n\n \"\"\"\n order_book_ids = ensure_order_book_ids(order_book_ids, type=\"CS\", market=market)\n\n if len(order_book_ids) == 1:\n instrument = instruments(order_book_ids[0], market=market)\n start_date, end_date = ensure_dates_base_on_listed_date(instrument, start_date, end_date, market)\n if start_date is None:\n return\n\n start_date, end_date = ensure_date_range(start_date, end_date)\n\n trading_dates = pd.to_datetime(get_trading_dates(start_date, end_date, market=market))\n data = get_client().execute(\n \"get_st_days\", order_book_ids, start_date=start_date, end_date=end_date\n )\n df = pd.DataFrame(data=False, columns=order_book_ids, index=trading_dates)\n for idx, dates in data.items():\n for date in dates:\n date = to_datetime(date)\n df.at[date, idx] = True\n return df\n\n\n@export_as_api\ndef _is_st_stock(order_book_id, date=None, market=\"cn\"):\n \"\"\"判断股票在给定日期是否是ST股\n :param order_book_id: 股票id\n :param date: (Default value = None)\n :param market: (Default value = \"cn\")\n :returns: True or False\n \"\"\"\n order_book_id = ensure_order_book_id(order_book_id, type=\"CS\", market=market)\n date = ensure_date_or_today_int(date)\n df = is_st_stock(order_book_id, start_date=date, end_date=date, market=market)\n if df is None or df.empty:\n return False\n else:\n return df[order_book_id][0]\n\n\n@export_as_api\n@compatible_with_parm(name=\"country\", value=\"cn\", replace=\"market\")\ndef is_suspended(order_book_ids, start_date=None, end_date=None, market=\"cn\"):\n \"\"\"获取股票停牌信息\n\n :param order_book_ids: 股票名称\n :param start_date: 开始日期, 如'2013-01-04' (Default value = None)\n :param end_date: 结束日期,如'2014-01-04' (Default value = None)\n :param market: 地区代码, 如 'cn' (Default value = \"cn\")\n :returns: DataFrame\n\n \"\"\"\n order_book_ids = ensure_order_book_ids(order_book_ids, type=\"CS\", market=market)\n\n if len(order_book_ids) == 1:\n instrument = instruments(order_book_ids[0], market=market)\n start_date, end_date = ensure_dates_base_on_listed_date(instrument, start_date, end_date, market)\n if start_date is None:\n return\n\n start_date, end_date = ensure_date_range(start_date, end_date)\n\n trading_dates = pd.to_datetime(get_trading_dates(start_date, end_date, market=market))\n df = pd.DataFrame(data=False, columns=order_book_ids, index=trading_dates)\n data = get_client().execute(\"get_suspended_days\", order_book_ids, start_date, end_date, market=market)\n for idx, dates in data.items():\n for date in dates:\n date = to_datetime(int(date))\n df.at[date, idx] = True\n return df\n\n\nstock_fields = {\"shares_holding\": \"shares_holding\", \"holding_ratio\": \"holding_ratio\"}\nspecial_symbols = [\"all_connect\", \"shanghai_connect\", \"shenzhen_connect\"]\nsymbols_map = {\"shanghai_connect\": \"SH\", \"shenzhen_connect\": \"SZ\"}\n\n\n@export_as_api\ndef get_stock_connect(order_book_ids, start_date=None, end_date=None, fields=None, expect_df=False):\n \"\"\"获取\"陆股通\"的持股、持股比例\n\n :param order_book_ids: 股票列表\n :param start_date: 开始日期: 如'2017-03-17' (Default value = None)\n :param end_date: 结束日期: 如'2018-03-16' (Default value = None)\n :param fields: 默认为所有字段,可输入shares_holding或者holding_ratio (Default value = None)\n :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\n :returns: 返回pandas.DataFrame or pandas.Panel\n\n \"\"\"\n if order_book_ids not in (\"shanghai_connect\", \"shenzhen_connect\", \"all_connect\"):\n order_book_ids = ensure_order_book_ids(order_book_ids, type=\"CS\")\n start_date, end_date = ensure_date_range(start_date, end_date)\n if fields is not None:\n fields = ensure_list_of_string(fields)\n for f in fields:\n if f not in (\"shares_holding\", \"holding_ratio\"):\n raise ValueError(\"invalid field: {}\".format(f))\n else:\n fields = [\"shares_holding\", \"holding_ratio\"]\n\n data = get_client().execute(\"get_stock_connect\", order_book_ids, start_date, end_date, fields)\n if not data:\n return None\n df = pd.DataFrame(data, columns=[\"trading_date\", \"order_book_id\"] + fields)\n\n if expect_df:\n df.sort_values([\"order_book_id\", \"trading_date\"], inplace=True)\n df.set_index([\"order_book_id\", \"trading_date\"], inplace=True)\n return df\n\n df = df.set_index([\"trading_date\", \"order_book_id\"])\n df = df.to_panel()\n df.major_axis.name = None\n df.minor_axis.name = None\n if len(order_book_ids) == 1:\n df = df.minor_xs(order_book_ids[0])\n if len(fields) == 1:\n df = df[fields[0]]\n if len(order_book_ids) != 1 and len(fields) != 1:\n warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\n \" the default value of 'expect_df' will change to True in the future.\")\n return df\n\n\nMARGIN_FIELDS = (\n \"margin_balance\",\n \"buy_on_margin_value\",\n \"short_sell_quantity\",\n \"margin_repayment\",\n \"short_balance_quantity\",\n \"short_repayment_quantity\",\n \"short_balance\",\n \"total_balance\",\n)\n\nMARGIN_SUMMARY_MAP = {\"SH\": \"XSHG\", \"XSHG\": \"XSHG\", \"SZ\": \"XSHE\", \"XSHE\": \"XSHE\"}\n\n\n@export_as_api\ndef get_securities_margin(\n order_book_ids, start_date=None, end_date=None, fields=None, expect_df=False, market=\"cn\"\n):\n \"\"\"获取股票融资融券数据\n\n :param order_book_ids: 股票代码或代码列表\n :param start_date: 开始时间,支持 str, date, datetime, pandasTimestamp\n 默认为 end_date 之前一个月 (Default value = None)\n :param end_date: 结束时间 默认为当前日期前一天 (Default value = None)\n :param fields: str 或 list 类型. 默认为 None, 返回所有字段。可选字段包括:\n today, week, month, three_month, six_month, year, current_year, total\n (Default value = None)\n :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\n :param market: 地区代码, 如: 'cn' (Default value = \"cn\")\n :returns: 如果传入多个股票代码,且 fields 为多个或者 None,返回 pandas.Panel\n 如果传入一只股票或者 fields 为单个字段,则返回 pandas.DataFrame\n 如果传入的股票代码和字段数都是1,则返回 pandas.Series\n\n \"\"\"\n\n order_book_ids = ensure_list_of_string(order_book_ids, \"order_book_ids\")\n all_list = []\n for order_book_id in order_book_ids:\n if order_book_id.upper() in MARGIN_SUMMARY_MAP:\n all_list.append(MARGIN_SUMMARY_MAP[order_book_id.upper()])\n else:\n inst = instruments(order_book_id, market)\n\n if inst.type in [\"CS\", \"ETF\", \"LOF\"]:\n all_list.append(inst.order_book_id)\n else:\n warnings.warn(\"{} is not stock, ETF, or LOF.\".format(order_book_id))\n order_book_ids = all_list\n if not order_book_ids:\n raise ValueError(\"no valid securities in {}\".format(order_book_ids))\n\n if fields is None:\n fields = list(MARGIN_FIELDS)\n else:\n fields = ensure_list_of_string(fields, \"fields\")\n check_items_in_container(fields, MARGIN_FIELDS, \"fields\")\n fields = ensure_order(fields, MARGIN_FIELDS)\n start_date, end_date = ensure_date_range(start_date, end_date)\n if end_date > ensure_date_or_today_int(None):\n end_date = ensure_date_or_today_int(get_previous_trading_date(datetime.date.today()))\n trading_dates = pd.to_datetime(get_trading_dates(start_date, end_date, market=market))\n\n data = get_client().execute(\n \"get_securities_margin\", order_book_ids, start_date, end_date, market=market\n )\n if not data:\n return\n\n if expect_df:\n df = pd.DataFrame(data)\n df.sort_values([\"order_book_id\", \"date\"], inplace=True)\n df.set_index([\"order_book_id\", \"date\"], inplace=True)\n df = df.reindex(columns=fields)\n return df\n\n pl = pd.Panel(items=fields, major_axis=trading_dates, minor_axis=order_book_ids)\n for r in data:\n for field in fields:\n value = r.get(field)\n pl.at[field, r[\"date\"], r[\"order_book_id\"]] = value\n\n if len(order_book_ids) == 1:\n pl = pl.minor_xs(order_book_ids[0])\n if len(fields) == 1:\n pl = pl[fields[0]]\n if len(order_book_ids) != 1 and len(fields) != 1:\n warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\n \" the default value of 'expect_df' will change to True in the future.\")\n return pl\n\n\nMARGIN_TYPE = (\"stock\", \"cash\")\nEXCHANGE_TYPE = {\"SZ\": \"XSHE\", \"sz\": \"XSHE\", \"xshe\": \"XSHE\", \"SH\": \"XSHG\", \"sh\": \"XSHG\", \"xshg\": \"XSHG\"}\nEXCHANGE_CONTENT = [\"XSHE\", \"XSHG\"]\n\n\n@export_as_api\ndef get_margin_stocks(date=None, exchange=None, margin_type='stock', market=\"cn\"):\n \"\"\"获取融资融券信息\n\n :param date: 查询日期,默认返回今天上一交易日,支持 str, timestamp, datetime 类型\n :param exchange: 交易所信息,默认不填写则返回全部。\n str类型,默认为 None,返回所有字段。可选字段包括:\n 'XSHE', 'sz' 代表深交所;'XSHG', 'sh' 代表上交所,不区分大小写\n (Default value = None)\n :param margin_type: 'stock' 代表融券卖出,'cash',代表融资买入,默认为'stock'\n\n \"\"\"\n if date:\n date = ensure_date_int(date)\n else:\n date = get_previous_trading_date(datetime.date.today())\n date = date.year * 10000 + date.month * 100 + date.day\n\n if exchange is None:\n exchange = EXCHANGE_CONTENT\n else:\n exchange = ensure_string(exchange, \"exchange\")\n if exchange in EXCHANGE_TYPE:\n exchange = EXCHANGE_TYPE[exchange]\n check_items_in_container(exchange, EXCHANGE_CONTENT, \"exchange\")\n exchange = [exchange]\n\n margin_type = ensure_string(margin_type, \"margin_type\")\n check_items_in_container(margin_type, MARGIN_TYPE, \"margin_type\")\n\n data = get_client().execute(\n \"get_margin_stocks\", date, exchange, margin_type, market=market\n )\n\n if not data:\n return []\n else:\n return sorted(data)\n\n\nshare_fields = {\n \"total\": \"total_shares\",\n \"circulation_a\": \"a_cir_shares\",\n \"non_circulation_a\": \"a_non_cir_shares\",\n \"total_a\": \"a_total_shares\",\n}\n\nanti_fields = {v: k for k, v in share_fields.items()}\n\n\n@export_as_api\n@compatible_with_parm(name=\"country\", value=\"cn\", replace=\"market\")\ndef get_shares(order_book_ids, start_date=None, end_date=None, fields=None, expect_df=False, market=\"cn\"):\n \"\"\"获取流通股本信息\n\n :param order_book_ids: 股票名称\n :param start_date: 开始日期, 如'2013-01-04' (Default value = None)\n :param end_date: 结束日期,如'2014-01-04' (Default value = None)\n :param fields: 如'total', 'circulation_a' (Default value = None)\n :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\n :param market: 地区代码,如'cn' (Default value = \"cn\")\n :returns: 返回一个DataFrame\n\n \"\"\"\n order_book_ids = ensure_order_book_ids(order_book_ids, market=market)\n start_date, end_date = ensure_date_range(start_date, end_date)\n\n if fields:\n fields = ensure_list_of_string(fields, \"fields\")\n if 'management_circulation' in fields:\n fields.remove('management_circulation')\n if fields:\n warnings.warn(\"management_circulation is removed\")\n else:\n raise ValueError(\"management_circulation is removed\")\n check_items_in_container(fields, set(share_fields), \"fields\")\n fields = [share_fields[i] for i in fields]\n else:\n fields = list(share_fields.values())\n \n all_shares = get_client().execute(\"get_shares\", order_book_ids, fields, market=market)\n if not all_shares:\n return\n dates = get_trading_dates_in_type(start_date, end_date, expect_type=\"datetime\", market=market)\n df = pd.DataFrame(all_shares)\n unique = set(df.order_book_id)\n for order_book_id in order_book_ids:\n if order_book_id not in unique:\n df = df.append(\n {\"order_book_id\": order_book_id, \"date\": df.date.iloc[-1]}, ignore_index=True\n )\n df.set_index([\"date\", \"order_book_id\"], inplace=True)\n df.sort_index(inplace=True)\n df = df.unstack(level=1)\n index = df.index.union(dates)\n df = df.reindex(index)\n df = df.fillna(method=\"ffill\")\n df = df.loc[list(dates)]\n df = df.dropna(how=\"all\")\n df = df[fields]\n if expect_df:\n df = df.stack(1)\n df.index.set_names([\"date\", \"order_book_id\"], inplace=True)\n df = df.reorder_levels([\"order_book_id\", \"date\"]).sort_index()\n df = df.rename(columns=anti_fields)\n return df\n\n pl = df.stack(1).to_panel()\n pl.items = [anti_fields[i] for i in pl.items]\n if len(order_book_ids) == 1:\n pl = pl.minor_xs(order_book_ids[0])\n if len(fields) == 1:\n pl = pl[anti_fields[fields[0]]]\n if len(order_book_ids) != 1 and len(fields) != 1:\n warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\n \" the default value of 'expect_df' will change to True in the future.\")\n return pl\n", "# -*- coding: utf-8 -*-\nimport datetime\nimport six\nimport warnings\nfrom itertools import islice\nfrom functools import reduce\n\nimport pandas as pd\nimport numpy as np\nfrom dateutil.relativedelta import relativedelta\nfrom sqlalchemy import Column\nfrom sqlalchemy.orm.query import Query\nfrom sqlalchemy.orm.attributes import InstrumentedAttribute\nfrom sqlalchemy.sql.elements import UnaryExpression\nfrom sqlalchemy.dialects import mysql\nfrom sqlalchemy.ext.declarative.api import DeclarativeMeta\nfrom pymysql.converters import conversions, escape_item, encoders\n\nfrom rqdatac.client import get_client\nfrom rqdatac.services.orm.balance_sheet_sql import StkBalaGen\nfrom rqdatac.services.orm.cash_flow_sql import StkCashGen\nfrom rqdatac.services.orm.financial_indicator_sql import AnaStkFinIdx\nfrom rqdatac.services.orm.fundamental_base_sql import FundamentalBase\nfrom rqdatac.services.orm.eod_derivative_indicator_sql import AnaStkValIdx\nfrom rqdatac.services.orm.income_statement_sql import StkIncomeGen\nfrom rqdatac.services.orm.ttm_sql import (\n CashFlowStatementTTM,\n IncomeStatementTTM,\n FinancialIndicatorTTM,\n)\nfrom rqdatac.services.orm.pit_financials import (\n BalanceSheet,\n CashFlowsStatement,\n IncomeStatement,\n MainData,\n TTM,\n PIT_TABLES,\n PIT_FIELDS,\n PIT_BASIC_FIELDS,\n PIT_BASIC_FIELDS_SET\n)\n\nfrom rqdatac.share.errors import MarketNotSupportError\nfrom rqdatac.services.calendar import get_previous_trading_date\nfrom rqdatac.utils import int8_to_date, to_date_int, to_datetime, iterable\nfrom rqdatac.validators import (\n ensure_list_of_string,\n ensure_string,\n check_items_in_container,\n ensure_date_int,\n ensure_order_book_id,\n)\nfrom rqdatac.decorators import export_as_api\n\ntry:\n from functools import lru_cache\nexcept ImportError:\n\n def lru_cache(*args, **kwargs):\n def decorator(f):\n return f\n\n return decorator\n\n\n@export_as_api(name=\"financials\")\n@export_as_api\nclass Financials:\n stockcode = FundamentalBase.stockcode\n announce_date = FundamentalBase.announce_date\n income_statement = StkIncomeGen\n balance_sheet = StkBalaGen\n cash_flow_statement = StkCashGen\n financial_indicator = AnaStkFinIdx\n cash_flow_statement_TTM = CashFlowStatementTTM\n income_statement_TTM = IncomeStatementTTM\n financial_indicator_TTM = FinancialIndicatorTTM\n\n\n@export_as_api\n@lru_cache(maxsize=3)\ndef get_financials(query, quarter, interval=None, expect_df=False, market=\"cn\"):\n \"\"\"获取季度报表数据\n\n :param query: SQLAlchemy Query对象\n :param quarter: 季度, 如: '2016q1'\n :param interval: 2y', '4q', 与 get_fundamentals 类似,但只接受 y(year) 和 q(quarter)\n (Default value = None)\n :param market: 市场 (Default value = \"cn\")\n :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\n :returns: 如果返回结果中股票代码和查询指标为单个值, 返回Series;\n 如果返回结果中股票代码或查询指标中有且只有一个为单个值, 返回pandas.DataFrame; 否则返回pandas.Panel\n\n \"\"\"\n\n sql, quarters = _parse_arguments(query, quarter, interval)\n records = get_client().execute(\"get_financial\", sql, market=market)\n return parse_results(records, quarters, expect_df)\n\n\ndef classify_fields(fields):\n if isinstance(fields, six.string_types) or fields in (\n BalanceSheet, CashFlowsStatement, IncomeStatement, TTM, MainData):\n fields = [fields]\n result = [\n # table_name fields\n ('balance_sheet_new', []),\n ('cash_flow_statement_new', []),\n ('income_statement_new', []),\n ('ttm_new', []),\n ('main_data', []),\n ]\n\n for f in fields:\n if f in PIT_BASIC_FIELDS_SET:\n continue\n elif f in PIT_FIELDS[0]:\n result[0][1].append(f)\n elif f in PIT_FIELDS[1]:\n result[1][1].append(f)\n elif f in PIT_FIELDS[2]:\n result[2][1].append(f)\n elif f in PIT_FIELDS[3]:\n result[3][1].append(f)\n elif f in PIT_FIELDS[4]:\n result[4][1].append(f)\n elif f in (BalanceSheet, CashFlowsStatement, IncomeStatement, TTM, MainData):\n index = PIT_TABLES.index(f.__name__)\n result[index][1].extend(PIT_FIELDS[index])\n else:\n raise ValueError('invalid field: {}'.format(f))\n return result\n\n\n@export_as_api(name=\"pit_financials\")\n@export_as_api\nclass PitFinancials:\n balance_sheet = BalanceSheet\n cash_flows_statement = CashFlowsStatement\n income_statement = IncomeStatement\n ttm = TTM\n main_data = MainData\n\n\nENTERPRISE_TYPE_MAP = {\n 13: \"business_bank\",\n 31: \"securities_firms\",\n 33: \"trust\",\n 35: \"insurance_company\",\n 39: \"other_financial_institution\",\n 99: \"general_enterprise\",\n}\n\nINFO_TYPE_MAP = {\n 10: \"发行上市书\",\n 20: \"定期报告\",\n 30: \"业绩快报\",\n 50: \"章程制度\",\n 70: \"临时公告\",\n 90: \"交易所通报\",\n 91: \"交易所临时停(复)牌公告\",\n 99: \"其他\"\n}\n\n\n@export_as_api\ndef get_pit_financials(fields, quarter, interval=None, order_book_ids=None,\n if_adjusted='all', max_info_date=None, market='cn'):\n \"\"\"\n 获取pit季度报表数据\n :param fields: 财务指标 or 财务指标 list\n :param quarter: 季度, 如: '2016q1'\n :param interval: '2y', '4q', 默认只返回当季\n :param order_book_ids: 股票列表, 默认为None返回所有股票数据\n :param if_adjusted: 是否调整\n 0: 每个order_book_id每个季度返回一条发布日期最新的未调整的数据\n 1: 每个order_book_id每个季度返回一条发布日期最新的调整的数据\n 'ignore': 每个order_book_id每个季度返回一条发布日期最新的数据\n 'all': 返回所有数据,无论发布日期新旧和是否调整\n :param max_info_date: 指定最大发布日期, 如20180430,则所取数据的发布日期均不大于20180430,默认为None\n :return: pandas.DataFrame or None\n \"\"\"\n\n if if_adjusted not in [0, 1, '0', '1', 'all', 'ignore']:\n raise ValueError(\"if_adjusted should in [0, 1, 'all', 'ignore']\")\n\n if order_book_ids is not None:\n order_book_ids = ensure_list_of_string(order_book_ids)\n quarters = get_quarters(quarter, interval)\n quarter_dates = [str(quarter_to_date(y, q)) for y, q in quarters]\n result = []\n for i, (table_name, fields) in enumerate(classify_fields(fields)):\n if not fields:\n continue\n\n if i == 3: # ttm, exclude ['info_type', 'is_complete', 'enterprise_type']\n extra_fields = PIT_BASIC_FIELDS[0:-3]\n elif i == 4: # main_data, exclude ['is_complete', 'enterprise_type']\n extra_fields = PIT_BASIC_FIELDS[0:-2]\n else:\n extra_fields = PIT_BASIC_FIELDS\n fields.extend(extra_fields)\n\n sql = \"\"\"SELECT {}\n FROM {}\n \"\"\".format(', '.join(fields), table_name)\n where = [\"end_date IN ('{}')\".format(\"', '\".join(quarter_dates))]\n if if_adjusted not in ['all', 'ignore']:\n where.append('if_adjusted {} 2'.format('=' if if_adjusted in (0, '0') else '<>'))\n if order_book_ids is not None:\n where.append(\"order_book_id IN ('{}')\".format(\"', '\".join(order_book_ids)))\n if max_info_date is not None:\n where.append(\"info_date <= '{}'\".format(max_info_date))\n\n sql += \"\"\"WHERE {}\"\"\".format(' AND '.join(where))\n records = get_client().execute(\"get_pit_financials\", sql, market=market)\n if records:\n df = pd.DataFrame(records)\n df['if_adjusted'] = df['if_adjusted'].apply(lambda x: 0 if x == 2 else 1)\n df['accounting_standards'] = df['accounting_standards'].apply(lambda x: 1 if x == 1 else 0)\n\n if i not in (3, 4):\n df['if_complete'] = df['if_complete'].apply(lambda x: 1 if x == 1 else 0)\n\n if if_adjusted != 'all':\n if if_adjusted == 'ignore':\n subset = ['order_book_id', 'end_date']\n else:\n subset = ['order_book_id', 'end_date', 'if_adjusted']\n df.sort_values('info_date', inplace=True)\n df.drop_duplicates(subset=subset, keep='last', inplace=True)\n df.fillna(np.inf, inplace=True)\n result.append(df)\n if not result:\n return\n if len(result) == 1:\n result = result[0]\n elif len(result) > 1:\n result = reduce(\n lambda left, right: pd.merge(\n left, right, how='outer', on=[f for f in left.columns if f in right.columns]\n ), result)\n\n result.sort_values(by=['order_book_id', 'end_date', 'info_date'], inplace=True)\n result.set_index(['order_book_id', 'end_date'], inplace=True)\n\n base_columns = ['info_date', 'if_adjusted', 'accounting_standards']\n if 'if_complete' in result.columns:\n result.rename(columns={'if_complete': 'is_complete'}, inplace=True)\n result['enterprise_type'] = result['enterprise_type'].map(ENTERPRISE_TYPE_MAP)\n base_columns.extend(['is_complete', 'enterprise_type'])\n if 'info_type' in result.columns:\n result['info_type'] = result['info_type'].map(INFO_TYPE_MAP)\n base_columns.extend(['info_type'])\n\n return result[base_columns + [c for c in result.columns if c not in base_columns]]\n\n\n@export_as_api\n@lru_cache(maxsize=3)\ndef get_fundamentals(query, entry_date, interval=None, report_quarter=False, expect_df=False, market=\"cn\"):\n \"\"\"获取财务数据\n\n :param query: query 对象\n :param entry_date: 日期\n :param interval: (Default value = None)\n :param report_quarter: (Default value = False)\n :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\n :param market: (Default value = \"cn\")\n\n \"\"\"\n if market != \"cn\":\n raise MarketNotSupportError(\"don't support market {} yet.\", market)\n\n if not isinstance(query, Query):\n raise ValueError(\"a sqlalchemy's Query object expected: {}\".format(type(query)))\n\n entry_date = to_datetime(entry_date)\n\n delta = 0\n duration = 0\n if interval is not None:\n if not isinstance(interval, str):\n raise ValueError(\n \"invalid interval: {} should be a string like 1d, 5y, 3m, 2q\".format(interval)\n )\n if interval[-1] not in __TIME_DELTA_MAP__:\n raise ValueError(\n \"invalid interval: {}, interval unit should be d(day), \"\n \"m(month), q(quarter) or y(year)\".format(interval)\n )\n delta = __TIME_DELTA_MAP__[interval[-1]]\n\n try:\n duration = int(interval[:-1])\n except ValueError:\n raise ValueError(\n \"invalid interval: {}, should be a string like 1d, 5y, 3m, 2q\".format(interval)\n )\n\n trading_dates = [get_previous_trading_date(entry_date + __TIME_DELTA_MAP__[\"d\"], market=market)]\n if duration > 0:\n current_date = trading_dates[0]\n one_day = __TIME_DELTA_MAP__[\"d\"]\n for i in range(duration - 1):\n current_date = get_previous_trading_date(current_date - delta + one_day, market=market)\n trading_dates.append(current_date)\n\n query = _unsafe_apply_query_filter(query, trading_dates)\n sql = _compile_query(query)\n records = get_client().execute(\"get_fundamentals\", sql, market=market)\n\n if not records:\n warnings.warn(\"No record found\")\n return None\n\n base_fields = [\"STOCKCODE\", \"TRADEDATE\", \"RPT_YEAR\", \"RPT_QUARTER\"]\n field_names = base_fields + list(set(records[0].keys()) - set(base_fields))\n items = [\"report_quarter\"] + field_names[4:] if report_quarter else field_names[4:]\n\n if expect_df:\n df = pd.DataFrame(records)\n df.rename(columns={\"STOCKCODE\": \"order_book_id\", \"TRADEDATE\": \"date\"}, inplace=True)\n df[\"report_quarter\"] = df[\"RPT_YEAR\"].map(str) + \"q\" + df[\"RPT_QUARTER\"].map(str)\n df.sort_values([\"order_book_id\", \"date\"], ascending=[True, False], inplace=True)\n df.set_index([\"order_book_id\", \"date\"], inplace=True)\n for item in items:\n if item != \"report_quarter\":\n df[item] = df[item].astype(np.float64)\n return df[items]\n\n # 只有一个查询日期时, 保持顺序\n if len(trading_dates) > 1:\n stocks = list(set([r[field_names[0]] for r in records]))\n else:\n stocks = [r[field_names[0]] for r in records]\n\n stock_index = {s: i for i, s in enumerate(stocks)}\n day_index = {d: i for i, d in enumerate(trading_dates)}\n\n removed_items_size = 3 if report_quarter else 4\n\n array = np.ndarray(\n ((len(records[0]) - removed_items_size), len(trading_dates), len(stocks)), dtype=object\n )\n array.fill(np.nan)\n for r in records:\n istock = stock_index[r[field_names[0]]]\n iday = day_index[int8_to_date(r[field_names[1]])]\n for i in range(4, len(r)):\n array[(i - removed_items_size, iday, istock)] = np.float64(r[field_names[i]])\n if report_quarter:\n array[(0, iday, istock)] = (\n np.nan\n if None in (r[field_names[2]], r[field_names[3]])\n else str(r[field_names[2]]) + \"q\" + str(r[field_names[3]])\n )\n\n trading_dates = pd.to_datetime(trading_dates)\n\n warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\n \"the default value of 'expect_df' will change to True in the future.\")\n return pd.Panel(data=array, items=items, major_axis=trading_dates, minor_axis=stocks)\n\n\ndeprecated_fields = {\"data_point\": \"data_point\", \"table\": \"table\", \"comment\": \"comment\"}\n\n\n@export_as_api\ndef deprecated_fundamental_data(fields=None, market=\"cn\"):\n fields = _check_deprecated_fields(fields)\n df = pd.DataFrame(get_client().execute(\"deprecated_fundamental_data\", fields, market=market))\n\n if len(df) < 1:\n return None\n if len(fields) == 1:\n df = list(df[fields[0]])\n return df\n\n\n@export_as_api\ndef current_performance(\n order_book_id, info_date=None, quarter=None, interval=\"1q\", fields=None, market=\"cn\"\n):\n \"\"\"获取A股快报\n\n :param order_book_id: 股票代码, 如'000001.XSHE'\n :param info_date: 发布日期, 如'20180501', 默认为最近的交易日 (Default value = None)\n :param quarter: 发布季度, 如'2018q1' (Default value = None)\n :param interval: 数据区间, 发布日期, 如'2y', '4q' (Default value = \"1q\")\n :param fields: str 或 list 类型. 默认为 None, 返回所有字段 (Default value = None)\n :param market: 地区代码, 如'cn' (Default value = \"cn\")\n :returns: pd.DataFrame\n\n \"\"\"\n order_book_id = ensure_order_book_id(order_book_id, market=market)\n end_date = None\n if info_date:\n info_date = ensure_date_int(info_date)\n elif quarter:\n splited = quarter.lower().split(\"q\")\n if len(quarter) != 6 or len(splited) != 2:\n raise ValueError(\n \"invalid argument {}: {}, valid parameter: {}\".format(\n \"quarter\", quarter, \"string format like '2016q1'\"\n )\n )\n\n year, quarter = int(splited[0]), int(splited[1])\n if not 1 <= quarter <= 4:\n raise ValueError(\n \"invalid argument {}: {}, valid parameter: {}\".format(\n \"quarter\", quarter, \"quarter should be in [1, 4]\"\n )\n )\n month, day = QUARTER_DATE_MAP[quarter]\n end_date = ensure_date_int(datetime.datetime(year, month, day))\n else:\n info_date = ensure_date_int(datetime.date.today())\n ensure_string(interval, \"interval\")\n if interval[-1] not in (\"y\", \"q\", \"Y\", \"Q\"):\n raise ValueError(\n \"invalid argument {}: {}, valid parameter: {}\".format(\n \"interval\", interval, \"interval unit should be q(quarter) or y(year)\"\n )\n )\n\n try:\n int(interval[:-1])\n except ValueError:\n raise ValueError(\n \"invalid argument {}: {}, valid parameter: {}\".format(\n \"interval\", interval, \"string like 4q, 2y\"\n )\n )\n interval = interval.lower()\n\n if fields is not None:\n fields = ensure_list_of_string(fields, \"fields\")\n check_items_in_container(fields, PERFORMANCE_FIELDS, \"fields\")\n else:\n fields = PERFORMANCE_FIELDS\n\n data = get_client().execute(\n \"current_performance\", order_book_id, info_date, end_date, fields, market=market\n )\n if not data:\n return\n df = pd.DataFrame(data)\n sort_field = \"info_date\" if info_date else \"end_date\"\n df.sort_values(by=[sort_field, \"mark\"], ascending=[False, True], inplace=True)\n df.drop_duplicates(subset=\"end_date\", keep=\"first\", inplace=True)\n num = int(interval[:-1])\n unit = interval[-1]\n if unit == \"y\":\n latest_month = df.loc[0, \"end_date\"].month\n df[\"month\"] = df.end_date.apply(lambda x: x.month)\n df = df[df.month == latest_month]\n df.reset_index(drop=True, inplace=True)\n return df.loc[: num - 1, [\"end_date\", \"info_date\"] + fields]\n\n\nPERFORMANCE_FORECAST_FIELDS = [\n \"forecast_type\",\n \"forecast_description\",\n \"forecast_growth_rate_floor\",\n \"forecast_growth_rate_ceiling\",\n \"forecast_earning_floor\",\n \"forecast_earning_ceiling\",\n \"forecast_np_floor\",\n \"forecast_np_ceiling\",\n \"forecast_eps_floor\",\n \"forecast_eps_ceiling\",\n \"net_profit_yoy_const_forecast\",\n]\n\n\n@export_as_api\ndef performance_forecast(order_book_id, info_date=None, end_date=None, fields=None, market=\"cn\"):\n \"\"\"获取业绩预报\n\n :param order_book_id: 股票代码,如'000001.XSHE'\n :param info_date: 信息发布日期,如'20180501',默认为最近的交易日 (Default value = None)\n :param end_date: 业绩预计报告期,如'20180501',默认为最近的交易日 (Default value = None)\n :param fields: str或list类型. 默认为None,返回所有字段 (Default value = None)\n :param market: (Default value = \"cn\")\n :returns: pd.DataFrame\n\n \"\"\"\n order_book_id = ensure_order_book_id(order_book_id)\n\n if info_date:\n info_date = ensure_date_int(info_date)\n elif end_date:\n end_date = ensure_date_int(end_date)\n else:\n info_date = ensure_date_int(datetime.datetime.today())\n\n if fields:\n fields = ensure_list_of_string(fields, \"fields\")\n check_items_in_container(fields, PERFORMANCE_FORECAST_FIELDS, \"fields\")\n else:\n fields = PERFORMANCE_FORECAST_FIELDS\n\n data = get_client().execute(\n \"performance_forecast\", order_book_id, info_date, end_date, fields, market=market\n )\n if not data:\n return\n df = pd.DataFrame(data)[[\"info_date\", \"end_date\"] + fields]\n return df\n\n\ndef _check_deprecated_fields(fields):\n try:\n if fields is None:\n fields = list(deprecated_fields.values())\n elif isinstance(fields, str):\n fields = [deprecated_fields[fields]]\n elif isinstance(fields, list):\n fields = [deprecated_fields[i] for i in fields]\n else:\n raise ValueError(\"fields should be string or list of strings\")\n except KeyError:\n raise ValueError(\n \"invalid argument fields: {!r}, valid parameter: {!r}\".format(\n fields, list(deprecated_fields)\n )\n )\n return fields\n\n\nPERFORMANCE_FIELDS = [\n \"operating_revenue\",\n \"gross_profit\",\n \"operating_profit\",\n \"total_profit\",\n \"np_parent_owners\",\n \"net_profit_cut\",\n \"net_operate_cashflow\",\n \"total_assets\",\n \"se_without_minority\",\n \"total_shares\",\n \"basic_eps\",\n \"eps_weighted\",\n \"eps_cut_epscut\",\n \"eps_cut_weighted\",\n \"roe\",\n \"roe_weighted\",\n \"roe_cut\",\n \"roe_cut_weighted\",\n \"net_operate_cashflow_per_share\",\n \"equity_per_share\",\n \"operating_revenue_yoy\",\n \"gross_profit_yoy\",\n \"operating_profit_yoy\",\n \"total_profit_yoy\",\n \"np_parent_minority_pany_yoy\",\n \"ne_t_minority_ty_yoy\",\n \"net_operate_cash_flow_yoy\",\n \"total_assets_to_opening\",\n \"se_without_minority_to_opening\",\n \"basic_eps_yoy\",\n \"eps_weighted_yoy\",\n \"eps_cut_yoy\",\n \"eps_cut_weighted_yoy\",\n \"roe_yoy\",\n \"roe_weighted_yoy\",\n \"roe_cut_yoy\",\n \"roe_cut_weighted_yoy\",\n \"net_operate_cash_flow_per_share_yoy\",\n \"net_asset_psto_opening\",\n]\n\nQUARTER_DATE_MAP = {1: (3, 31), 2: (6, 30), 3: (9, 30), 4: (12, 31)}\n\n__TIME_DELTA_MAP__ = {\n \"y\": relativedelta(years=1),\n \"m\": relativedelta(months=1),\n \"q\": relativedelta(months=3),\n \"d\": relativedelta(days=1),\n}\n\n\n@export_as_api(name=\"fundamentals\")\n@export_as_api\nclass Fundamentals:\n stockcode = FundamentalBase.stockcode\n announce_date = FundamentalBase.announce_date\n income_statement = StkIncomeGen\n balance_sheet = StkBalaGen\n cash_flow = StkCashGen\n cash_flow_statement = StkCashGen\n financial_indicator = AnaStkFinIdx\n eod_derivative_indicator = AnaStkValIdx\n fundamental_base = FundamentalBase\n cash_flow_statement_TTM = CashFlowStatementTTM\n income_statement_TTM = IncomeStatementTTM\n financial_indicator_TTM = FinancialIndicatorTTM\n\n\n@export_as_api(name=\"query\")\ndef query_entities(*entities):\n base_list = [\"stockcode\", \"tradedate\", \"end_date\", \"announce_date\", \"rpt_year\", \"rpt_quarter\"]\n columns = [\n Fundamentals.fundamental_base.stockcode,\n Fundamentals.fundamental_base.tradedate,\n Fundamentals.fundamental_base.rpt_year,\n Fundamentals.fundamental_base.rpt_quarter,\n ]\n for ele in entities:\n if isinstance(ele, DeclarativeMeta):\n deprecated_list = deprecated_fundamental_data(\"data_point\")\n query_list = [\n v\n for k, v in ele.__dict__.items()\n if not k.startswith(\"_\") and k not in base_list and k not in deprecated_list\n ]\n columns.extend(query_list)\n elif isinstance(ele, InstrumentedAttribute):\n name = str(ele).split(\".\")[-1]\n if name in [\"stockcode\", \"tradedate\", \"rpt_year\", \"rpt_quarter\"]:\n continue\n columns.append(ele)\n else:\n raise ValueError(\n \"Invalid metrics to query, it maybe not specify metrics, \"\n \"please check the metrics in query.\"\n )\n\n return Query(columns)\n\n\ndef _compile_query(query):\n comp = query.statement.compile(dialect=mysql.dialect())\n comp_params = comp.params\n params = []\n for k in comp.positiontup:\n v = comp_params[k]\n params.append(escape_item(v, conversions, encoders))\n\n comp = comp.string\n if \"equity_preferred_stock\" in comp:\n if \"equity_prefer_stock\" in comp:\n comp = comp.replace(\"fundamental_view.equity_prefer_stock,\", \"\")\n comp = comp.replace(\"equity_preferred_stock\", \"equity_prefer_stock as equity_preferred_stock\")\n elif \"equity_prefer_stock\" in comp:\n warnings.warn(\"'equity_prefer_stock' has been deprecated, please use 'equity_preferred_stock'.\")\n\n return comp % tuple(params)\n\n\ndef _unsafe_apply_query_filter(query, trading_dates):\n # TODO this is a hack\n limit, offset = query._limit, query._offset\n query = query.limit(None).offset(None)\n\n if query._order_by:\n # 对于存在order_by的, 过滤掉 NaN\n def _filter(q, column):\n if isinstance(column, Column):\n return q.filter(column is not None)\n if isinstance(column, UnaryExpression):\n return _filter(q, column.element)\n return q\n\n for creterion in query._order_by:\n query = _filter(query, creterion)\n\n query = query.filter(FundamentalBase.tradedate.in_([to_date_int(d) for d in trading_dates]))\n\n if len(trading_dates) > 1:\n query = query.order_by(FundamentalBase.tradedate.desc())\n return query.limit(limit).offset(offset)\n\n\ndef _parse_arguments(query, quarter, interval):\n if not isinstance(query, Query):\n raise ValueError(\n \"The first argument must be a sqlalchemy's Query object. \"\n \"But what passed in was: \" + str(type(query))\n )\n quarters = get_quarters(quarter, interval)\n quarter_dates = [quarter_to_date(y, q) for y, q in quarters]\n query = adjust_query(query, quarter_dates)\n return _compile_query(query), quarters\n\n\ndef quarter_generator(year, quarter):\n while True:\n yield year, quarter\n quarter -= 1\n if quarter == 0:\n quarter = 4\n year -= 1\n\n\ndef year_generator(year, quarter):\n while True:\n yield year, quarter\n year -= 1\n\n\ndef quarter_to_date(year, quarter):\n dates = (331, 630, 930, 1231)\n return year * 10000 + dates[quarter - 1]\n\n\ndef get_quarters(quarter, interval):\n if quarter is None:\n raise ValueError(\"quarter is required.\")\n\n splited = quarter.lower().split(\"q\")\n if len(splited) != 2:\n raise ValueError(\"wrong quarter format, use format like '2016q1'\")\n\n year, quarter = int(splited[0]), int(splited[1])\n if not 1 <= quarter <= 4:\n raise ValueError(\"quarter should be in [1, 4]\")\n\n if interval is not None:\n if not isinstance(interval, str):\n raise ValueError(\"interval should be a string like 4q, 2y\")\n\n if interval[-1] not in (\"y\", \"q\", \"Y\", \"Q\"):\n raise ValueError(\"interval unit should be y(year) or q(quarter)\")\n try:\n int(interval[:-1])\n except ValueError:\n raise ValueError(\"interval should be a string like 4q, 2y\")\n if interval is not None:\n generator = (quarter_generator if interval[-1].lower() == \"q\" else year_generator)(\n year, quarter\n )\n n = int(interval[:-1])\n return list(islice(generator, n))\n else:\n return [(year, quarter)]\n\n\ndef adjust_query(query, quarter_dates):\n # hack\n if str(query._entities[1]).split(\".\")[-1] == \"tradedate\":\n query._entities.pop(1) # remove tradedate entity\n limit, offset = query._limit, query._offset\n query.limit(None).offset(None)\n\n query = query.filter(FundamentalBase.end_date.in_(quarter_dates))\n\n if len(quarter_dates) > 1:\n query = query.order_by(FundamentalBase.end_date.desc())\n return query.limit(limit).offset(offset)\n\n\ndef parse_results(records, quarters, expect_df):\n if not records:\n return None\n\n removed_items_size = 3\n base_fields = [\"stockcode\", \"rpt_year\", \"rpt_quarter\"]\n\n field_names = base_fields + list(set(records[0].keys()) - set(base_fields))\n items = field_names[removed_items_size:]\n\n if expect_df:\n df = pd.DataFrame(records)\n df.rename(columns={\"stockcode\": \"order_book_id\"}, inplace=True)\n df[\"quarter\"] = df[\"rpt_year\"].map(str) + \"q\" + df[\"rpt_quarter\"].map(str)\n df.sort_values([\"order_book_id\", \"quarter\"], ascending=[True, False], inplace=True)\n df.set_index([\"order_book_id\", \"quarter\"], inplace=True)\n for item in items:\n if item != \"announce_date\":\n df[item] = df[item].astype(np.float64)\n return df[items]\n\n # 只有一个查询日期时, 保持顺序\n stocks = list(set(r[field_names[0]] for r in records))\n stock_index = {s: i for i, s in enumerate(stocks)}\n quarter_index = {q: i for i, q in enumerate(quarters)}\n\n array = np.ndarray(\n (len(records[0]) - removed_items_size, len(quarters), len(stocks)), dtype=object\n )\n array.fill(np.nan)\n for r in records:\n istock = stock_index[r[field_names[0]]]\n iquarter = quarter_index[(r[field_names[1]], r[field_names[2]])]\n for i in range(removed_items_size, len(r)):\n if field_names[i] == \"announce_date\":\n announce_date = r[field_names[i]]\n array[i - removed_items_size, iquarter, istock] = (\n np.nan if announce_date is None else announce_date\n )\n else:\n array[i - removed_items_size, iquarter, istock] = np.float64(r[field_names[i]])\n\n s_quarters = [\"%dq%d\" % (year, quarter) for year, quarter in quarters]\n results = pd.Panel(data=array, items=items, major_axis=s_quarters, minor_axis=stocks)\n item_size, major_size, minor_size = results.shape\n if minor_size == 1:\n ret = results.minor_xs(*stocks)\n return ret[field_names[removed_items_size]] if item_size == 1 else ret\n elif item_size == 1:\n return results[field_names[removed_items_size]]\n elif major_size == 1:\n return results.major_xs(*s_quarters)\n else:\n warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\n \" the default value of 'expect_df' will change to True in the future.\")\n return results\n", "# -*- coding: utf-8 -*-\nfrom decimal import Decimal, DecimalTuple\n\n\nimport pandas as pd\n\nfrom rqdatac.client import get_client\nfrom rqdatac.decorators import export_as_api\nfrom rqdatac.validators import ensure_list_of_string\n\n_SIGN = \"sign\"\n_DIGITS = \"digits\"\n_EXPONENT = \"exponent\"\n\n\ndef _encode_decimal(num, prefix):\n decimal_tuple = Decimal(str(num)).normalize().as_tuple()\n prefix += \".\"\n encoded_decimal = {\n prefix + _SIGN: decimal_tuple.sign,\n prefix + _DIGITS: decimal_tuple.digits,\n prefix + _EXPONENT: decimal_tuple.exponent,\n }\n return encoded_decimal\n\n\ndef _decode_decimal(encoded_decimal):\n sign = encoded_decimal[_SIGN]\n digits = tuple(encoded_decimal[_DIGITS])\n exponent = encoded_decimal[_EXPONENT]\n return Decimal(DecimalTuple(sign=sign, digits=digits, exponent=exponent))\n\n\ndef _remake_decimal(dlist):\n for one in dlist:\n for key, value in one.items():\n if isinstance(value, dict) and value.get(_DIGITS):\n one[key] = _decode_decimal(value)\n\n\n@export_as_api(namespace=\"fenji\")\ndef get_a_by_yield(current_yield, listing=True, market=\"cn\"):\n if listing is not None:\n listing = bool(listing)\n\n data = get_client().execute(\"fenji.get_a_by_yield\", current_yield, listing, market)\n return data\n\n\n@export_as_api(namespace=\"fenji\")\ndef get_a_by_interest_rule(interest_rule, listing=True, market=\"cn\"):\n if listing is not None:\n listing = bool(listing)\n data = get_client().execute(\"fenji.get_a_by_interest_rule\", interest_rule, listing, market)\n return data\n\n\n@export_as_api(namespace=\"fenji\")\ndef get_all(field_list=None, market=\"cn\"):\n data = get_client().execute(\"fenji.get_all\", field_list, market)\n _remake_decimal(data)\n df = pd.DataFrame(data)\n df.reindex(columns=sorted(df.columns))\n return df\n\n\n@export_as_api(namespace=\"fenji\")\ndef get(order_book_ids, field_list=None, market=\"cn\"):\n order_book_ids = ensure_list_of_string(order_book_ids, \"order_book_ids\")\n data = get_client().execute(\"fenji.get\", order_book_ids, field_list, market)\n if not data:\n return\n _remake_decimal(data)\n df = pd.DataFrame(data)\n df.reindex(columns=sorted(df.columns))\n return df\n", "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn\nimport math\nfrom sklearn import metrics\nfrom collections import Iterable\nfrom sklearn.cluster import KMeans\nfrom scipy import optimize as sco\nimport datetime as dt\nimport vnpy.analyze.data.data_prepare as dp\n\ntry:\n from data_provider.nestlib.progress_bar import ProgressBar\n\n is_online = True\n\n\n def progress_map(func, iterator):\n bar = ProgressBar(max_value=len(iterator))\n bar.start()\n wrapped_iterator = map(func, iterator)\n results = []\n for i, _ in enumerate(wrapped_iterator):\n results.append(_)\n bar.update(i + 1)\n return results\n\nexcept ImportError:\n is_online = False\n from tqdm import tqdm\n\n\n def progress_map(func, iterator, desc=None):\n with tqdm(iterator, desc=desc, ncols=100) as bar:\n results = []\n for i in bar:\n bar.set_postfix_str(str(i))\n results.append(func(i))\n return results\n\n\nclass StraightLine():\n def __init__(self, x1=None, y1=None, x2=None, y2=None, slope=None):\n\n if slope is not None:\n self.slope = slope\n else:\n if x1 == x2:\n self.slope = np.nan\n else:\n self.slope = (y2 - y1) / (x2 - x1)\n self.intercept = y1 - self.slope * x1\n\n def point_distance(self, x0, y0):\n return abs(self.slope * x0 - y0 + self.intercept) / math.sqrt(self.slope ** 2 + 1)\n\n def is_point_above_line(self, x0, y0):\n pred_y = x0 * self.slope + self.intercept\n if pred_y == y0:\n print('直线 y = {self.slope}x + {self.intercept} 穿过点({x0}, {y0})')\n import ipdb;\n ipdb.set_trace()\n return y0 > pred_y\n\n def predict(self, x_list, limit=None):\n if not isinstance(x_list, Iterable):\n x_list = [x_list]\n results = [self.slope * _ + self.intercept for _ in x_list]\n if len(results) == 1:\n return results[0]\n if limit is not None:\n results = [\n _ if _ > min(limit) and _ < max(limit) else np.nan\n for _ in results\n ]\n return results\n\n\ndef clustering_kmeans(num_list, thresh=0.03):\n # 阻力位或者支撑位序列从1-序列个数开始聚类\n k_rng = range(1, len(num_list) + 1)\n est_arr = [\n KMeans(n_clusters=k).fit([[num] for num in num_list])\n for k in k_rng\n ]\n\n # 各个分类器的距离和\n sum_squares = [e.inertia_ for e in est_arr]\n\n # 相对于1个类的分类器的距离和的比例\n diff_squares = [squares / sum_squares[0] for squares in sum_squares]\n diff_squares_pd = pd.Series(diff_squares)\n\n # 根据阈值设置选择分类器\n thresh_pd = diff_squares_pd[diff_squares_pd < thresh]\n\n if len(thresh_pd) > 0:\n select_k = thresh_pd.index[0] + 1\n else:\n # 没有符合的,就用最多的分类器\n select_k = k_rng[-1]\n\n est = est_arr[select_k - 1]\n results = est.predict([[num] for num in num_list])\n\n return results\n\n\nclass SupportResistanceLine():\n def __init__(self, data, kind='support'):\n if not isinstance(data, pd.Series):\n raise TypeError('data必须为pd.Series格式')\n\n self.y = data.copy()\n self.x = np.arange(0, len(data))\n df = pd.DataFrame(columns=['x', 'y'])\n df.x = self.x\n df.y = self.y\n df.set_index(['x'], inplace=True)\n df.index.name = None # 去掉索引列名\n self.df = df\n self.kind = kind\n self.dot_color = 'g' if kind == 'support' else 'r'\n\n def find_best_poly(self, poly_min=1, poly_max=100, show=False):\n \"\"\"\n 寻找最佳拟合次数\n :param poly_min: 最小拟合次数\n :param poly_max: 最大拟合次数\n :param show: 是否展示\n :return:\n \"\"\"\n df = self.df\n rolling_window = int(len(self.y) / 30)\n df['y_roll_mean'] = df['y'].rolling(rolling_window, min_periods=1).mean()\n\n # 度量原始y值和均线y_roll_mean的距离distance_mean\n distance_mean = np.sqrt(metrics.mean_squared_error(df.y, df.y_roll_mean))\n\n poly = poly_min\n while poly < poly_max:\n # 迭代计算1-100poly次regress_xy_polynomial的拟合曲线y_fit\n p = np.polynomial.Chebyshev.fit(self.x, self.y, poly)\n y_fit = p(self.x)\n distance_fit = np.sqrt(metrics.mean_squared_error(df.y, y_fit))\n # 使用metrics_func方法度量原始y值和拟合回归的趋势曲线y_fit的距离distance_fit\n if distance_fit <= distance_mean * 0.6:\n # 如果distance_fit <= distance_mean* 0.6即代表拟合曲线可以比较完美的代表原始曲线y的走势,停止迭代\n df[f'poly_{poly}'] = y_fit\n break\n poly += 1\n self.best_poly = poly\n self.p = p\n self.df['best_poly'] = y_fit\n if show:\n fig, ax = plt.subplots(1, figsize=(16, 9))\n df.plot(ax=ax, figsize=(16, 9), colormap='coolwarm')\n plt.show()\n\n def find_extreme_pos(self, show=False):\n \"\"\"寻找极值点\"\"\"\n p = self.p\n\n # 求导函数的根\n extreme_pos = [int(round(_.real)) for _ in p.deriv().roots()]\n extreme_pos = [_ for _ in extreme_pos if _ > 0 and _ < len(self.df)]\n\n # 通过二阶导数分拣极大值和极小值\n second_deriv = p.deriv(2)\n min_extreme_pos = []\n max_extreme_pos = []\n for pos in extreme_pos:\n if second_deriv(pos) > 0:\n min_extreme_pos.append(pos)\n elif second_deriv(pos) < 0:\n max_extreme_pos.append(pos)\n\n self.min_extreme_pos = min_extreme_pos\n self.max_extreme_pos = max_extreme_pos\n\n if show:\n fig, ax = plt.subplots(1, figsize=(16, 9))\n self.df.plot(ax=ax)\n ax.scatter(self.min_extreme_pos, [p(_) for _ in self.min_extreme_pos], s=50, c='g')\n ax.scatter(self.max_extreme_pos, [p(_) for _ in self.max_extreme_pos], s=50, c='r')\n plt.show()\n\n # 拟合极值点附近的真实极值\n def find_real_extreme_points(self, show=False):\n\n # 寻找一个支撑点两边最近的压力点,或反之\n def find_left_and_right_pos(pos, refer_pos):\n refer_sr = pd.Series(refer_pos)\n left_pos = refer_sr[refer_sr < pos].iloc[-1] if len(refer_sr[refer_sr < pos]) > 0 else 0\n right_pos = refer_sr[refer_sr > pos].iloc[0] if len(refer_sr[refer_sr > pos]) > 0 else len(self.df)\n return left_pos, right_pos\n\n # 寻找一个拟合极值点附近的真实极值\n def extreme_around(left_pos, right_pos):\n\n if self.kind == 'support':\n extreme_around_pos = self.y.iloc[left_pos:right_pos].idxmin()\n elif self.kind == 'resistance':\n extreme_around_pos = self.y.iloc[left_pos:right_pos].idxmax()\n\n # 如果附近的小值在边缘上,该点附近区间单调性较强,属于假极值,抛弃\n if extreme_around_pos in (left_pos, right_pos):\n return 0\n\n return extreme_around_pos\n\n extreme_pos = self.min_extreme_pos\n refer_pos = self.max_extreme_pos\n if self.kind == 'resistance':\n extreme_pos, refer_pos = refer_pos, extreme_pos\n\n support_resistance_pos = []\n for index, pos in enumerate(extreme_pos):\n if pos in [0, len(self.df)]:\n continue\n\n left_pos, right_pos = find_left_and_right_pos(pos, refer_pos)\n\n support_resistance_pos.append(\n extreme_around(left_pos, right_pos)\n )\n\n if 0 in support_resistance_pos:\n support_resistance_pos.remove(0)\n\n # 去重\n support_resistance_pos = list(set(support_resistance_pos))\n\n support_resistance_sr = pd.Series(\n self.df.y.loc[support_resistance_pos],\n index=support_resistance_pos\n ).sort_index()\n\n support_resistance_sr.index.name = 'x'\n support_resistance_df = support_resistance_sr.reset_index()\n\n self.support_resistance_df = support_resistance_df\n\n if show:\n self.show_line(support_resistance_df)\n\n return self.support_resistance_df\n\n def cluster_nearest_support_resistance_pos(self, show=False, inplace=True):\n\n def clustering_nearest(num_list, thresh=len(self.df) / 80):\n sr = pd.Series(num_list).sort_values().reset_index(drop=True)\n while sr.diff().min() < thresh:\n index1 = sr.diff().idxmin()\n index2 = index1 - 1\n num1 = sr[index1]\n num2 = sr[index2]\n y1 = self.df['y'].iloc[num1]\n y2 = self.df['y'].iloc[num2]\n\n smaller_y_index = index1 if y1 < y2 else index2\n bigger_y_index = index1 if y1 > y2 else index2\n sr = sr.drop(bigger_y_index if self.kind == 'support' else smaller_y_index).reset_index(drop=True)\n return sr.tolist()\n\n clustered_pos = clustering_nearest(self.support_resistance_df['x'].tolist())\n\n support_resistance_df = self.support_resistance_df[self.support_resistance_df['x'].isin(clustered_pos)].copy()\n\n if show:\n self.show_line(support_resistance_df)\n\n if inplace:\n self.support_resistance_df = support_resistance_df\n\n return support_resistance_df\n\n def cluster_kmeans_support_resistance_pos(self, show=False, inplace=True):\n # 聚类\n\n support_resistance_df = self.support_resistance_df.copy()\n support_resistance_df['cluster'] = clustering_kmeans(support_resistance_df.x, 0.001)\n print(\n f\"共{len(support_resistance_df)}个极值点,聚类为{support_resistance_df['cluster'].max() + 1}个类\"\n )\n\n def extreme_in_cluster(cluster_df):\n if self.kind == 'support':\n cluster_df['is_extreme'] = cluster_df['y'] == cluster_df['y'].min()\n else:\n cluster_df['is_extreme'] = cluster_df['y'] == cluster_df['y'].max()\n return cluster_df\n\n # 只保留每个类的最小值\n support_resistance_df = support_resistance_df.groupby('cluster').apply(extreme_in_cluster)\n support_resistance_df = support_resistance_df[support_resistance_df['is_extreme']].drop('is_extreme', axis=1)\n\n if show:\n self.show_line(support_resistance_df)\n\n if inplace:\n self.support_resistance_df = support_resistance_df\n\n return support_resistance_df\n\n def score_lines_from_a_point(self, last_support_resistance_pos):\n\n # 只考虑该点之前的点\n support_resistance_df = self.support_resistance_df[\n (self.support_resistance_df['x'] <= last_support_resistance_pos['x'])\n # & (self.support_resistance_df['x'] >= len(self.df) * 0.25)\n ].copy()\n\n if len(support_resistance_df) <= 2:\n return pd.DataFrame()\n\n # 计算经过各个点的斜率\n support_resistance_df['slope'] = support_resistance_df.apply(\n lambda _: StraightLine(_['x'], _['y'], last_support_resistance_pos['x'],\n last_support_resistance_pos['y']).slope,\n axis=1\n )\n\n # 根据斜率给所有线排序\n if self.kind == 'support':\n support_resistance_df = support_resistance_df.dropna().sort_values('slope')\n elif self.kind == 'resistance':\n support_resistance_df = support_resistance_df.dropna().sort_values('slope', ascending=False)\n\n # 过滤掉斜率过大的线\n support_resistance_df = support_resistance_df[support_resistance_df['slope'].abs() / self.y.mean() < 0.003]\n if len(support_resistance_df) <= 2:\n return pd.DataFrame()\n\n # 聚类\n thresh = 0.03\n support_resistance_df['cluster'] = clustering_kmeans(support_resistance_df['slope'], thresh)\n while support_resistance_df.groupby('cluster').apply(len).max() <= 2: # 如果个数最多的类还不超过2个\n thresh *= 2\n if thresh >= 1:\n return pd.DataFrame()\n support_resistance_df['cluster'] = clustering_kmeans(support_resistance_df['slope'], thresh)\n\n def calc_score_for_cluster(cluster_df):\n if len(cluster_df) <= 2:\n return pd.DataFrame()\n\n avg_x = cluster_df.iloc[:-1]['x'].mean()\n avg_y = cluster_df.iloc[:-1]['y'].mean()\n line = StraightLine(cluster_df.iloc[-1]['x'], cluster_df.iloc[-1]['y'], slope=cluster_df.iloc[-1]['slope'])\n mean_distance = line.point_distance(avg_x, avg_y)\n std = cluster_df.iloc[:-1]['x'].std(ddof=0)\n mean_x = cluster_df.iloc[:-1]['x'].mean()\n # divisor = (\n # std\n # # * math.sqrt(len(cluster_df) + 1)\n # * (len(cluster_df) + 1) ** 2\n # )\n # score = mean_distance / divisor\n\n return pd.DataFrame(\n {\n 'cluster': cluster_df.name,\n 'x1': last_support_resistance_pos['x'],\n 'y1': last_support_resistance_pos['y'],\n 'x2': cluster_df.iloc[-1]['x'],\n 'y2': cluster_df.iloc[-1]['y'],\n 'slope': cluster_df.iloc[-1]['slope'],\n 'count': len(cluster_df) - 1,\n 'mean_distance': mean_distance,\n 'mean_x': mean_x,\n 'std': std,\n # 'divisor': divisor,\n # 'score': score\n },\n index=[0]\n )\n\n score_df = (\n support_resistance_df\n .groupby('cluster')\n .apply(calc_score_for_cluster)\n .reset_index(drop=True)\n )\n\n # 整体不分组的情况也加入考虑\n all_df = support_resistance_df.copy()\n all_df.name = 'all'\n score_df.loc[len(score_df)] = calc_score_for_cluster(all_df).iloc[0]\n\n return score_df\n\n def show_line(self, points_df, *straight_line_list):\n fig, ax = plt.subplots(1, figsize=(16, 9))\n self.df.plot(ax=ax)\n\n # 支撑线画绿色点,压力线画红色点\n ax.scatter(points_df.x, points_df.y, s=50, c=self.dot_color, label=f'{self.kind}_dots')\n\n for i, st_line in enumerate(straight_line_list):\n ax.plot(\n self.x,\n st_line.predict(self.x, limit=(self.y.min(), self.y.max())),\n label=(['1st', '2nd', '3rd'] + list('456789abcdefghijklmnopq'))[i]\n )\n\n plt.legend()\n plt.show()\n\n # 对时间轴后40%上的所有点寻找最佳支撑或压力线\n def find_lines_in_the_last_area(self):\n last_area_support_resistance_df = self.support_resistance_df[\n self.support_resistance_df['x'] > len(self.df) * 0.75].copy()\n # last_area_support_resistance_df['min_distance'] = last_area_support_resistance_df.apply(\n # lambda _: self.find_best_line_from_a_point(_).min_score, axis=1\n # )\n\n df_list = [self.score_lines_from_a_point(row) for index, row in last_area_support_resistance_df.iterrows()]\n\n last_area_support_resistance_df = pd.concat(df_list)\n\n if len(last_area_support_resistance_df) == 0:\n raise ValueError(f\"未找到{'支撑线' if self.kind == 'support' else '压力线'},可能因为时间序列过短。\")\n\n last_area_support_resistance_df['score'] = (\n (\n last_area_support_resistance_df['mean_distance']\n / last_area_support_resistance_df['mean_x']\n / last_area_support_resistance_df['std']\n ).rank()\n / last_area_support_resistance_df['count']\n )\n\n self.last_area_support_resistance_df = last_area_support_resistance_df.sort_values(\n ['score', 'count'],\n ascending=[True, False]\n ).reset_index(drop=True)\n\n return self.last_area_support_resistance_df\n\n # 画出最好的3条线\n def show_top_lines(self, num=3):\n self.show_line(\n self.support_resistance_df, # 描点\n *(\n self.last_area_support_resistance_df[:num]\n .apply(lambda _: StraightLine(_['x1'], _['y1'], _['x2'], _['y2']), axis=1)\n .tolist()\n ),\n )\n\n # 画出最好的线\n def find_best_line(self, show=False):\n best_line_data = self.last_area_support_resistance_df.iloc[0]\n self.best_line = StraightLine(best_line_data['x1'], best_line_data['y1'], best_line_data['x2'],\n best_line_data['y2'])\n\n if show:\n self.show_line(\n self.support_resistance_df,\n self.best_line,\n )\n return self.best_line\n\n def show_both(self, ax=None, show_step=False):\n if self.kind != 'support':\n raise ValueError(\"只有支撑线对象可以调用此方法\")\n\n if show_step:\n print('寻找最佳拟合多项式曲线...')\n self.find_best_poly(show=show_step)\n if show_step:\n print('寻找拟合曲线极值点...')\n self.find_extreme_pos(show=show_step)\n\n if show_step:\n print('寻找支撑点...')\n self.find_real_extreme_points(show=show_step)\n if show_step:\n print('支撑点聚类...')\n self.cluster_nearest_support_resistance_pos(show=show_step)\n if show_step:\n print('遍历从时间序列后25%区域出发的所有支撑线...')\n self.find_lines_in_the_last_area()\n\n resistance_line = SupportResistanceLine(self.y, 'resistance')\n resistance_line.df = self.df\n resistance_line.min_extreme_pos = self.min_extreme_pos\n resistance_line.max_extreme_pos = self.max_extreme_pos\n\n if show_step:\n print('寻找阻力点...')\n resistance_line.find_real_extreme_points(show=show_step)\n if show_step:\n print('阻力点聚类...')\n resistance_line.cluster_nearest_support_resistance_pos(show=show_step)\n if show_step:\n print('遍历从时间序列后25%区域出发的所有阻力线...')\n resistance_line.find_lines_in_the_last_area()\n\n self.resistance_line = resistance_line\n\n if show_step:\n print('绘制图形...')\n\n is_new = False\n if ax is None:\n fig, ax = plt.subplots(1, figsize=(16, 9))\n is_new = True\n\n self.df.plot(ax=ax)\n\n # 支撑线画绿色点,压力线画红色点\n ax.scatter(self.support_resistance_df.x, self.support_resistance_df.y, s=50, c=self.dot_color,\n label='support_dots')\n ax.scatter(resistance_line.support_resistance_df.x, resistance_line.support_resistance_df.y, s=50,\n c=resistance_line.dot_color, label='resistance_dots')\n\n ax.plot(self.x, self.find_best_line().predict(self.x, (self.y.min(), self.y.max())), label='support_line',\n c='g')\n ax.plot(self.x, resistance_line.find_best_line().predict(self.x, (self.y.min(), self.y.max())),\n label='resistance_line', c='r')\n\n ax.legend()\n\n if is_new:\n plt.show()\n\n def find_points(self):\n \"\"\"\n 寻找所有的支撑点\\阻力点\n :return:\n \"\"\"\n self.find_best_poly(show=False)\n self.find_extreme_pos(show=False)\n self.find_real_extreme_points(show=False)\n return self.cluster_nearest_support_resistance_pos(show=False, inplace=True)\n\n\ndef test_support_line(datas):\n start_idx = 0\n df = pd.DataFrame()\n trend_cnt = 0\n for index, data in datas.iterrows():\n start_idx = start_idx + 1\n df = df.append({'y': data.close}, ignore_index=True)\n if start_idx > 160:\n support_line = SupportResistanceLine(df['y'], 'support')\n supports = support_line.find_support_points()\n if supports.__len__() > 2:\n if supports[-3] < supports[-2] < supports[-1]:\n trend_cnt = trend_cnt + 1\n else:\n print(data.date.strftime(\"%Y-%m-%d\") + '结束, 持续天数:' + str(trend_cnt))\n trend_cnt = 0\n else:\n print('未找到足够的支撑点!!!')\n df = df.drop(0)\n if trend_cnt == 1:\n print(data.date.strftime(\"%Y-%m-%d\") + ',第一次,连续三次支撑点上升')\n\n\nif __name__ == '__main__':\n df = dp.load_bar_data('000001', 'XSHG', start_date=dt.datetime(2019, 5, 1), end_data=dt.datetime(2020, 5, 1))\n # test_support_line(data)\n support_line = SupportResistanceLine(df.close, 'support')\n # support_line.show_both(show_step=True)\n support_line.show_both(show_step=True)\n # support_line.find_best_poly(show=True)\n # support_line.find_extreme_pos(show=True)\n # support_line.find_real_extreme_points(show=True)\n # support_line.cluster_nearest_support_resistance_pos(show=True)\n" ]
[ [ "pandas.Panel", "pandas.DataFrame" ], [ "pandas.merge", "pandas.to_datetime", "pandas.Panel", "pandas.DataFrame", "numpy.float64" ], [ "pandas.DataFrame" ], [ "matplotlib.pyplot.legend", "pandas.concat", "pandas.Series", "numpy.polynomial.Chebyshev.fit", "sklearn.cluster.KMeans", "matplotlib.pyplot.subplots", "pandas.DataFrame", "sklearn.metrics.mean_squared_error", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20" ], "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": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.15", "1.14", "1.17" ], "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": [] } ]
pazamelin/openvino
[ "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "031e998a15ec738c64cc2379d7f30fb73087c272", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "031e998a15ec738c64cc2379d7f30fb73087c272", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48", "b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48" ]
[ "src/bindings/python/tests/test_ngraph/test_ops_binary.py", "tools/mo/openvino/tools/mo/middle/passes/convert_data_type.py", "src/bindings/python/tests_compatibility/test_ngraph/test_ops_multioutput.py", "tools/mo/unit_tests/mo/ops/scatternd_test.py", "tools/mo/unit_tests/mo/ops/sparse_segment_sum_test.py", "tools/mo/openvino/tools/mo/ops/hard_sigmoid.py", "src/bindings/python/tests_compatibility/test_onnx/utils/model_importer.py", "tools/mo/openvino/tools/mo/back/ProposalMutation.py", "src/bindings/python/tests_compatibility/test_ngraph/test_ops_unary.py", "tools/mo/openvino/tools/mo/middle/passes/fusing/decomposition.py", "tools/mo/unit_tests/mo/front/common/partial_infer/utils_test.py", "tools/mo/unit_tests/mo/ops/unique_test.py", "tests/conditional_compilation/test_cc.py", "tools/mo/openvino/tools/mo/back/ShuffleChannelPatternOptimization.py" ]
[ "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport operator\n\nimport numpy as np\nimport pytest\n\nimport openvino.runtime.opset8 as ov\nfrom tests.runtime import get_runtime\nfrom tests.test_ngraph.util import run_op_node\n\n\[email protected](\n \"ng_api_helper,numpy_function\",\n [\n (ov.add, np.add),\n (ov.divide, np.divide),\n (ov.multiply, np.multiply),\n (ov.subtract, np.subtract),\n (ov.minimum, np.minimum),\n (ov.maximum, np.maximum),\n (ov.mod, np.mod),\n (ov.equal, np.equal),\n (ov.not_equal, np.not_equal),\n (ov.greater, np.greater),\n (ov.greater_equal, np.greater_equal),\n (ov.less, np.less),\n (ov.less_equal, np.less_equal),\n ],\n)\ndef test_binary_op(ng_api_helper, numpy_function):\n runtime = get_runtime()\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.float32)\n parameter_b = ov.parameter(shape, name=\"B\", dtype=np.float32)\n\n model = ng_api_helper(parameter_a, parameter_b)\n computation = runtime.computation(model, parameter_a, parameter_b)\n\n value_a = np.array([[1, 2], [3, 4]], dtype=np.float32)\n value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)\n\n result = computation(value_a, value_b)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"ng_api_helper,numpy_function\",\n [\n (ov.add, np.add),\n (ov.divide, np.divide),\n (ov.multiply, np.multiply),\n (ov.subtract, np.subtract),\n (ov.minimum, np.minimum),\n (ov.maximum, np.maximum),\n (ov.mod, np.mod),\n (ov.equal, np.equal),\n (ov.not_equal, np.not_equal),\n (ov.greater, np.greater),\n (ov.greater_equal, np.greater_equal),\n (ov.less, np.less),\n (ov.less_equal, np.less_equal),\n ],\n)\ndef test_binary_op_with_scalar(ng_api_helper, numpy_function):\n runtime = get_runtime()\n\n value_a = np.array([[1, 2], [3, 4]], dtype=np.float32)\n value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.float32)\n\n model = ng_api_helper(parameter_a, value_b)\n computation = runtime.computation(model, parameter_a)\n\n result = computation(value_a)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"ng_api_helper,numpy_function\",\n [(ov.logical_and, np.logical_and), (ov.logical_or, np.logical_or), (ov.logical_xor, np.logical_xor)],\n)\ndef test_binary_logical_op(ng_api_helper, numpy_function):\n runtime = get_runtime()\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.bool)\n parameter_b = ov.parameter(shape, name=\"B\", dtype=np.bool)\n\n model = ng_api_helper(parameter_a, parameter_b)\n computation = runtime.computation(model, parameter_a, parameter_b)\n\n value_a = np.array([[True, False], [False, True]], dtype=np.bool)\n value_b = np.array([[False, True], [False, True]], dtype=np.bool)\n\n result = computation(value_a, value_b)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"ng_api_helper,numpy_function\",\n [(ov.logical_and, np.logical_and), (ov.logical_or, np.logical_or), (ov.logical_xor, np.logical_xor)],\n)\ndef test_binary_logical_op_with_scalar(ng_api_helper, numpy_function):\n runtime = get_runtime()\n\n value_a = np.array([[True, False], [False, True]], dtype=np.bool)\n value_b = np.array([[False, True], [False, True]], dtype=np.bool)\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.bool)\n\n model = ng_api_helper(parameter_a, value_b)\n computation = runtime.computation(model, parameter_a)\n\n result = computation(value_a)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"operator,numpy_function\",\n [\n (operator.add, np.add),\n (operator.sub, np.subtract),\n (operator.mul, np.multiply),\n (operator.truediv, np.divide),\n (operator.eq, np.equal),\n (operator.ne, np.not_equal),\n (operator.gt, np.greater),\n (operator.ge, np.greater_equal),\n (operator.lt, np.less),\n (operator.le, np.less_equal),\n ],\n)\ndef test_binary_operators(operator, numpy_function):\n runtime = get_runtime()\n\n value_a = np.array([[1, 2], [3, 4]], dtype=np.float32)\n value_b = np.array([[4, 5], [1, 7]], dtype=np.float32)\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.float32)\n\n model = operator(parameter_a, value_b)\n computation = runtime.computation(model, parameter_a)\n\n result = computation(value_a)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"operator,numpy_function\",\n [\n (operator.add, np.add),\n (operator.sub, np.subtract),\n (operator.mul, np.multiply),\n (operator.truediv, np.divide),\n (operator.eq, np.equal),\n (operator.ne, np.not_equal),\n (operator.gt, np.greater),\n (operator.ge, np.greater_equal),\n (operator.lt, np.less),\n (operator.le, np.less_equal),\n ],\n)\ndef test_binary_operators_with_scalar(operator, numpy_function):\n runtime = get_runtime()\n\n value_a = np.array([[1, 2], [3, 4]], dtype=np.float32)\n value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)\n\n shape = [2, 2]\n parameter_a = ov.parameter(shape, name=\"A\", dtype=np.float32)\n\n model = operator(parameter_a, value_b)\n computation = runtime.computation(model, parameter_a)\n\n result = computation(value_a)\n expected = numpy_function(value_a, value_b)\n assert np.allclose(result, expected)\n\n\ndef test_multiply():\n A = np.arange(48, dtype=np.int32).reshape((8, 1, 6, 1))\n B = np.arange(35, dtype=np.int32).reshape((7, 1, 5))\n\n expected = np.multiply(A, B)\n result = run_op_node([A, B], ov.multiply)\n\n assert np.allclose(result, expected)\n\n\ndef test_power_v1():\n A = np.arange(48, dtype=np.float32).reshape((8, 1, 6, 1))\n B = np.arange(20, dtype=np.float32).reshape((4, 1, 5))\n\n expected = np.power(A, B)\n result = run_op_node([A, B], ov.power)\n\n assert np.allclose(result, expected)\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport logging as log\n\nimport numpy as np\n\nfrom openvino.tools.mo.front.extractor import get_new_placeholder_name\nfrom openvino.tools.mo.graph.graph import Node, Graph\nfrom openvino.tools.mo.utils.error import Error\nfrom openvino.tools.mo.utils.utils import refer_to_faq_msg\n\n\"\"\"\nPacked data of custom types are stored in numpy uint8 data type.\nTo distinguish true uint8 and custom data we introduce this class not to store,\nbut to have unique data type in SUPPORTED_DATA_TYPES map\n\"\"\"\n\n\nclass packed_U1(np.generic):\n pass\n\n\nclass packed_U4(np.generic):\n pass\n\n\nclass packed_I4(np.generic):\n pass\n\n\nSUPPORTED_DATA_TYPES = {\n 'float': (np.float32, 'FP32', 'f32'),\n 'half': (np.float16, 'FP16', 'f16'),\n 'FP32': (np.float32, 'FP32', 'f32'),\n 'FP64': (np.float64, 'FP64', 'f64'),\n 'FP16': (np.float16, 'FP16', 'f16'),\n 'I32': (np.int32, 'I32', 'i32'),\n 'I64': (np.int64, 'I64', 'i64'),\n 'int8': (np.int8, 'I8', 'i8'),\n 'int32': (np.int32, 'I32', 'i32'),\n 'int64': (np.int64, 'I64', 'i64'),\n 'bool': (np.bool, 'BOOL', 'boolean'),\n 'uint8': (np.uint8, 'U8', 'u8'),\n 'uint32': (np.uint32, 'U32', 'u32'),\n 'uint64': (np.uint64, 'U64', 'u64'),\n\n # custom types\n 'U1': (packed_U1, 'U1', 'u1'),\n 'int4': (packed_I4, 'I4', 'i4'),\n 'uint4': (packed_U4, 'U4', 'u4'),\n 'I4': (packed_I4, 'I4', 'i4'),\n 'U4': (packed_U4, 'U4', 'u4'),\n}\n\n\ndef data_type_str_to_np(data_type_str: str):\n return SUPPORTED_DATA_TYPES[data_type_str][0] if data_type_str in SUPPORTED_DATA_TYPES else None\n\n\ndef data_type_str_to_precision(data_type_str: str):\n return SUPPORTED_DATA_TYPES[data_type_str][1] if data_type_str in SUPPORTED_DATA_TYPES else None\n\n\ndef data_type_str_to_destination_type(data_type_str: str):\n return SUPPORTED_DATA_TYPES[data_type_str][2] if data_type_str in SUPPORTED_DATA_TYPES else None\n\n\ndef np_data_type_to_precision(np_data_type):\n for np_t, precision, _ in SUPPORTED_DATA_TYPES.values():\n if np_t == np_data_type:\n return precision\n raise Error('Data type \"{}\" is not supported'.format(np_data_type))\n\n\ndef np_data_type_to_destination_type(np_data_type):\n for np_t, _, destination_type in SUPPORTED_DATA_TYPES.values():\n if np_t == np_data_type:\n return destination_type\n raise Error('Data type \"{}\" is not supported'.format(np_data_type))\n\n\ndef destination_type_to_np_data_type(dst_type):\n for np_t, _, destination_type in SUPPORTED_DATA_TYPES.values():\n if destination_type == dst_type:\n return np_t\n raise Error('Destination type \"{}\" is not supported'.format(dst_type))\n\n\ndef precision_to_destination_type(data_type_str):\n for _, precision, destination_type in SUPPORTED_DATA_TYPES.values():\n if precision == data_type_str:\n return destination_type\n raise Error('Data type \"{}\" is not supported'.format(data_type_str))\n\n\ndef convert_blob(blob: np.ndarray, dst_type: type):\n if blob.dtype == dst_type:\n return blob, None, None\n\n converted_blob = blob.astype(dtype=dst_type, casting=\"unsafe\")\n if dst_type in (np.int32, np.int64, np.uint8, np.int8) and not np.array_equal(blob, converted_blob):\n raise Error('The conversion of blob with value \"{}\" to dst_type \"{}\" results in rounding'.format(\n blob, dst_type))\n\n finite_match = (np.isfinite(blob) != np.isfinite(converted_blob))\n zero_match = ((blob == 0) != (converted_blob == 0))\n finite_match_count = np.count_nonzero(finite_match)\n zero_match_count = np.count_nonzero(zero_match)\n\n return converted_blob, finite_match_count, zero_match_count\n\n\ndef convert_node_blobs(graph: Graph, node: Node, data_type: type):\n out_edges = graph.out_edges(node.node, data=True)\n\n # if the data.value is used as binary weights\n if any('bin' in d for _, __, d in out_edges):\n blob = node.value\n if blob.dtype != data_type:\n new_blob, finite_match_count, zero_match_count = convert_blob(blob, data_type)\n consumers = [x.name if x.has_valid('name') else '<NO NAME>' for x in node.out_nodes()]\n log.debug(\n 'Blob was converted to {} while dumping to the bin file. This blob is an input for {} nodes.'.format(\n data_type, consumers))\n if finite_match_count:\n log.error(\n (\"{} elements of {} were clipped to infinity while converting a blob for node [{}] to {}. \" +\n refer_to_faq_msg(76)).format(finite_match_count, blob.size, consumers, data_type))\n if zero_match_count:\n log.warning(\n (\"{} elements of {} were clipped to zero while converting a blob for node [{}] to {}. \" +\n refer_to_faq_msg(77)).format(zero_match_count, blob.size, consumers, data_type))\n\n node.value = new_blob\n # for the constant node need to propagate the converted value to the node output because there is a fake\n # input data for the 'Const' nodes being generated in the CreateConstNodesReplacement\n if len(node.out_nodes()) == 1 and node.out_node(0).op == 'Const':\n const_node = node.out_node(0)\n const_node.value = new_blob\n const_node.infer(const_node)\n const_node.type_infer(const_node)\n\n\ndef convert_parameters_data_type(graph: Graph, data_type_str: str):\n inputs = graph.get_op_nodes(op='Parameter')\n data_type = data_type_str_to_np(data_type_str)\n user_defined_data_types = graph.graph['user_shapes'] if 'user_shapes' in graph.graph else None\n for input in inputs:\n user_defined_type = None\n name = input.soft_get('initial_node_name', input.id)\n\n # override data type for Parameter specified by the user. This is a workaround for the issue in the\n # extensions.middle.ChangePlaceholderTypes transformation which has an incorrect condition and always overrides\n # Parameter data type to np.float32. When the transformation is fixed the code below must be updated\n if user_defined_data_types is not None and name in user_defined_data_types:\n for desc in user_defined_data_types[name]:\n if 'port' in desc and desc['port'] is None: # neither input nor output port specified\n user_defined_type = desc.get('data_type', None)\n else: # need to check the particular port the Parameter was created for\n p_name = get_new_placeholder_name(name, 'out' in desc, desc['out'] if 'out' in desc else desc['in'])\n if p_name == input.soft_get('name'):\n user_defined_type = desc.get('data_type', None)\n if user_defined_type is not None:\n log.info('Overriding Parameter node {} data type to {}'.format(name, user_defined_type))\n input['data_type'] = user_defined_type\n input.out_port(0).set_data_type(user_defined_type, True)\n elif not input.has_valid('data_type') or input.data_type == np.float32:\n input['data_type'] = data_type\n input.out_port(0).set_data_type(data_type, True)\n else:\n log.info('Do not change data type for node {}'.format(input.soft_get('name')))\n\n\ndef convert_blobs(graph: Graph, data_type_str: str):\n for node in graph.get_data_nodes():\n if node.value is not None:\n try:\n if node.value.dtype in [np.float32, np.float64, np.float16] and not node.has_and_set('correct_data_type'):\n convert_node_blobs(graph, node, data_type_str_to_np(data_type_str))\n except Exception as e:\n raise Error('Coudn\\'t convert blob {}, details: {}', node.soft_get('name'), e) from e\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\n\nimport ngraph as ng\nfrom tests_compatibility.runtime import get_runtime\n\n\ndef test_split():\n runtime = get_runtime()\n input_tensor = ng.constant(np.array([0, 1, 2, 3, 4, 5], dtype=np.int32))\n axis = ng.constant(0, dtype=np.int64)\n splits = 3\n\n split_node = ng.split(input_tensor, axis, splits)\n computation = runtime.computation(split_node)\n split_results = computation()\n expected_results = np.array([[0, 1], [2, 3], [4, 5]], dtype=np.int32)\n assert np.allclose(split_results, expected_results)\n\n\ndef test_variadic_split():\n runtime = get_runtime()\n input_tensor = ng.constant(np.array([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]], dtype=np.int32))\n axis = ng.constant(1, dtype=np.int64)\n splits = ng.constant(np.array([2, 4], dtype=np.int64))\n\n v_split_node = ng.variadic_split(input_tensor, axis, splits)\n computation = runtime.computation(v_split_node)\n results = computation()\n split0 = np.array([[0, 1], [6, 7]], dtype=np.int32)\n split1 = np.array([[2, 3, 4, 5], [8, 9, 10, 11]], dtype=np.int32)\n\n assert np.allclose(results[0], split0)\n assert np.allclose(results[1], split1)\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport unittest\n\nimport numpy as np\n\nfrom openvino.tools.mo.ops.scatternd import ScatterNDUpdate\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array\nfrom openvino.tools.mo.graph.graph import Node\nfrom unit_tests.utils.graph import build_graph\n\nnodes_attributes = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'updates': {'shape': None, 'value': None, 'kind': 'data'},\n 'scatternd_node': {'op': 'ScatterNDUpdate', 'kind': 'op'},\n 'output': {'shape': None, 'value': None, 'kind': 'data'}}\n\n# graph 1\nedges = [('input', 'scatternd_node', {'in': 0}),\n ('indices', 'scatternd_node', {'in': 1}),\n ('updates', 'scatternd_node', {'in': 2}),\n ('scatternd_node', 'output', {'out': 0})]\n\n# test data for partial infer\ninputs1 = {'input': {'shape': int64_array([10, 40]), 'value': None},\n 'indices': {'shape': int64_array([3, 2]), 'value': None},\n 'updates': {'shape': int64_array([3]), 'value': None}}\n\ninputs2 = {'input': {'shape': int64_array([20, 30]), 'value': None},\n 'indices': {'shape': int64_array([2]), 'value': None},\n 'updates': {'shape': int64_array([]), 'value': None}}\n\ninputs3 = {'input': {'shape': int64_array([20, 30, 5]), 'value': None},\n 'indices': {'shape': int64_array([2]), 'value': None},\n 'updates': {'shape': int64_array([5]), 'value': None}}\n\ninputs4 = {'input': {'shape': int64_array([10, 40, 50]), 'value': None},\n 'indices': {'shape': int64_array([7, 3, 2]), 'value': None},\n 'updates': {'shape': int64_array([7, 3, 50]), 'value': None}}\n\n# test data for constant folding\ninputs5 = {'input': {'shape': int64_array([8]), 'value': int64_array([1, 2, 3, 4, 5, 6, 7, 8])},\n 'indices': {'shape': int64_array([4, 1]), 'value': int64_array([[4], [3], [1], [7]])},\n 'updates': {'shape': int64_array([4]), 'value': int64_array([9, 10, 11, 12])}}\noutput5 = int64_array([1, 11, 3, 10, 9, 6, 7, 12])\n\ninputs6 = {'input': {'shape': int64_array([4, 4, 4]), 'value': int64_array([[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]])},\n 'indices': {'shape': int64_array([2, 1]), 'value': int64_array([[0], [2]])},\n 'updates': {'shape': int64_array([2, 4, 4]), 'value': int64_array([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]])}}\noutput6 = int64_array([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]])\n\ninputs7 = {'input': {'shape': int64_array([8]), 'value': int64_array([1, 2, 3, 4, 5, 6, 7, 8])},\n 'indices': {'shape': int64_array([1]), 'value': int64_array([4])},\n 'updates': {'shape': int64_array([]), 'value': 9}}\noutput7 = int64_array([1, 2, 3, 4, 9, 6, 7, 8])\n\ninputs8 = {'input': {'shape': int64_array([3]), 'value': int64_array([1, 2, 3])},\n 'indices': {'shape': int64_array([1]), 'value': int64_array([2])},\n 'updates': {'shape': int64_array([1]), 'value': int64_array([9])}}\noutput8 = int64_array([1, 2, 9])\n\nclass TestScatterNDUpdate(unittest.TestCase):\n def test_partial_infer1(self):\n graph = build_graph(nodes_attributes, edges, inputs1)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # prepare reference results\n ref_output_shape = np.array([10, 40], dtype=np.int32)\n\n # get the result\n res_output_shape = graph.node['output']['shape']\n\n self.assertTrue(np.array_equal(ref_output_shape, res_output_shape),\n 'values do not match expected: {} and given: {}'.format(ref_output_shape, res_output_shape))\n\n def test_partial_infer2(self):\n graph = build_graph(nodes_attributes, edges, inputs2)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # prepare reference results\n ref_output_shape = np.array([20, 30], dtype=np.int32)\n\n # get the result\n res_output_shape = graph.node['output']['shape']\n\n self.assertTrue(np.array_equal(ref_output_shape, res_output_shape),\n 'values do not match expected: {} and given: {}'.format(ref_output_shape, res_output_shape))\n\n def test_partial_infer3(self):\n graph = build_graph(nodes_attributes, edges, inputs3)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # prepare reference results\n ref_output_shape = np.array([20, 30, 5], dtype=np.int32)\n\n # get the result\n res_output_shape = graph.node['output']['shape']\n\n self.assertTrue(np.array_equal(ref_output_shape, res_output_shape),\n 'values do not match expected: {} and given: {}'.format(ref_output_shape, res_output_shape))\n\n def test_partial_infer4(self):\n graph = build_graph(nodes_attributes, edges, inputs4)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # prepare reference results\n ref_output_shape = np.array([10, 40, 50], dtype=np.int32)\n\n # get the result\n res_output_shape = graph.node['output']['shape']\n\n self.assertTrue(np.array_equal(ref_output_shape, res_output_shape),\n 'values do not match expected: {} and given: {}'.format(ref_output_shape, res_output_shape))\n\n def test_infer5(self):\n graph = build_graph(nodes_attributes, edges, inputs5)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # get the result\n res_output_value = graph.node['output']['value']\n\n self.assertTrue(np.array_equal(output5, res_output_value),\n 'values do not match expected: {} and given: {}'.format(output5, res_output_value))\n\n def test_infer6(self):\n graph = build_graph(nodes_attributes, edges, inputs6)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # get the result\n res_output_value = graph.node['output']['value']\n\n self.assertTrue(np.array_equal(output6, res_output_value),\n 'values do not match expected: {} and given: {}'.format(output6, res_output_value))\n\n def test_infer7_scalar(self):\n graph = build_graph(nodes_attributes, edges, inputs7)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # get the result\n res_output_value = graph.node['output']['value']\n\n self.assertTrue(np.array_equal(output7, res_output_value),\n 'values do not match expected: {} and given: {}'.format(output7, res_output_value))\n\n def test_infer8(self):\n graph = build_graph(nodes_attributes, edges, inputs8)\n scatternd_node = Node(graph, 'scatternd_node')\n ScatterNDUpdate.infer(scatternd_node)\n\n # get the result\n res_output_value = graph.node['output']['value']\n\n self.assertTrue(np.array_equal(output8, res_output_value),\n 'values do not match expected: {} and given: {}'.format(output8, res_output_value))\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport unittest\n\nimport numpy as np\n\nfrom openvino.tools.mo.ops.sparse_segment_sum import SparseSegmentSum\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array\nfrom openvino.tools.mo.graph.graph import Node\nfrom unit_tests.utils.graph import build_graph\n\n# graph 1\nnodes_attributes1 = {'input_data': {'shape': None, 'value': None, 'kind': 'data'},\n 'input_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'input_segment_ids': {'shape': None, 'value': None, 'kind': 'data'},\n 'sparse_segment_sum_node': {'op': 'SparseSegmentSum', 'kind': 'op'},\n 'output_segments': {'shape': None, 'value': None, 'kind': 'data'},\n }\n\nedges1 = [('input_data', 'sparse_segment_sum_node', {'in': 0}),\n ('input_indices', 'sparse_segment_sum_node', {'in': 1}),\n ('input_segment_ids', 'sparse_segment_sum_node', {'in': 2}),\n ('sparse_segment_sum_node', 'output_segments', {'out': 0})]\n\ninputs1 = {'input_data': {'shape': int64_array([20, 4, 5]), 'value': None},\n 'input_indices': {'shape': int64_array([40]), 'value': None},\n 'input_segment_ids': {'shape': int64_array([40]), 'value': None}}\n\n# graph 2 with constant input, sum\nnodes_attributes2 = {'input_data': {'shape': None, 'value': None, 'kind': 'data'},\n 'input_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'input_segment_ids': {'shape': None, 'value': None, 'kind': 'data'},\n 'sparse_segment_sum_node': {'op': 'SparseSegmentSum', 'kind': 'op'},\n 'output_segments': {'shape': None, 'value': None, 'kind': 'data'},\n }\n\nedges2 = [('input_data', 'sparse_segment_sum_node', {'in': 0}),\n ('input_indices', 'sparse_segment_sum_node', {'in': 1}),\n ('input_segment_ids', 'sparse_segment_sum_node', {'in': 2}),\n ('sparse_segment_sum_node', 'output_segments', {'out': 0})]\n\ninputs2 = {'input_data': {'shape': int64_array([3, 4]), 'value': np.array([[1, 2, 3, 4], [-1, -2, -3, -4], [5, 6, 7, 8]], dtype=np.float)},\n 'input_indices': {'shape': int64_array([3]), 'value': np.array([0, 1, 2], dtype=np.float)},\n 'input_segment_ids': {'shape': int64_array([3]), 'value': np.array([0, 0, 1], dtype=np.float)}}\n\nclass TestSparseSegmentSum(unittest.TestCase):\n def test_partial_infer(self):\n graph = build_graph(nodes_attributes1, edges1, inputs1)\n\n sparse_segment_sum_node = Node(graph, 'sparse_segment_sum_node')\n SparseSegmentSum.infer(sparse_segment_sum_node)\n\n # prepare reference results\n ref_output_segments_shape = int64_array([40, 4, 5])\n\n # get resulted shapes\n res_output_segments_shape = graph.node['output_segments']['shape']\n\n self.assertTrue(np.array_equal(ref_output_segments_shape, res_output_segments_shape),\n 'Shapes do not match expected: {} and given: {}'.format(ref_output_segments_shape, res_output_segments_shape))\n\n def test_incorrect_shapes(self):\n inputs = {'input_data': {'shape': int64_array([20, 4, 5]), 'value': None},\n 'input_indices': {'shape': int64_array([39]), 'value': None},\n 'input_segment_ids': {'shape': int64_array([40]), 'value': None}}\n graph = build_graph(nodes_attributes1, edges1, inputs)\n sparse_segment_sum_node = Node(graph, 'sparse_segment_sum_node')\n self.assertRaises(AssertionError, SparseSegmentSum.infer, sparse_segment_sum_node)\n\n def test_infer_constant_input_sum(self):\n graph = build_graph(nodes_attributes2, edges2, inputs2)\n\n sparse_segment_sum_node = Node(graph, 'sparse_segment_sum_node')\n SparseSegmentSum.infer(sparse_segment_sum_node)\n\n # prepare reference results\n ref_output_segments_shape = int64_array([2, 4])\n ref_output_segments_value = np.array([[0, 0, 0, 0], [5, 6, 7, 8]], dtype=np.float)\n\n # get resulted shapes\n res_output_segments_shape = graph.node['output_segments']['shape']\n res_output_segments_value = graph.node['output_segments']['value']\n\n self.assertTrue(np.array_equal(ref_output_segments_shape, res_output_segments_shape),\n 'Shapes do not match expected: {} and given: {}'.format(ref_output_segments_shape, res_output_segments_shape))\n self.assertTrue(np.array_equal(ref_output_segments_value, res_output_segments_value),\n 'Shapes do not match expected: {} and given: {}'.format(ref_output_segments_value, res_output_segments_value))\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\n\nfrom openvino.tools.mo.graph.graph import Node, Graph\nfrom openvino.tools.mo.ops.op import Op\n\n\nclass HardSigmoid(Op):\n op = 'HardSigmoid'\n enabled = False\n\n def __init__(self, graph: Graph, attrs: dict):\n super().__init__(graph, {\n 'op': self.op,\n 'type': self.op,\n 'version': 'opset1',\n 'infer': self.infer,\n 'in_ports_count': 3,\n 'out_ports_count': 1,\n }, attrs)\n\n @staticmethod\n def infer(node: Node):\n input_node = node.in_node(0)\n data_value = node.in_port(0).data.get_value()\n alpha_value = node.in_port(1).data.get_value()\n beta_value = node.in_port(2).data.get_value()\n if data_value is not None and alpha_value is not None and beta_value is not None:\n node.out_port(0).data.set_value(np.clip(data_value * alpha_value + beta_value, 0, 1))\n return\n\n node.out_port(0).data.set_shape(input_node.shape.copy())\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\nimport onnx\nimport onnx.backend.test\nimport unittest\n\nfrom collections import defaultdict, namedtuple\nfrom onnx import numpy_helper, NodeProto, ModelProto\nfrom onnx.backend.base import Backend, BackendRep\nfrom onnx.backend.test.case.test_case import TestCase as OnnxTestCase\nfrom onnx.backend.test.runner import TestItem\nfrom pathlib import Path\nfrom tests_compatibility.test_onnx.utils.onnx_helpers import import_onnx_model\nfrom typing import Any, Dict, List, Optional, Pattern, Set, Text, Type, Union, Callable, Sequence\n\n\n# add post-processing function as part of test data\nExtOnnxTestCase = namedtuple(\"TestCaseExt\", OnnxTestCase._fields + (\"post_processing\",))\n\n\nclass ModelImportRunner(onnx.backend.test.BackendTest):\n def __init__(\n self,\n backend: Type[Backend],\n models: List[Dict[str, Path]],\n parent_module: Optional[str] = None,\n data_root: Optional[Path] = \"\",\n ) -> None:\n self.backend = backend\n self._parent_module = parent_module\n self._include_patterns = set() # type: Set[Pattern[Text]]\n self._exclude_patterns = set() # type: Set[Pattern[Text]]\n self._test_items = defaultdict(dict) # type: Dict[Text, Dict[Text, TestItem]]\n self._xfail_patterns = set() # type: Set[Pattern[Text]]\n\n for model in models:\n test_name = \"test{}\".format(model[\"model_name\"]) \\\n .replace(str(data_root), \"\") \\\n .replace(\".onnx\", \"\") \\\n .replace(\"/\", \"_\") \\\n .replace(\"\\\\\", \"_\") \\\n .replace(\"-\", \"_\")\n\n test_case = ExtOnnxTestCase(\n name=test_name,\n url=None,\n model_name=model[\"model_name\"],\n model_dir=model[\"dir\"],\n model=model[\"model_file\"],\n data_sets=None,\n kind=\"OnnxBackendRealModelTest\",\n rtol=model.get(\"rtol\", 0.001),\n atol=model.get(\"atol\", 1e-07),\n post_processing=model.get(\"post_processing\", None)\n )\n self._add_model_import_test(test_case)\n self._add_model_execution_test(test_case)\n\n @staticmethod\n def _load_onnx_model(model_dir: Path, filename: Path) -> ModelProto:\n if model_dir is None:\n raise unittest.SkipTest(\"Model directory not provided\")\n\n return onnx.load(model_dir / filename)\n\n def _add_model_import_test(self, model_test: ExtOnnxTestCase) -> None:\n # model is loaded at runtime, note sometimes it could even\n # never loaded if the test skipped\n model_marker = [None] # type: List[Optional[Union[ModelProto, NodeProto]]]\n\n def run_import(test_self: Any, device: Text) -> None:\n model = ModelImportRunner._load_onnx_model(model_test.model_dir, model_test.model)\n model_marker[0] = model\n assert import_onnx_model(model)\n\n self._add_test(\"ModelImport\", model_test.name, run_import, model_marker)\n\n @classmethod\n def _execute_npz_data(\n cls, model_dir: str, prepared_model: BackendRep, result_rtol: float, result_atol: float,\n post_processing: Callable[[Sequence[Any]], Sequence[Any]] = None\n ) -> int:\n executed_tests = 0\n for test_data_npz in model_dir.glob(\"test_data_*.npz\"):\n test_data = np.load(test_data_npz, encoding=\"bytes\")\n inputs = list(test_data[\"inputs\"])\n outputs = list(prepared_model.run(inputs))\n ref_outputs = test_data[\"outputs\"]\n if post_processing is not None:\n outputs = post_processing(outputs)\n cls.assert_similar_outputs(ref_outputs, outputs, result_rtol, result_atol)\n executed_tests = executed_tests + 1\n return executed_tests\n\n @classmethod\n def _execute_pb_data(\n cls, model_dir: str, prepared_model: BackendRep, result_rtol: float, result_atol: float,\n post_processing: Callable[[Sequence[Any]], Sequence[Any]] = None\n ) -> int:\n executed_tests = 0\n for test_data_dir in model_dir.glob(\"test_data_set*\"):\n inputs = []\n inputs_num = len(list(test_data_dir.glob(\"input_*.pb\")))\n for i in range(inputs_num):\n input_file = Path(test_data_dir) / \"input_{}.pb\".format(i)\n tensor = onnx.TensorProto()\n with open(input_file, \"rb\") as f:\n tensor.ParseFromString(f.read())\n inputs.append(numpy_helper.to_array(tensor))\n ref_outputs = []\n ref_outputs_num = len(list(test_data_dir.glob(\"output_*.pb\")))\n for i in range(ref_outputs_num):\n output_file = Path(test_data_dir) / \"output_{}.pb\".format(i)\n tensor = onnx.TensorProto()\n with open(output_file, \"rb\") as f:\n tensor.ParseFromString(f.read())\n ref_outputs.append(numpy_helper.to_array(tensor))\n if(len(inputs) == 0):\n continue\n outputs = list(prepared_model.run(inputs))\n if post_processing is not None:\n outputs = post_processing(outputs)\n cls.assert_similar_outputs(ref_outputs, outputs, result_rtol, result_atol)\n executed_tests = executed_tests + 1\n return executed_tests\n\n def _add_model_execution_test(self, model_test: ExtOnnxTestCase) -> None:\n # model is loaded at runtime, note sometimes it could even\n # never loaded if the test skipped\n model_marker = [None] # type: List[Optional[Union[ModelProto, NodeProto]]]\n\n def run_execution(test_self: Any, device: Text) -> None:\n model = ModelImportRunner._load_onnx_model(model_test.model_dir, model_test.model)\n model_marker[0] = model\n prepared_model = self.backend.prepare(model, device)\n assert prepared_model is not None\n executed_tests = ModelImportRunner._execute_npz_data(\n model_test.model_dir, prepared_model, model_test.rtol, model_test.atol,\n model_test.post_processing\n )\n\n executed_tests = executed_tests + ModelImportRunner._execute_pb_data(\n model_test.model_dir, prepared_model, model_test.rtol, model_test.atol,\n model_test.post_processing\n )\n assert executed_tests > 0, \"This model has no test data\"\n self._add_test(\"ModelExecution\", model_test.name, run_execution, model_marker)\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport logging as log\n\nimport numpy as np\n\nfrom openvino.tools.mo.back.ReshapeMutation import ReshapeMutation\nfrom openvino.tools.mo.back.StridedSliceMasksNormalizer import StridedSliceMasksNormalizer\nfrom openvino.tools.mo.back.replacement import BackReplacementPattern\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array\nfrom openvino.tools.mo.front.common.partial_infer.utils import mo_array\nfrom openvino.tools.mo.front.tf.graph_utils import create_op_with_const_inputs, create_op_node_with_second_input\nfrom openvino.tools.mo.graph.graph import Graph\nfrom openvino.tools.mo.ops.reshape import Reshape\nfrom openvino.tools.mo.ops.strided_slice import StridedSlice\n\n\nclass ProposalMutation(BackReplacementPattern):\n enabled = True\n force_shape_inference = True\n\n def run_before(self):\n return [ReshapeMutation, StridedSliceMasksNormalizer]\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[('proposal', {'type': 'Proposal'})],\n edges=[],\n )\n\n @staticmethod\n def replace_pattern(graph: Graph, match: dict):\n node = match['proposal']\n assert len(node.in_ports()) == 3, \"Proposal op must have exactly 3 input ports\"\n im_info_shape = node.in_port(2).data.get_shape()\n assert im_info_shape is not None\n\n if np.array_equal(im_info_shape, [1, 6]):\n log.error('The model contains Proposal layer \"{}\" with input of shape [1, 6]. Inference Engine '\n 'implementation of the Proposal layer uses only 4 first values (indices 0, 1, 2 and 3). '\n 'Elements with indices 4 and 5 will be ignored.'.format(node.soft_get('name', node.id)),\n extra={'is_warning': True})\n\n cropped_im_info = create_op_with_const_inputs(graph, StridedSlice, {1: mo_array([0, 0], dtype=np.int32),\n 2: mo_array([1, 3], dtype=np.int32),\n 3: mo_array([1, 1], dtype=np.int32)},\n {'name': 'cropped_im_info',\n 'begin_mask': int64_array([1, 1]),\n 'end_mask': int64_array([1, 1]),\n 'new_axis_mask': int64_array([0, 0]),\n 'shrink_axis_mask': int64_array([0, 0]),\n 'ellipsis_mask': int64_array([0, 0]),\n 'override_output_shape': True,\n })\n\n node.in_port(2).get_connection().insert_node(cropped_im_info)\n\n # update the im_info_shape so the next 'if' statement become true\n im_info_shape = int64_array([1, 3])\n\n if np.array_equal(im_info_shape, [1, 3]) or np.array_equal(im_info_shape, [1, 4]):\n reshape = create_op_node_with_second_input(graph, Reshape, [im_info_shape[1]], {'name': 'im_info/Reshape'})\n node.in_port(2).get_connection().set_destination(reshape.in_port(0))\n reshape.out_port(0).connect(node.in_port(2))\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\nimport pytest\n\nimport ngraph as ng\nfrom ngraph.impl import Shape, Type\nfrom tests_compatibility.runtime import get_runtime\nfrom tests_compatibility.test_ngraph.util import run_op_node\n\n\[email protected](\n \"ng_api_fn, numpy_fn, range_start, range_end\",\n [\n (ng.absolute, np.abs, -1, 1),\n (ng.abs, np.abs, -1, 1),\n (ng.acos, np.arccos, -1, 1),\n (ng.acosh, np.arccosh, 1, 2),\n (ng.asin, np.arcsin, -1, 1),\n (ng.asinh, np.arcsinh, -1, 1),\n (ng.atan, np.arctan, -100.0, 100.0),\n (ng.atanh, np.arctanh, 0.0, 1.0),\n (ng.ceiling, np.ceil, -100.0, 100.0),\n (ng.ceil, np.ceil, -100.0, 100.0),\n (ng.cos, np.cos, -100.0, 100.0),\n (ng.cosh, np.cosh, -100.0, 100.0),\n (ng.exp, np.exp, -100.0, 100.0),\n (ng.floor, np.floor, -100.0, 100.0),\n (ng.log, np.log, 0, 100.0),\n (ng.relu, lambda x: np.maximum(0, x), -100.0, 100.0),\n (ng.sign, np.sign, -100.0, 100.0),\n (ng.sin, np.sin, -100.0, 100.0),\n (ng.sinh, np.sinh, -100.0, 100.0),\n (ng.sqrt, np.sqrt, 0.0, 100.0),\n (ng.tan, np.tan, -1.0, 1.0),\n (ng.tanh, np.tanh, -100.0, 100.0),\n ],\n)\ndef test_unary_op_array(ng_api_fn, numpy_fn, range_start, range_end):\n np.random.seed(133391)\n input_data = (range_start + np.random.rand(2, 3, 4) * (range_end - range_start)).astype(np.float32)\n expected = numpy_fn(input_data)\n\n result = run_op_node([input_data], ng_api_fn)\n assert np.allclose(result, expected, rtol=0.001)\n\n\[email protected](\n \"ng_api_fn, numpy_fn, input_data\",\n [\n pytest.param(ng.absolute, np.abs, np.float32(-3)),\n pytest.param(ng.abs, np.abs, np.float32(-3)),\n pytest.param(ng.acos, np.arccos, np.float32(-0.5)),\n pytest.param(ng.asin, np.arcsin, np.float32(-0.5)),\n pytest.param(ng.atan, np.arctan, np.float32(-0.5)),\n pytest.param(ng.ceiling, np.ceil, np.float32(1.5)),\n pytest.param(ng.ceil, np.ceil, np.float32(1.5)),\n pytest.param(ng.cos, np.cos, np.float32(np.pi / 4.0)),\n pytest.param(ng.cosh, np.cosh, np.float32(np.pi / 4.0)),\n pytest.param(ng.exp, np.exp, np.float32(1.5)),\n pytest.param(ng.floor, np.floor, np.float32(1.5)),\n pytest.param(ng.log, np.log, np.float32(1.5)),\n pytest.param(ng.relu, lambda x: np.maximum(0, x), np.float32(-0.125)),\n pytest.param(ng.sign, np.sign, np.float32(0.0)),\n pytest.param(ng.sin, np.sin, np.float32(np.pi / 4.0)),\n pytest.param(ng.sinh, np.sinh, np.float32(0.0)),\n pytest.param(ng.sqrt, np.sqrt, np.float32(3.5)),\n pytest.param(ng.tan, np.tan, np.float32(np.pi / 4.0)),\n pytest.param(ng.tanh, np.tanh, np.float32(0.1234)),\n ],\n)\ndef test_unary_op_scalar(ng_api_fn, numpy_fn, input_data):\n expected = numpy_fn(input_data)\n\n result = run_op_node([input_data], ng_api_fn)\n assert np.allclose(result, expected)\n\n\[email protected](\n \"input_data\", [(np.array([True, False, True, False])), (np.array([True])), (np.array([False]))]\n)\ndef test_logical_not(input_data):\n expected = np.logical_not(input_data)\n\n result = run_op_node([input_data], ng.logical_not)\n assert np.allclose(result, expected)\n\n\ndef test_sigmoid():\n input_data = np.array([-3.14, -1.0, 0.0, 2.71001, 1000.0], dtype=np.float32)\n result = run_op_node([input_data], ng.sigmoid)\n\n def sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x))\n\n expected = np.array(list(map(sigmoid, input_data)))\n\n assert np.allclose(result, expected)\n\n\ndef test_softmax_positive_axis():\n axis = 1\n input_tensor = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)\n\n result = run_op_node([input_tensor], ng.softmax, axis)\n\n expected = [[0.09003056, 0.24472842, 0.6652409], [0.09003056, 0.24472842, 0.6652409]]\n\n assert np.allclose(result, expected)\n\n\ndef test_softmax_negative_axis():\n axis = -1\n input_tensor = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)\n\n result = run_op_node([input_tensor], ng.softmax, axis)\n\n expected = [[0.09003056, 0.24472842, 0.6652409], [0.09003056, 0.24472842, 0.6652409]]\n\n assert np.allclose(result, expected)\n\n\ndef test_erf():\n input_tensor = np.array([-1.0, 0.0, 1.0, 2.5, 3.14, 4.0], dtype=np.float32)\n expected = [-0.842701, 0.0, 0.842701, 0.999593, 0.999991, 1.0]\n\n result = run_op_node([input_tensor], ng.erf)\n assert np.allclose(result, expected)\n\n\ndef test_hswish():\n float_dtype = np.float32\n data = ng.parameter(Shape([3, 10]), dtype=float_dtype, name=\"data\")\n\n node = ng.hswish(data)\n assert node.get_type_name() == \"HSwish\"\n assert node.get_output_size() == 1\n assert list(node.get_output_shape(0)) == [3, 10]\n assert node.get_output_element_type(0) == Type.f32\n\n\ndef test_round_even():\n float_dtype = np.float32\n data = ng.parameter(Shape([3, 10]), dtype=float_dtype, name=\"data\")\n\n node = ng.round(data, \"HALF_TO_EVEN\")\n assert node.get_type_name() == \"Round\"\n assert node.get_output_size() == 1\n assert list(node.get_output_shape(0)) == [3, 10]\n assert node.get_output_element_type(0) == Type.f32\n\n input_tensor = np.array([-2.5, -1.5, -0.5, 0.5, 0.9, 1.5, 2.3, 2.5, 3.5], dtype=np.float32)\n expected = [-2.0, -2.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 4.0]\n\n result = run_op_node([input_tensor], ng.round, \"HALF_TO_EVEN\")\n assert np.allclose(result, expected)\n\n\ndef test_round_away():\n float_dtype = np.float32\n data = ng.parameter(Shape([3, 10]), dtype=float_dtype, name=\"data\")\n\n node = ng.round(data, \"HALF_AWAY_FROM_ZERO\")\n assert node.get_type_name() == \"Round\"\n assert node.get_output_size() == 1\n assert list(node.get_output_shape(0)) == [3, 10]\n assert node.get_output_element_type(0) == Type.f32\n\n input_tensor = np.array([-2.5, -1.5, -0.5, 0.5, 0.9, 1.5, 2.3, 2.5, 3.5], dtype=np.float32)\n expected = [-3.0, -2.0, -1.0, 1.0, 1.0, 2.0, 2.0, 3.0, 4.0]\n\n result = run_op_node([input_tensor], ng.round, \"HALF_AWAY_FROM_ZERO\")\n assert np.allclose(result, expected)\n\n\ndef test_hsigmoid():\n float_dtype = np.float32\n data = ng.parameter(Shape([3, 10]), dtype=float_dtype, name=\"data\")\n\n node = ng.hsigmoid(data)\n assert node.get_type_name() == \"HSigmoid\"\n assert node.get_output_size() == 1\n assert list(node.get_output_shape(0)) == [3, 10]\n assert node.get_output_element_type(0) == Type.f32\n\n\ndef test_gelu_operator_with_parameters():\n runtime = get_runtime()\n\n data_value = np.array([[-5, 1], [-2, 3]], dtype=np.float32)\n\n data_shape = [2, 2]\n parameter_data = ng.parameter(data_shape, name=\"Data\", dtype=np.float32)\n\n model = ng.gelu(parameter_data, \"erf\")\n computation = runtime.computation(model, parameter_data)\n\n result = computation(data_value)\n expected = np.array([[-1.6391277e-06, 8.4134471e-01], [-4.5500278e-02, 2.9959502]], dtype=np.float32)\n assert np.allclose(result, expected, 1e-6, 1e-6)\n\n\ndef test_gelu_operator_with_array():\n runtime = get_runtime()\n\n data_value = np.array([[-5, 1], [-2, 3]], dtype=np.float32)\n\n model = ng.gelu(data_value, \"erf\")\n computation = runtime.computation(model)\n\n result = computation()\n expected = np.array([[-1.6391277e-06, 8.4134471e-01], [-4.5500278e-02, 2.9959502]], dtype=np.float32)\n assert np.allclose(result, expected, 1e-6, 1e-6)\n\n\ndef test_gelu_tanh_operator_with_parameters():\n runtime = get_runtime()\n\n data_value = np.array([[-5, 1], [-2, 3]], dtype=np.float32)\n\n data_shape = [2, 2]\n parameter_data = ng.parameter(data_shape, name=\"Data\", dtype=np.float32)\n\n model = ng.gelu(parameter_data, \"tanh\")\n computation = runtime.computation(model, parameter_data)\n\n result = computation(data_value)\n expected = np.array([[0.0, 0.841192], [-0.04540223, 2.9963627]], dtype=np.float32)\n assert np.allclose(result, expected, 1e-6, 1e-6)\n\n\ndef test_gelu_tanh_operator_with_array():\n runtime = get_runtime()\n\n data_value = np.array([[-5, 1], [-2, 3]], dtype=np.float32)\n\n model = ng.gelu(data_value, \"tanh\")\n computation = runtime.computation(model)\n\n result = computation()\n expected = np.array([[0.0, 0.841192], [-0.04540223, 2.9963627]], dtype=np.float32)\n\n assert np.allclose(result, expected, 1e-6, 1e-6)\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport logging as log\n\nimport numpy as np\n\nfrom openvino.tools.mo.ops.elementwise import Mul, Add\nfrom openvino.tools.mo.front.common.partial_infer.utils import mo_array\nfrom openvino.tools.mo.front.tf.graph_utils import create_op_node_with_second_input\nfrom openvino.tools.mo.graph.graph import Graph\nfrom openvino.tools.mo.graph.port import Port\nfrom openvino.tools.mo.ops.const import Const\nfrom openvino.tools.mo.ops.reshape import Reshape\n\n\ndef expand_node_shape(port: Port, broadcast_dims_cnt):\n value = mo_array(port.data.get_value())\n for idx in range(broadcast_dims_cnt):\n value = np.expand_dims(value, axis=-1)\n port.data.set_value(value)\n\n\ndef convert_batch_norm(graph: Graph):\n \"\"\"\n This function finds FusedBatchNorm layer (or BatchNorm for MXNet) and replaces with Mul->Add->Mul->Add sequence.\n \"\"\"\n nodes = graph.get_op_nodes()\n for node in nodes:\n if node.has_valid('op') and (node.op in ['FusedBatchNorm', 'FusedBatchNormV2', 'FusedBatchNormV3',\n 'BatchNorm', 'BatchNormalization', 'batchNormInference']):\n\n if any([node.in_port(i).data.get_value() is None for i in range(1, len(node.in_ports()))]):\n log.warning('Cannot translate FusedBatchNorm {} node with non-constant weights'.format(\n node.name if node.has_valid('name') else '<UNKNOWN>'))\n continue\n\n const = node.in_port(1).get_source()\n node.in_port(1).disconnect()\n\n beta = node.in_port(2).get_source()\n node.in_port(2).disconnect()\n\n mean = node.in_port(3).get_source()\n node.in_port(3).disconnect()\n\n variance = node.in_port(4).get_source()\n node.in_port(4).disconnect()\n\n eps = node.eps\n\n if node.has_valid('fix_gamma') and node.fix_gamma:\n const.data.get_value().fill(1.)\n\n can_be_fused = False if not node.soft_get('can_be_fused') else True\n\n scale = 1. / np.sqrt(variance.data.get_value() + eps)\n shift = (mean.data.get_value() * (-1)) * scale\n\n # Expand dims for current layout\n broadcast_dims_cnt = len(node.in_port(0).data.get_shape()) - 2 if graph.graph['layout'] == 'NCHW' else 0\n\n # Update values and shapes with new shape\n expand_node_shape(const, broadcast_dims_cnt)\n expand_node_shape(beta, broadcast_dims_cnt)\n\n for idx in range(broadcast_dims_cnt):\n scale = np.expand_dims(scale, axis=-1)\n shift = np.expand_dims(shift, axis=-1)\n\n _fused_batch_norm_decomposition(graph, node.in_port(0), node.out_port(0), const, beta, scale, shift, can_be_fused)\n\n\ndef _fused_batch_norm_decomposition(graph: Graph, tinput: Port, toutput: Port, gamma: Port, beta: Port,\n mean: np.ndarray, variance: np.ndarray, can_be_fused=True):\n \"\"\"\n This is common function for TF, Caffe and MXNet\n It creates Mul->Add->Mul->Add sub graph\n \"\"\"\n batch_norm_name = tinput.get_connection().get_destination().node.name\n\n # Create first Mul & Add operations\n mul1_node = Mul(graph, dict(name=batch_norm_name + \"/mean\", can_be_fused=can_be_fused)).create_node()\n add1_node = Add(graph, dict(name=batch_norm_name + \"/variance\", can_be_fused=can_be_fused)).create_node()\n\n const_mul1_node = Const(graph, dict(name=\"data_mul_\", value=mo_array(mean))).create_node()\n const_add1_node = Const(graph, dict(name=\"data_add_\", value=mo_array(variance))).create_node()\n\n # Broadcast const from scalar\n # We can broadcast only when const.value is scalar\n if gamma.data.get_shape()[0] != gamma.data.get_value().shape[0]:\n value = gamma.data.get_value()\n value.resize(gamma.data.get_shape()).fill(value[0])\n gamma.data.set_value(value)\n\n # Create second Mul & Add\n mul2_node = Mul(graph, dict(name=batch_norm_name + \"/gamma\", can_be_fused=can_be_fused)).create_node()\n add2_node = Add(graph, dict(name=batch_norm_name + \"/beta\", can_be_fused=can_be_fused)).create_node()\n\n # Connect edges Mul1->Add1->Mul2->Add2\n tinput.get_connection().set_destination(mul1_node.in_port(0))\n mul1_node.in_port(1).get_connection().set_source(const_mul1_node.out_port(0))\n\n add1_node.in_port(0).get_connection().set_source(mul1_node.out_port(0))\n add1_node.in_port(1).get_connection().set_source(const_add1_node.out_port(0))\n\n mul2_node.in_port(0).get_connection().set_source(add1_node.out_port(0))\n gamma.get_connection().set_destination(mul2_node.in_port(1))\n\n add2_node.in_port(0).get_connection().set_source(mul2_node.out_port(0))\n beta.get_connection().set_destination(add2_node.in_port(1))\n\n toutput.get_connection().set_source(add2_node.out_port(0))\n\n\ndef convert_scale_shift_to_mul_add(graph: Graph):\n nodes = graph.get_op_nodes(op='ScaleShift')\n for node in nodes:\n if node.soft_get('can_be_fused') is False:\n continue\n\n ports_count = len(node.in_ports())\n\n input_port = node.in_port(0)\n scale_port = node.in_port(1) if ports_count > 1 and not node.in_port(1).disconnected() else None\n shift_port = node.in_port(2) if ports_count > 2 and not node.in_port(2).disconnected() else None\n output_port = node.out_port(0)\n\n has_biases = True\n has_weights = True\n\n # We don't need zero biases\n if shift_port is None or (shift_port.data.get_value() is not None and all([x == 0 for x in shift_port.data.get_value()])):\n has_biases = False\n\n # We don't need weights with ones\n if scale_port is None or (scale_port.data.get_value() is not None and all([x == 1 for x in scale_port.data.get_value()])):\n has_weights = False\n\n mul_op = Mul(graph, dict(name=node.name + \"/Mul_\"))\n add_op = Add(graph, dict(name=node.name + \"/Add_\"))\n\n # Expand dims for current layout\n broadcast_dims_cnt = len(input_port.data.get_shape()) - 2 if graph.graph['layout'] == 'NCHW' else 0\n\n # In case if we have constant weights/biases we have to broadcast them according to graph layout\n # otherwise we insert Reshape with broadcast dim attribute.\n def broadcast_value(port):\n value = mo_array(port.data.get_value())\n for idx in range(broadcast_dims_cnt):\n value = np.expand_dims(value, axis=-1)\n port.data.set_value(value)\n\n def broadcast_with_reshape(port):\n input_shape = input_port.data.get_shape()\n reshape_dims = np.zeros(len(input_shape), dtype=np.int64)\n for i in range(0, node.axis):\n reshape_dims[i] = 1\n data_shape = port.data.get_shape()\n for i in range(node.axis, node.axis + len(data_shape)):\n reshape_dims[i] = data_shape[i - node.axis]\n for i in range(node.axis + len(data_shape), len(input_shape)):\n reshape_dims[i] = 1\n reshape = create_op_node_with_second_input(graph, Reshape, reshape_dims,\n dict(name=port.node.name + \"/Broadcast_\"))\n port.get_connection().set_destination(reshape.in_port(0))\n reshape.out_port(0).connect(port)\n\n if has_weights and scale_port.data.get_value() is not None:\n broadcast_value(scale_port)\n elif has_weights:\n broadcast_with_reshape(scale_port)\n\n if has_biases and shift_port.data.get_value() is not None:\n broadcast_value(shift_port)\n elif has_biases:\n broadcast_with_reshape(shift_port)\n\n if has_biases and has_weights:\n # Connect input->mul->out->add->out\n add_node = add_op.create_node()\n mul_node = mul_op.create_node()\n\n # Connect Mul operation with inputs\n input_port.get_connection().set_destination(mul_node.in_port(0))\n scale_port.get_connection().set_destination(mul_node.in_port(1))\n\n # Connect Add operation with inputs\n mul_node.out_port(0).connect(add_node.in_port(0))\n shift_port.get_connection().set_destination(add_node.in_port(1))\n\n output_port.get_connection().set_source(add_node.out_port(0))\n elif has_weights:\n # Connect input->mul->out\n mul_node = mul_op.create_node()\n\n # Connect Mul operation with inputs\n input_port.get_connection().set_destination(mul_node.in_port(0))\n scale_port.get_connection().set_destination(mul_node.in_port(1))\n\n output_port.get_connection().set_source(mul_node.out_port(0))\n elif has_biases:\n # Connect input->add->out\n add_node = add_op.create_node()\n\n # Connect Add operation with inputs\n input_port.get_connection().set_destination(add_node.in_port(0))\n shift_port.get_connection().set_destination(add_node.in_port(1))\n\n output_port.get_connection().set_source(add_node.out_port(0))\n else:\n # Connect input->out\n producer_port = input_port.get_source()\n input_port.disconnect()\n output_port.get_connection().set_source(producer_port)", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport unittest\n\nimport numpy as np\nfrom generator import generator, generate\n\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array, mo_array, is_fully_defined, dynamic_dimension_value, \\\n dynamic_dimension, shape_array, compatible_shapes, shape_delete, shape_insert, strict_compare_tensors\nfrom openvino.tools.mo.utils.error import Error\n\n\ndef gen_masked_array(array, masked_indices):\n \"\"\"\n Creates a masked array from the input array by masking specific elements.\n\n :param array: the input array\n :param masked_indices: element indices to be masked\n :return: the result masked array\n \"\"\"\n res = np.ma.masked_array(array)\n for index in masked_indices:\n res[index] = np.ma.masked\n return res\n\n\n@generator\nclass IsFullyDefinedTest(unittest.TestCase):\n @generate(*[(None, False),\n (int64_array([2, 3, 5, 7]), True), # int64 array with valid values\n (np.array([2, 3, 5, 7]), True), # any numpy array with valid values\n (np.array([2, dynamic_dimension_value]), True), # array with dynamic dimension value is fully defined!\n (shape_array([2, dynamic_dimension_value, 5]), False), # masked array with at least one masked element\n (shape_array([2, 4, 5]), True), # masked array with no masked elements is fully defined\n (dynamic_dimension, False), # dynamic dimension is not fully defined\n (dynamic_dimension_value, True), # dynamic dimension value is fully defined\n ((dynamic_dimension_value, dynamic_dimension_value), True), # list with dynamic dimension values is\n # fully defined\n ((dynamic_dimension, 1), False), # tuple with dynamic dimension is not fully defined\n ([dynamic_dimension, 1], False), # list with dynamic dimension is not fully defined\n ])\n def test_is_fully_defined(self, data, result):\n self.assertEqual(is_fully_defined(data), result)\n\n\n@generator\nclass ShapeArrayTest(unittest.TestCase):\n @generate(*[([1], shape_array([1]), True),\n # if we provide a list with dynamic_dimension_value then it is converted to dynamic dimension\n ([dynamic_dimension_value, 5], gen_masked_array([1, 5], [0]), True),\n # if we provide a list with dynamic_dimension then the generated shape array still have it\n ([7, dynamic_dimension], gen_masked_array([7, 1], [1]), True),\n # negative test to make sure that np.ma.allequal works properly\n ([2], gen_masked_array([1], []), False),\n ])\n def test_shape_array(self, data, ref, result):\n self.assertEqual(strict_compare_tensors(shape_array(data), ref), result)\n\n\n@generator\nclass CompareShapesTest(unittest.TestCase):\n @generate(*[(gen_masked_array([1, 2, 3], []), gen_masked_array([1, 2, 3], []), True),\n (gen_masked_array([4, 2, 3], []), gen_masked_array([1, 2, 3], []), False),\n (gen_masked_array([1, 2], []), gen_masked_array([1, 2, 3], []), False),\n (gen_masked_array([1, 2, 3], []), gen_masked_array([1, 2], []), False),\n (gen_masked_array([1, 2, 3], [1]), gen_masked_array([1, 5, 3], [1]), True), # [1, d, 3] vs [1, d, 3]\n (gen_masked_array([1, 2, 3], [2]), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, d] vs [1, d, 3]\n (gen_masked_array([1, 2, 3], []), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, 3] vs [1, d, 3]\n (gen_masked_array([1, 2, 3], [0]), gen_masked_array([1, 5, 3], []), False), # [d, 2, 3] vs [1, 5, 3]\n (np.array([1, 2, 3]), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, 3] vs [1, d, 3]\n (np.array([1, 2]), gen_masked_array([1, 5, 3], [1]), False),\n (np.array([1, 2]), np.array([1, 2]), True),\n (np.array([1, 2]), np.array([3, 2]), False),\n ])\n def test_compare_shapes(self, input1, input2, result):\n self.assertEqual(compatible_shapes(input1, input2), result)\n\n\n@generator\nclass ShapeDeleteTest(unittest.TestCase):\n @generate(*[(gen_masked_array([1, 2, 3], []), [], gen_masked_array([1, 2, 3], [])),\n # [1, d, 3] -> [d, 3]. Indices input is a list\n (gen_masked_array([1, 2, 3], [1]), [0], gen_masked_array([2, 3], [0])),\n # [1, d, 3] -> [d, 3]. Indices input is a numpy array\n (gen_masked_array([1, 2, 3], [1]), np.array([0]), gen_masked_array([2, 3], [0])),\n # [1, d, 3] -> [d, 3]. Indices input is a masked array\n (gen_masked_array([1, 2, 3], [1]), gen_masked_array([0], []), gen_masked_array([2, 3], [0])),\n # [1, d, 3] -> [d, 3]. Indices input is a numpy array with scalar\n (gen_masked_array([1, 2, 3], [1]), np.array(0), gen_masked_array([2, 3], [0])),\n # [1, d, 3] -> [d, 3]. Indices input is an integer\n (gen_masked_array([1, 2, 3], [1]), 0, gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3]\n (gen_masked_array([1, 2, 3, 4], [1]), [0, 2], gen_masked_array([2, 4], [0])), # [1, d, 3, 4] -> [d, 4]\n (gen_masked_array([1, 2, 3], [1]), [0, 2, 1], gen_masked_array([], [])), # [1, d, 3] -> []\n (gen_masked_array([1, 2, 3], [1]), [0, 2], gen_masked_array([2], [0])), # [1, d, 3] -> [d]\n # [1, d, d, 4] -> [d, d]\n (gen_masked_array([1, 2, 3, 4], [1, 2]), [3, 0], gen_masked_array([2, 3], [0, 1])),\n (gen_masked_array([1, 2, 3, 4], [2]), 3, gen_masked_array([1, 2, 3], [2])), # [1, 2, d, 4] -> [1, 2, d]\n ([1, 2, 3, 4], [1], [1, 3, 4]), # [1, 2, 3, 4] -> [1, 3, 4]. Input is a regular lists\n (np.array([1, 2, 3, 4]), [1], [1, 3, 4]), # [1, 2, 3, 4] -> [1, 3, 4]. Input is a regular arrays\n (np.array([1, 2, 3, 4]), [-1, -3], [1, 3]), # [1, 2, 3, 4] -> [1, 3]. Negative indices\n (np.array([1, 2, 3, 4]), -2, [1, 2, 4]), # [1, 2, 3, 4] -> [1, 2, 4]. Negative index\n ])\n def test_shape_delete(self, shape, indices, result):\n self.assertTrue(strict_compare_tensors(shape_delete(shape, indices), result))\n\n def test_shape_delete_raise_exception(self):\n with self.assertRaisesRegex(Error, '.*Incorrect parameter type.*'):\n shape_delete(gen_masked_array([1, 2, 3], []), {})\n\n\n@generator\nclass ShapeInsertTest(unittest.TestCase):\n @generate(*[(gen_masked_array([1, 2, 3], []), 1, [5], gen_masked_array([1, 5, 2, 3], [])),\n (gen_masked_array([1, 2, 3], [1]), 1, [5], gen_masked_array([1, 5, 2, 3], [2])),\n (gen_masked_array([1, 2, 3], [1]), 1, [dynamic_dimension], gen_masked_array([1, 5, 2, 3], [1, 2])),\n (gen_masked_array([1, 2, 3], [1]), 0, [dynamic_dimension], gen_masked_array([5, 1, 2, 3], [0, 2])),\n (gen_masked_array([1, 2, 3], [1]), np.int64(0), [dynamic_dimension],\n gen_masked_array([5, 1, 2, 3], [0, 2])),\n (gen_masked_array([1, 2, 3], [1]), 3, [dynamic_dimension], gen_masked_array([1, 2, 3, 5], [1, 3])),\n (gen_masked_array([1, 2, 3], [1]), 3, [dynamic_dimension, dynamic_dimension],\n gen_masked_array([1, 2, 3, 5, 6], [1, 3, 4])),\n (gen_masked_array([1], [0]), 0, [7, dynamic_dimension], gen_masked_array([7, 5, 2], [1, 2])),\n ])\n def test_shape_insert(self, shape, pos, values, result):\n self.assertTrue(strict_compare_tensors(shape_insert(shape, pos, values), result))\n\n def test_shape_insert_raise_exception(self):\n with self.assertRaisesRegex(Error, '.*Incorrect parameter type.*'):\n shape_insert(gen_masked_array([1, 2, 3], []), 2, {})\n\n\n@generator\nclass mo_array_test(unittest.TestCase):\n @generate(*[(mo_array([2, 3, 5, 7]), np.array([2, 3, 5, 7])),\n (mo_array([2., 3., 5., 7.], dtype=np.float64), np.array([2., 3., 5., 7.])),\n (mo_array([2., 3., 5., 7.]), np.array([2., 3., 5., 7.], dtype=np.float32)),\n ])\n def test_mo_array_positive(self, data, result):\n self.assertEqual(data.dtype, result.dtype)\n\n @generate(*[(mo_array([2., 3., 5., 7.]), np.array([2., 3., 5., 7.])),\n ])\n def test_mo_array_negative(self, data, result):\n self.assertNotEqual(data.dtype, result.dtype)\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport unittest\n\nimport numpy as np\n\nfrom openvino.tools.mo.ops.unique import Unique\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array\nfrom openvino.tools.mo.graph.graph import Node\nfrom unit_tests.utils.graph import build_graph\n\n# graph 1 with two outputs: uniques and indices\nnodes_attributes = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'unique_node': {'op': 'Unique', 'kind': 'op'},\n 'output_uniques': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_indices': {'shape': None, 'value': None, 'kind': 'data'},\n }\nedges1 = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0}),\n ('unique_node', 'output_indices', {'out': 1})]\ninputs1 = {'input': {'shape': int64_array([20]), 'value': None},\n 'unique_node': {\n 'sorted': 'false',\n 'return_inverse': 'true',\n 'return_counts': 'false'\n }\n }\n\n# graph 2 with three outputs: uniques, indices and counts\nnodes_attributes2 = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'unique_node': {'op': 'Unique', 'kind': 'op'},\n 'output_uniques': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_counts': {'shape': None, 'value': None, 'kind': 'data'}\n }\nedges2 = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0}),\n ('unique_node', 'output_indices', {'out': 1}),\n ('unique_node', 'output_counts', {'out': 2})]\ninputs2 = {'input': {'shape': int64_array([20]), 'value': None},\n 'unique_node': {\n 'sorted': 'false',\n 'return_inverse': 'true',\n 'return_counts': 'true'\n }\n }\n\n\nclass TestUnique(unittest.TestCase):\n # case 1: a graph with two outputs: uniques and indices\n def test_partial_infer1(self):\n graph = build_graph(nodes_attributes, edges1, inputs1)\n\n unique_node = Node(graph, 'unique_node')\n Unique.infer(unique_node)\n\n # prepare reference results\n ref_output_uniques_shape = int64_array([20])\n ref_output_indices_shape = int64_array([20])\n\n # get resulted shapes\n res_output_uniques_shape = graph.node['output_uniques']['shape']\n res_output_indices_shape = graph.node['output_indices']['shape']\n\n self.assertTrue(np.array_equal(ref_output_uniques_shape, res_output_uniques_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_uniques_shape, res_output_uniques_shape))\n\n self.assertTrue(np.array_equal(ref_output_indices_shape, res_output_indices_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_indices_shape, res_output_indices_shape))\n\n # case 2: a graph with three outputs: uniques, indices and counts\n def test_partial_infer2(self):\n graph = build_graph(nodes_attributes2, edges2, inputs2)\n\n unique_node = Node(graph, 'unique_node')\n Unique.infer(unique_node)\n\n # prepare reference results\n ref_output_uniques_shape = int64_array([20])\n ref_output_indices_shape = int64_array([20])\n ref_output_counts_shape = int64_array([20])\n\n # get resulted shapes\n res_output_uniques_shape = graph.node['output_uniques']['shape']\n res_output_indices_shape = graph.node['output_indices']['shape']\n res_output_counts_shape = graph.node['output_counts']['shape']\n\n self.assertTrue(np.array_equal(ref_output_uniques_shape, res_output_uniques_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_uniques_shape, res_output_uniques_shape))\n\n self.assertTrue(np.array_equal(ref_output_indices_shape, res_output_indices_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_indices_shape, res_output_indices_shape))\n\n self.assertTrue(np.array_equal(ref_output_counts_shape, res_output_counts_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_counts_shape, res_output_counts_shape))\n\n # case 3: a graph with just unique output\n def test_partial_infer_just_unique(self):\n edges = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0})]\n graph = build_graph(nodes_attributes, edges, inputs1)\n\n unique_node = Node(graph, 'unique_node')\n Unique.infer(unique_node)\n\n # prepare reference results\n ref_output_uniques_shape = int64_array([20])\n\n # get resulted shapes\n res_output_uniques_shape = graph.node['output_uniques']['shape']\n\n self.assertTrue(np.array_equal(ref_output_uniques_shape, res_output_uniques_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_uniques_shape, res_output_uniques_shape))\n\n # case 4: an invalid graph with 2D input\n def test_incorrect_input_shape(self):\n inputs = {'input': {'shape': int64_array([20, 2]), 'value': None}}\n\n graph = build_graph(nodes_attributes, edges1, inputs)\n\n unique_node = Node(graph, 'unique_node')\n self.assertRaises(AssertionError, Unique.infer, unique_node)\n\n # case 5: an invalid graph with return_counts = false and three outputs\n def test_more_output_ports(self):\n nodes_attributes1 = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'unique_node': {'op': 'Unique', 'kind': 'op'},\n 'output_uniques': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'output3': {'shape': None, 'value': None, 'kind': 'data'},\n }\n edges = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0}),\n ('unique_node', 'output_indices', {'out': 1}),\n ('unique_node', 'output3', {'out': 2})]\n graph = build_graph(nodes_attributes1, edges, inputs1)\n\n unique_node = Node(graph, 'unique_node')\n self.assertRaises(AssertionError, Unique.infer, unique_node)\n\n # case 6: an invalid graph without unique output\n def test_no_uniques_output(self):\n edges = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_indices', {'out': 1})]\n graph = build_graph(nodes_attributes, edges, inputs1)\n\n unique_node = Node(graph, 'unique_node')\n self.assertRaises(AssertionError, Unique.infer, unique_node)\n\n # case 7: infer for constant input\n # graph with a constant input, three outputs, sorted = 'false'\n def test_constant_input(self):\n nodes_attributes_ = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'unique_node': {'op': 'Unique', 'kind': 'op'},\n 'output_uniques': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_counts': {'shape': None, 'value': None, 'kind': 'data'}\n }\n edges_ = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0}),\n ('unique_node', 'output_indices', {'out': 1}),\n ('unique_node', 'output_counts', {'out': 2})]\n inputs_ = {'input': {'shape': int64_array([10]),\n 'value': np.array([8.0, 1.0, 2.0, 1.0, 8.0, 5.0, 1.0, 5.0, 0.0, 0.0], dtype=np.float)},\n 'unique_node': {\n 'sorted': 'false',\n 'return_inverse': 'true',\n 'return_counts': 'true'\n }\n }\n graph = build_graph(nodes_attributes_, edges_, inputs_)\n unique_node = Node(graph, 'unique_node')\n Unique.infer(unique_node)\n\n # prepare reference results\n ref_output_uniques_shape = int64_array([5])\n ref_output_uniques_value = np.array([8.0, 1.0, 2.0, 5.0, 0.0], dtype=np.float)\n ref_output_indices_shape = int64_array([10])\n ref_output_indices_value = np.array([0.0, 1.0, 2.0, 1.0, 0.0, 3.0, 1.0, 3.0, 4.0, 4.0], dtype=np.float)\n ref_output_counts_shape = int64_array([5])\n ref_output_counts_value = np.array([2.0, 3.0, 1.0, 2.0, 2.0], dtype=np.float)\n\n # get resulted shapes\n res_output_uniques_shape = graph.node['output_uniques']['shape']\n res_output_uniques_value = graph.node['output_uniques']['value']\n res_output_indices_shape = graph.node['output_indices']['shape']\n res_output_indices_value = graph.node['output_indices']['value']\n res_output_counts_shape = graph.node['output_counts']['shape']\n res_output_counts_value = graph.node['output_counts']['value']\n\n # verify the results\n self.assertTrue(np.array_equal(ref_output_uniques_shape, res_output_uniques_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_uniques_shape, res_output_uniques_shape))\n self.assertTrue(np.array_equal(ref_output_uniques_value, res_output_uniques_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_uniques_value, res_output_uniques_value))\n self.assertTrue(np.array_equal(ref_output_indices_shape, res_output_indices_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_indices_shape, res_output_indices_shape))\n self.assertTrue(np.array_equal(ref_output_indices_value, res_output_indices_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_indices_value, res_output_indices_value))\n self.assertTrue(np.array_equal(ref_output_counts_shape, res_output_counts_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_counts_shape, res_output_counts_shape))\n self.assertTrue(np.array_equal(ref_output_counts_value, res_output_counts_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_counts_value, res_output_counts_value))\n\n # case 8: infer for constant input\n # graph with a constant input, three outputs, sorted = 'true'\n def test_constant_input(self):\n nodes_attributes_ = {'input': {'shape': None, 'value': None, 'kind': 'data'},\n 'unique_node': {'op': 'Unique', 'kind': 'op'},\n 'output_uniques': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_indices': {'shape': None, 'value': None, 'kind': 'data'},\n 'output_counts': {'shape': None, 'value': None, 'kind': 'data'}\n }\n edges_ = [('input', 'unique_node', {'in': 0}),\n ('unique_node', 'output_uniques', {'out': 0}),\n ('unique_node', 'output_indices', {'out': 1}),\n ('unique_node', 'output_counts', {'out': 2})]\n inputs_ = {'input': {'shape': int64_array([10]),\n 'value': np.array([8.0, 1.0, 2.0, 1.0, 8.0, 5.0, 1.0, 5.0, 0.0, 0.0], dtype=np.float)},\n 'unique_node': {\n 'sorted': 'true',\n 'return_inverse': 'true',\n 'return_counts': 'true'\n }\n }\n graph = build_graph(nodes_attributes_, edges_, inputs_)\n unique_node = Node(graph, 'unique_node')\n Unique.infer(unique_node)\n\n # prepare reference results\n ref_output_uniques_shape = int64_array([5])\n ref_output_uniques_value = np.array([0.0, 1.0, 2.0, 5.0, 8.0], dtype=np.float)\n ref_output_indices_shape = int64_array([10])\n ref_output_indices_value = np.array([4.0, 1.0, 2.0, 1.0, 4.0, 3.0, 1.0, 3.0, 0.0, 0.0], dtype=np.float)\n ref_output_counts_shape = int64_array([5])\n ref_output_counts_value = np.array([2.0, 3.0, 1.0, 2.0, 2.0], dtype=np.float)\n\n # get resulted shapes\n res_output_uniques_shape = graph.node['output_uniques']['shape']\n res_output_uniques_value = graph.node['output_uniques']['value']\n res_output_indices_shape = graph.node['output_indices']['shape']\n res_output_indices_value = graph.node['output_indices']['value']\n res_output_counts_shape = graph.node['output_counts']['shape']\n res_output_counts_value = graph.node['output_counts']['value']\n\n # verify the results\n self.assertTrue(np.array_equal(ref_output_uniques_shape, res_output_uniques_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_uniques_shape, res_output_uniques_shape))\n self.assertTrue(np.array_equal(ref_output_uniques_value, res_output_uniques_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_uniques_value, res_output_uniques_value))\n self.assertTrue(np.array_equal(ref_output_indices_shape, res_output_indices_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_indices_shape, res_output_indices_shape))\n self.assertTrue(np.array_equal(ref_output_indices_value, res_output_indices_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_indices_value, res_output_indices_value))\n self.assertTrue(np.array_equal(ref_output_counts_shape, res_output_counts_shape),\n 'shapes do not match expected: {} and given: {}'.format(ref_output_counts_shape, res_output_counts_shape))\n self.assertTrue(np.array_equal(ref_output_counts_value, res_output_counts_value),\n 'values do not match expected: {} and given: {}'.format(ref_output_counts_value, res_output_counts_value))\n", "#!/usr/bin/env python3\n\n# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\" Test conditional compilation.\n\"\"\"\n\nimport glob\nimport logging\nimport os\nimport sys\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\nfrom proc_utils import cmd_exec # pylint: disable=import-error\n\nfrom test_utils import get_lib_sizes, infer_tool, make_build, run_infer # pylint: disable=import-error\n\nlog = logging.getLogger()\n\n\[email protected](name=\"cc_collect\")\ndef test_cc_collect(test_id, prepared_models, openvino_ref, test_info,\n save_session_info, sea_runtool, collector_dir, artifacts): # pylint: disable=unused-argument\n \"\"\"Test conditional compilation statistics collection\n :param test_info: custom `test_info` field of built-in `request` pytest fixture.\n contain a dictionary to store test metadata.\n \"\"\"\n out = artifacts / test_id\n infer_out_dir = out / \"inference_result\"\n test_info[\"test_id\"] = test_id\n\n # cleanup old data if any\n prev_result = glob.glob(f\"{out / test_id}.pid*.csv\")\n for path in prev_result:\n os.remove(path)\n # Create a directory for infer results, if it haven't done before\n infer_out_dir.mkdir(parents=True, exist_ok=True)\n # run use case\n return_code, output = cmd_exec(\n [\n sys.executable,\n str(sea_runtool),\n f\"--output={out / test_id}\",\n f\"--bindir={collector_dir}\",\n \"!\",\n sys.executable,\n infer_tool,\n *[f\"-m={model}\" for model in prepared_models],\n \"-d=CPU\",\n f\"-r={infer_out_dir}\"\n ]\n )\n out_csv = glob.glob(f\"{out / test_id}.pid*.csv\")\n test_info[\"out_csv\"] = out_csv\n\n assert return_code == 0, f\"Command exited with non-zero status {return_code}:\\n {output}\"\n assert len(out_csv) == 1, f'Multiple or none \"{out / test_id}.pid*.csv\" files'\n\n\[email protected](depends=[\"cc_collect\"])\ndef test_minimized_pkg(test_id, models, openvino_root_dir, artifacts): # pylint: disable=unused-argument\n \"\"\"Build and install OpenVINO package with collected conditional compilation statistics.\"\"\"\n out = artifacts / test_id\n install_prefix = out / \"install_pkg\"\n build_dir = openvino_root_dir / \"build_minimized\"\n\n out_csv = glob.glob(f\"{out / test_id}.pid*.csv\")\n assert len(out_csv) == 1, f'Multiple or none \"{out / test_id}.pid*.csv\" files'\n\n log.info(\"Building minimized build at %s\", build_dir)\n\n return_code, output = make_build(\n openvino_root_dir,\n build_dir,\n install_prefix,\n cmake_additional_args=[f\"-DSELECTIVE_BUILD_STAT={out_csv[0]}\"],\n log=log,\n )\n assert return_code == 0, f\"Command exited with non-zero status {return_code}:\\n {output}\"\n\n\[email protected](depends=[\"cc_collect\", \"minimized_pkg\"])\ndef test_infer(test_id, prepared_models, artifacts):\n \"\"\"Test inference with conditional compiled binaries.\"\"\"\n out = artifacts / test_id\n minimized_pkg = out / \"install_pkg\"\n infer_out_dir_cc = out / \"inference_result_cc/\"\n\n return_code, output = run_infer(prepared_models, infer_out_dir_cc, minimized_pkg)\n assert return_code == 0, f\"Command exited with non-zero status {return_code}:\\n {output}\"\n\n\[email protected](depends=[\"cc_collect\", \"minimized_pkg\"])\ndef test_verify(test_id, prepared_models, openvino_ref, artifacts, tolerance=1e-6): # pylint: disable=too-many-arguments\n \"\"\"Test verifying that inference results are equal.\"\"\"\n out = artifacts / test_id\n minimized_pkg = out / \"install_pkg\"\n\n infer_out_dir_cc = out / \"inference_result_cc/\"\n infer_out_dir = out / \"inference_result/\"\n\n return_code, output = run_infer(prepared_models, infer_out_dir, openvino_ref)\n assert return_code == 0, f\"Command exited with non-zero status {return_code}:\\n {output}\"\n return_code, output = run_infer(prepared_models, infer_out_dir_cc, minimized_pkg)\n assert return_code == 0, f\"Command exited with non-zero status {return_code}:\\n {output}\"\n\n for model in prepared_models:\n out_file = f\"{infer_out_dir / Path(model).name}.npz\"\n out_file_cc = f\"{infer_out_dir_cc / Path(model).name}.npz\"\n\n reference_results = dict(np.load(out_file))\n inference_results = dict(np.load(out_file_cc))\n assert sorted(reference_results.keys()) == sorted(\n inference_results.keys()\n ), \"Results have different number of layers\"\n for layer in reference_results.keys():\n assert np.allclose(\n reference_results[layer], inference_results[layer], tolerance\n ), \"Reference and inference results differ\"\n\n\[email protected](depends=[\"cc_collect\", \"minimized_pkg\"])\ndef test_libs_size(test_id, models, openvino_ref, artifacts): # pylint: disable=unused-argument\n \"\"\"Test if libraries haven't increased in size after conditional compilation.\"\"\"\n libraries = [\"ov_runtime\", \"ov_intel_cpu_plugin\"]\n minimized_pkg = artifacts / test_id / \"install_pkg\"\n ref_libs_size = get_lib_sizes(openvino_ref, libraries)\n lib_sizes = get_lib_sizes(minimized_pkg, libraries)\n\n for lib in libraries:\n lib_size_diff = ref_libs_size[lib] - lib_sizes[lib]\n lib_size_diff_percent = lib_size_diff / ref_libs_size[lib] * 100\n log.info(\n \"{}: old - {}kB; new - {}kB; diff = {}kB({:.2f}%)\".format(\n lib,\n ref_libs_size[lib] / 1024,\n lib_sizes[lib] / 1024,\n lib_size_diff / 1024,\n lib_size_diff_percent,\n )\n )\n res = [lib for lib in libraries if lib_sizes[lib] > ref_libs_size[lib]]\n assert len(res) == 0, f\"These libraries: {res} have increased in size!\"\n", "# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport numpy as np\n\nfrom openvino.tools.mo.back.FuseTransposesSequence import FuseTransposesSequence\nfrom openvino.tools.mo.ops.depth_to_space import DepthToSpaceOp\nfrom openvino.tools.mo.ops.shufflechannel import ShuffleChannels\nfrom openvino.tools.mo.back.replacement import BackReplacementPattern\nfrom openvino.tools.mo.front.common.partial_infer.utils import int64_array\nfrom openvino.tools.mo.graph.graph import Graph\n\n\nclass ShuffleChannelPatternOptimization(BackReplacementPattern):\n enabled = True\n force_clean_up = True\n\n def run_after(self):\n return [FuseTransposesSequence]\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[\n ('t_start_order', {'type': 'Const'}),\n ('t_start_order_d',\n {'value': lambda v: v is not None and np.all(np.array_equal(v, [0, 2, 3, 1]))}),\n ('t_start', {'type': 'Transpose'}),\n ('t_start_d', {}),\n\n ('reshape_dim', {'type': 'Const'}),\n ('reshape_dim_d',\n {'value': lambda v: v is not None and v.size == 5 and np.all(v[0] == -1)}),\n ('reshape_start', {'type': 'Reshape'}),\n ('reshape_start_d', {}),\n\n ('t_5d_order', {'type': 'Const'}),\n ('t_5d_order_d', {'value': lambda v: v is not None and np.all(np.array_equal(v, [0, 1, 2, 4, 3]))}),\n ('t_5d', {'type': 'Transpose'}),\n ('t_5d_d', {}),\n\n ('reshape_1_dim', {'type': 'Const'}),\n ('reshape_1_dim_d', {'value': lambda v: v is not None and v.size == 4 and np.all(v[0] == -1)}),\n ('reshape_end', {'type': 'Reshape'}),\n ('reshape_end_d', {}),\n\n ('t_end_order', {'type': 'Const'}),\n ('t_end_order_d', {'value': lambda v: v is not None and np.all(np.array_equal(v, [0, 3, 1, 2]))}),\n ('t_end', {'type': 'Transpose'}),\n ],\n edges=[\n ('t_start_order', 't_start_order_d'),\n ('t_start_order_d', 't_start', {'in': 1}),\n ('t_start', 't_start_d'),\n\n ('reshape_dim', 'reshape_dim_d'),\n ('t_start_d', 'reshape_start', {'in': 0}),\n ('reshape_dim_d', 'reshape_start', {'in': 1}),\n ('reshape_start', 'reshape_start_d'),\n\n ('t_5d_order', 't_5d_order_d'),\n ('reshape_start_d', 't_5d', {'in': 0}),\n ('t_5d_order_d', 't_5d', {'in': 1}),\n ('t_5d', 't_5d_d'),\n\n ('reshape_1_dim', 'reshape_1_dim_d'),\n ('t_5d_d', 'reshape_end', {'in': 0}),\n ('reshape_1_dim_d', 'reshape_end', {'in': 1}),\n ('reshape_end', 'reshape_end_d'),\n\n ('t_end_order', 't_end_order_d'),\n ('reshape_end_d', 't_end', {'in': 0}),\n ('t_end_order_d', 't_end', {'in': 1}),\n ],\n )\n\n @staticmethod\n def feature_dim_splitted(short_shape, long_shape):\n return all([short_shape[i] == long_shape[i] for i in range(len(short_shape) - 1)]) and \\\n short_shape[-1] == long_shape[-1] * long_shape[-2]\n\n @staticmethod\n def replace_pattern(graph: Graph, match: dict):\n reshape_5d = match['reshape_start']\n if not ShuffleChannelPatternOptimization.feature_dim_splitted(\n short_shape=reshape_5d.in_port(0).data.get_shape(), long_shape=reshape_5d.out_port(0).data.get_shape()):\n return\n\n reshape_4d = match['reshape_end']\n if not ShuffleChannelPatternOptimization.feature_dim_splitted(\n short_shape=reshape_4d.out_port(0).data.get_shape(), long_shape=reshape_4d.in_port(0).data.get_shape()):\n return\n\n start = match['t_start']\n end = match['t_end']\n\n new_start = match['reshape_start']\n new_end = match['reshape_end']\n\n start_source = start.in_port(0).get_connection().get_source()\n end_connection = end.out_port(0).get_connection()\n\n new_end.out_port(0).disconnect()\n end_connection.set_source(new_end.out_port(0))\n\n start.in_port(0).disconnect()\n new_start.in_port(0).disconnect()\n\n new_start.in_port(0).connect(start_source)\n\n match['reshape_dim']['value'] = int64_array(np.take(new_start.in_port(1).data.get_value(), [0, 3, 4, 1, 2]))\n match['reshape_dim'].infer(match['reshape_dim'])\n new_start.infer(new_start)\n\n match['t_5d_order']['value'] = int64_array([0, 2, 1, 3, 4])\n match['t_5d_order'].infer(match['t_5d_order'])\n match['t_5d'].infer(match['t_5d'])\n\n match['reshape_1_dim']['value'] = int64_array(np.take(new_end.in_port(1).data.get_value(), [0, 3, 1, 2]))\n match['reshape_1_dim'].infer(match['reshape_1_dim'])\n\n\nclass ShuffleChannelFusion(BackReplacementPattern):\n \"\"\"\n FUSION: Reshape->Transpose->Reshape to ShuffleChannel\n We are able to perform the fusion if the pattern satisfies the conditions:\n 1. Pattern input 4D shape is the same as pattern output 4D shape\n 2. First Reshape splits channel dimension (1 axis) into two dimensions\n 3. Transpose permutes only split dimensions\n 4. Second Reshape pack them back\n\n Fixes original models reshape-ability (Smart reshape)\n \"\"\"\n enabled = True\n force_clean_up = True\n\n def run_after(self):\n return [FuseTransposesSequence]\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[\n ('reshape_0_pattern', dict(type='Const')),\n ('reshape_0_pattern_d', dict(value=lambda v: v is not None and v.size == 5 and np.all(v > 0))),\n ('reshape_0', dict(type='Reshape')),\n ('reshape_0_d', dict()),\n\n ('order', dict(type='Const')),\n ('order_d', dict(value=lambda v: v is not None and np.array_equal([0, 2, 1, 3, 4], v))),\n ('transpose', dict(type='Transpose')),\n ('transpose_d', {}),\n\n ('reshape_1_pattern', dict(type='Const')),\n ('reshape_1_pattern_d', dict(value=lambda v: v is not None and v.size == 4 and np.all(v > 0))),\n ('reshape_1', dict(type='Reshape')),\n ],\n edges=[\n ('reshape_0_pattern', 'reshape_0_pattern_d'),\n ('reshape_0_pattern_d', 'reshape_0'),\n ('reshape_0', 'reshape_0_d'),\n ('reshape_0_d', 'transpose'),\n ('order', 'order_d'),\n ('order_d', 'transpose'),\n ('transpose', 'transpose_d'),\n ('transpose_d', 'reshape_1'),\n ('reshape_1_pattern', 'reshape_1_pattern_d'),\n ('reshape_1_pattern_d', 'reshape_1'),\n ]\n )\n\n @staticmethod\n def replace_pattern(graph: Graph, match: dict):\n channel_splitting_reshape = match['reshape_0']\n channel_concating_reshape = match['reshape_1']\n\n initial_shape = channel_splitting_reshape.in_port(0).data.get_shape()\n resulting_shape = channel_concating_reshape.in_port(1).data.get_value()\n if not np.array_equal(initial_shape, resulting_shape):\n return\n\n channel_splitted_out_shape = channel_splitting_reshape.in_port(1).data.get_value()\n if not all([initial_shape[i] == channel_splitted_out_shape[j] for i, j in {0: 0, 2: 3, 3: 4}.items()]):\n return\n\n name = channel_concating_reshape.soft_get('name', channel_concating_reshape.id)\n group = channel_splitted_out_shape[1]\n shuffle_channel = ShuffleChannels(graph, {'name': name, 'group': group}).create_node()\n channel_concating_reshape.out_port(0).get_connection().set_source(shuffle_channel.out_port(0))\n shuffle_channel.in_port(0).connect(channel_splitting_reshape.in_port(0).get_source())\n\n\nclass DepthToSpaceFusion(BackReplacementPattern):\n \"\"\"\n FUSION: Reshape->Transpose->Reshape to DepthToSpace\n We are able to perform the fusion if the pattern satisfies the conditions:\n 1. Pattern has 6D input and 4D output\n 2. First Reshape splits channel dimension (1 axis) into three dimensions [new_depth, block_size, block_size]\n 3. Transpose permutes split dimensions with spatial ones\n 4. Second Reshape pack block size together with spatial dimension\n\n Fixes original models reshape-ability (Smart reshape)\n \"\"\"\n enabled = True\n force_clean_up = True\n\n def run_after(self):\n return [FuseTransposesSequence]\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[\n ('reshape_0_pattern', dict(type='Const')),\n ('reshape_0_pattern_d', dict(value=lambda v: v is not None and v.size == 6 and np.all(v > 0))),\n ('reshape_0', dict(type='Reshape')),\n ('reshape_0_d', dict()),\n\n ('order', dict(type='Const')),\n ('order_d', dict(value=lambda v: v is not None and np.array_equal([0, 1, 4, 2, 5, 3], v))),\n ('transpose', dict(type='Transpose')),\n ('transpose_d', {}),\n\n ('reshape_1_pattern', dict(type='Const')),\n ('reshape_1_pattern_d', dict(value=lambda v: v is not None and v.size == 4 and np.all(v > 0))),\n ('reshape_1', dict(type='Reshape')),\n ],\n edges=[\n ('reshape_0_pattern', 'reshape_0_pattern_d'),\n ('reshape_0_pattern_d', 'reshape_0'),\n ('reshape_0', 'reshape_0_d'),\n ('reshape_0_d', 'transpose'),\n ('order', 'order_d'),\n ('order_d', 'transpose'),\n ('transpose', 'transpose_d'),\n ('transpose_d', 'reshape_1'),\n ('reshape_1_pattern', 'reshape_1_pattern_d'),\n ('reshape_1_pattern_d', 'reshape_1'),\n ]\n )\n\n @staticmethod\n def replace_pattern(graph: Graph, match: dict):\n channel_splitting_reshape = match['reshape_0']\n channel_concating_reshape = match['reshape_1']\n\n initial_shape = channel_splitting_reshape.in_port(0).data.get_shape()\n resulting_shape = channel_concating_reshape.in_port(1).data.get_value()\n if initial_shape[0] != resulting_shape[0]:\n return\n\n channel_splitted_out_shape = channel_splitting_reshape.in_port(1).data.get_value()\n if not all([initial_shape[i] == channel_splitted_out_shape[j] for i, j in {0: 0, 2: 4, 3: 5}.items()]) or \\\n channel_splitted_out_shape[1] != channel_splitted_out_shape[2]:\n return\n block_size = channel_splitted_out_shape[2]\n expected_output_shape = [initial_shape[0], initial_shape[1] // (block_size * block_size),\n initial_shape[2] * block_size, initial_shape[3] * block_size]\n if not np.array_equal(expected_output_shape, resulting_shape):\n return\n\n name = channel_concating_reshape.soft_get('name', channel_concating_reshape.id)\n depth_to_space = DepthToSpaceOp(graph,\n {'name': name, 'block_size': block_size, 'mode': 'depth_first'}).create_node()\n channel_concating_reshape.out_port(0).get_connection().set_source(depth_to_space.out_port(0))\n depth_to_space.in_port(0).connect(channel_splitting_reshape.in_port(0).get_source())\n" ]
[ [ "numpy.allclose", "numpy.multiply", "numpy.power", "numpy.arange", "numpy.array" ], [ "numpy.array_equal", "numpy.isfinite", "numpy.count_nonzero" ], [ "numpy.array", "numpy.allclose" ], [ "numpy.array", "numpy.array_equal" ], [ "numpy.array", "numpy.array_equal" ], [ "numpy.clip" ], [ "numpy.load" ], [ "numpy.array_equal" ], [ "numpy.logical_not", "numpy.maximum", "numpy.allclose", "numpy.random.seed", "numpy.random.rand", "numpy.float32", "numpy.exp", "numpy.array" ], [ "numpy.expand_dims" ], [ "numpy.int64", "numpy.array", "numpy.ma.masked_array" ], [ "numpy.array", "numpy.array_equal" ], [ "numpy.load", "numpy.allclose" ], [ "numpy.all", "numpy.array_equal" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ihmeuw/cascade-at
[ "a5b1b5da1698163fd3bbafc6288968dd9c398096", "a5b1b5da1698163fd3bbafc6288968dd9c398096", "a5b1b5da1698163fd3bbafc6288968dd9c398096" ]
[ "tests/model/test_priors.py", "src/cascade_at/dismod/constants.py", "src/cascade_at/model/age_time_grid.py" ]
[ "import pytest\nimport numpy as np\nfrom numpy import isclose\nfrom numpy.random import RandomState\n\nfrom cascade_at.model.priors import (\n Constant,\n Gaussian,\n Uniform,\n Laplace,\n StudentsT,\n LogGaussian,\n LogLaplace,\n LogStudentsT,\n PriorError,\n)\n\n\ndef test_happy_construction():\n Uniform(-1, 1, 0, name=\"test\")\n Uniform(-1, 1, 0, 0.5, name=\"test\")\n Gaussian(0, 1, -10, 10, name=\"test2\")\n Gaussian(0, 1, -10, 10, 0.5, name=\"test2\")\n Laplace(0, 1, -10, 10, name=\"test3\")\n Laplace(0, 1, -10, 10, 0.5, name=\"test3\")\n StudentsT(0, 1, 2.5, -10, 10, name=\"test4\")\n LogGaussian(0, 1, 0.5, -10, 10, name=\"test5\")\n LogLaplace(0, 1, 0.5, -10, 10, name=\"test6\")\n LogStudentsT(0, 1, 2.5, 0.5, -10, 10, name=\"test7\")\n\n\ndef test_prior_equality():\n a = Gaussian(0, 1)\n b = Gaussian(0, 1)\n assert a == b\n\n a = Gaussian(0, 1, -1, 1)\n b = Gaussian(0, 1, -1, 1)\n assert a == b\n\n a = Uniform(0, 10)\n b = Uniform(0, 10)\n assert a == b\n\n a = Uniform(0, 10, name=\"test_prior\")\n b = Uniform(0, 10, name=\"test_prior\")\n assert a == b\n\n\ndef test_prior_nonequality():\n a = Gaussian(0, 1)\n b = Gaussian(1, 1)\n assert a != b\n\n a = Uniform(0, 1)\n b = Uniform(-1, 0)\n assert a != b\n\n a = Gaussian(0, 1, name=\"test_prior\")\n b = Gaussian(0, 1, name=\"other_test_prior\")\n assert a != b\n\n a = Gaussian(0, 1)\n b = Uniform(0, 1)\n assert a != b\n\n\ndef test_prior_sort():\n priors = [\n Uniform(lower=1e-10, upper=1, mean=5e-5, name=\"iota\"),\n Gaussian(0, 1, name=\"other_test_prior\"),\n Uniform(0, 1),\n ]\n\n # NOTE: This is a weak test of actual sorting behavior however all I\n # actually care about is that the sort is stable, I don't really care\n # what the order is\n assert sorted(priors) == sorted(reversed(priors))\n\n\ndef test_prior_hashing():\n s = {Gaussian(0, 1), Uniform(0, 1), Gaussian(0, 1), Uniform(0, 2), Uniform(0, 1)}\n\n assert len(s) == 3\n assert Gaussian(0, 1) in s\n assert Uniform(0, 10) not in s\n\n\ndef test_prior_hashing__near_miss():\n assert hash(Gaussian(0, 1.0000000000000001)) == hash(Gaussian(0, 1))\n assert hash(Gaussian(0, 1.000000000000001)) != hash(Gaussian(0, 1))\n\n\ndef test_bounds_check():\n with pytest.raises(PriorError) as excinfo:\n Uniform(0, -1, 1)\n assert \"Bounds are inconsistent\" in str(excinfo.value)\n\n\ndef test_validate_standard_deviation():\n with pytest.raises(PriorError) as excinfo:\n Gaussian(0, -1)\n assert \"must be positive\" in str(excinfo.value)\n\n\[email protected](\"bad_nu\", [-1, -3, 0, 2, 1.99])\ndef test_validate_nu(bad_nu):\n with pytest.raises(PriorError) as excinfo:\n StudentsT(0, 1, bad_nu)\n assert \"must be greater\" in str(excinfo.value)\n\n\[email protected]\ndef rng():\n return RandomState(34257234)\n\n\ndef test_const_fit():\n \"\"\"A constant distribution is unchanged.\"\"\"\n dist = Constant(0.023)\n assert isclose(dist.rvs(), 0.023)\n assert isclose(dist.mle([6, 24, 327]).mean, 0.023)\n\n\ndef test_uniform_fit(rng):\n dist = Uniform(-0.4, 0.6, 0.5)\n draws = dist.rvs(size=10000, random_state=rng)\n new_dist = dist.mle(draws)\n assert isclose(new_dist.mean, 0.1, atol=0.01)\n\n\[email protected](\"cls,params\", [\n (Gaussian, (0.1, 1, -10, 10)),\n (Gaussian, (0.1, 1, 0, 0.2)),\n (Laplace, (0, 1, -10, 10)),\n (StudentsT, (0, 1, 2.7, -10, 10)),\n])\ndef test_mle(cls, params, rng):\n dist = cls(*params)\n draw_dist = dist\n if hasattr(dist, \"mean\"):\n draw_dist = draw_dist.assign(mean=0.1)\n if hasattr(dist, \"standard_deviation\"):\n draw_dist = draw_dist.assign(standard_deviation=0.04)\n\n draws = draw_dist.rvs(size=10000, random_state=rng)\n assert np.all((dist.lower <= draws) & (draws <= dist.upper))\n new_dist = dist.mle(draws)\n\n if hasattr(dist, \"mean\"):\n assert isclose(new_dist.mean, 0.1, rtol=0.2)\n\n if hasattr(dist, \"standard_deviation\"):\n assert isclose(new_dist.standard_deviation, 0.04, rtol=0.2)\n", "from enum import Enum\nimport pandas as pd\nimport numpy as np\n\n\n_dismod_cmd_ = 'dismod_at'\n_dismod_cmd_ = 'dmdismod'\n_dismod_cmd_ = 'dmdismod_script'\n\ndef enum_to_dataframe(enum_name):\n \"\"\"Given an enum, return a dataframe with two columns, name and value.\"\"\"\n return pd.DataFrame.from_records(\n np.array(\n [(measure, enum_value.value) for (measure, enum_value) in enum_name.__members__.items()],\n dtype=np.dtype([(\"name\", object), (\"value\", int)]),\n )\n )\n\n\nclass DensityEnum(Enum):\n \"\"\"The distributions supported by Dismod-AT. They always have these ids.\"\"\"\n uniform = 0\n \"Uniform Distribution\"\n gaussian = 1\n \"Gaussian Distribution\"\n laplace = 2\n \"Laplace Distribution\"\n students = 3\n \"Students-t Distribution\"\n log_gaussian = 4\n \"Log-Gaussian Distribution\"\n log_laplace = 5\n \"Log-Laplace Distribution\"\n log_students = 6\n \"Log-Students-t Distribution\"\n\n\nclass RateEnum(Enum):\n \"\"\"These are the five underlying rates.\n \"\"\"\n pini = 0\n \"\"\"Initial prevalence of the condition at birth, as a fraction of one.\"\"\"\n iota = 1\n \"\"\"Incidence rate for leaving susceptible to become diseased.\"\"\"\n rho = 2\n \"\"\"Remission from disease to susceptible.\"\"\"\n chi = 3\n \"\"\"Excess mortality rate.\"\"\"\n omega = 4\n \"\"\"Other-cause mortality rate.\"\"\"\n\n\nclass MulCovEnum(Enum):\n \"\"\"These are the mulcov kinds listed in the mulcov table.\"\"\"\n alpha = \"rate_value\"\n beta = \"meas_value\"\n gamma = \"meas_noise\"\n\n\nclass IntegrandEnum(Enum):\n \"\"\"These are all of the integrands Dismod-AT supports, and they will\n have exactly these IDs when serialized.\"\"\"\n Sincidence = 0\n \"\"\"Susceptible incidence, where the denominator is the number of susceptibles.\n Corresponds to iota.\"\"\"\n remission = 1\n \"\"\"Remission rate, corresponds to rho.\"\"\"\n mtexcess = 2\n \"\"\"Excess mortality rate, corresponds to chi.\"\"\"\n mtother = 3\n \"\"\"Other-cause mortality, corresponds to omega.\"\"\"\n mtwith = 4\n \"\"\"Mortality rate for those with condition.\"\"\"\n susceptible = 5\n \"\"\"Fraction of susceptibles out of total population.\"\"\"\n withC = 6\n \"\"\"Fraction of population with the disease. Total pop is the denominator.\"\"\"\n prevalence = 7\n \"\"\"Fraction of those alive with the disease, so S+C is denominator.\"\"\"\n Tincidence = 8\n \"\"\"Total-incidence, where denominator is susceptibles and with-condition.\"\"\"\n mtspecific = 9\n \"\"\"Cause-specific mortality rate, so mx_c.\"\"\"\n mtall = 10\n \"\"\"All-cause mortality rate, mx.\"\"\"\n mtstandard = 11\n \"\"\"Standardized mortality ratio.\"\"\"\n relrisk = 12\n \"\"\"Relative risk.\"\"\"\n incidence = -99\n \"\"\"This integrand should never be used, but we need it when we are converting\n from the epi database measures initially\"\"\"\n\n\nclass WeightEnum(Enum):\n \"\"\"Dismod-AT allows arbitrary weights, which are functions of space\n and time, defined by bilinear interpolations on grids. These weights\n are used to average rates over age and time intervals. Given this\n problem, there are three kinds of weights that are relevant.\"\"\"\n constant = 0\n \"\"\"This weight is constant everywhere at 1. This is the no-weight weight.\"\"\"\n susceptible = 1\n \"\"\"For measures that are integrals over population without the condition.\"\"\"\n with_condition = 2\n \"\"\"For measures that are integrals over those with the disease.\"\"\"\n total = 3\n \"\"\"For measures where the denominator is the whole population.\"\"\"\n\n\nclass PriorKindEnum(Enum):\n \"\"\"The three kinds of priors.\"\"\"\n value = 0\n dage = 1\n dtime = 2\n\n\nINTEGRAND_TO_WEIGHT = dict(\n Sincidence=WeightEnum.susceptible,\n remission=WeightEnum.with_condition,\n mtexcess=WeightEnum.with_condition,\n mtother=WeightEnum.total,\n susceptible=WeightEnum.constant,\n withC=WeightEnum.constant,\n mtwith=WeightEnum.with_condition,\n prevalence=WeightEnum.total,\n Tincidence=WeightEnum.total,\n mtspecific=WeightEnum.total,\n mtall=WeightEnum.total,\n mtstandard=WeightEnum.constant,\n relrisk=WeightEnum.constant,\n)\n\n\nRateToIntegrand = {\n \"iota\": \"Sincidence\",\n \"rho\": \"remission\",\n \"chi\": \"mtexcess\",\n \"omega\": \"mtother\",\n \"pini\": \"prevalence\"\n}\n\nIntegrandToRate = {\n v: k for k, v in RateToIntegrand.items()\n}\n\n\"\"\"Each integrand has a natural association with a particular weight because\nit is a count of events with one of four denominators: constant, susceptibles,\nwith-condition, or the total population. For instance, if you supply\nmtspecific data, it will always use the weight called \"total.\"\n\"\"\"\n", "from datetime import timedelta\nfrom itertools import product\nfrom math import nan, inf\n\nimport numpy as np\nimport pandas as pd\n\nfrom cascade_at.core.log import get_loggers\nfrom cascade_at.dismod.constants import PriorKindEnum\n\nLOG = get_loggers(__name__)\n\nGRID_SNAP_DISTANCE = 1 / timedelta(days=365).total_seconds()\n\"\"\"Times within one second are considered equal.\"\"\"\n\n\nclass AgeTimeGrid:\n \"\"\"The AgeTime grid holds rows of a table at each age and time value.\n\n At each age and time point is a DataFrame consisting of the columns\n given in the constructor. So getting an item returns a dataframe\n with those columns. Setting a DataFrame sets those columns.\n Each AgeTimeGrid has three possible mulstds, for value, dage, dtime.\n\n >>> atg = AgeTimeGrid([0, 10, 20], [1990, 2000, 2010], [\"height\", \"weight\"])\n >>> atg[:, :] = [6.1, 195]\n >>> atg[:, :].height = [5.9]\n >>> atg[10, 2000] = [5.7, 180]\n >>> atg[5:17, 1980:1990].weight = 125\n >>> assert (atg[20, 2000].weight == 195).all()\n >>> assert isinstance(atg[0, 1990], pd.DataFrame)\n\n If the column has the same name as a function (mean), then access it\n with getitem,\n\n >>> atg[:, :][\"mean\"] = [5.9]\n\n Why is this in Pandas, when it's a regular array of data with an\n index, which makes it better suited to XArray, or even a\n Numpy array? It needs to interface with a database representation,\n and Pandas is a better match there.\n \"\"\"\n def __init__(self, ages, times, columns):\n try:\n self.ages = np.sort(np.atleast_1d(ages).astype(float))\n self.times = np.sort(np.atleast_1d(times).astype(float))\n except TypeError:\n raise TypeError(f\"Ages and times should be arrays of floats {(ages, times)}.\")\n type_constraint = \"Columns should be either a string or an iterable of strings.\"\n if isinstance(columns, str):\n columns = [columns]\n try:\n self.columns = list(columns)\n except TypeError:\n raise TypeError(f\"{type_constraint} {columns}\")\n for col_is_str in self.columns:\n if not isinstance(col_is_str, str):\n raise TypeError(f\"{type_constraint} {col_is_str}\")\n age_time = np.array(list(product(sorted(self.ages), sorted(self.times))))\n self.grid = pd.DataFrame(dict(\n age=age_time[:, 0],\n time=age_time[:, 1],\n ))\n self.grid = self.grid.assign(**{new_col: nan for new_col in columns})\n self._mulstd = dict()\n # Each mulstd is one record.\n for kind in PriorKindEnum:\n mulstd_df = pd.DataFrame(dict(\n age=[nan],\n time=[nan],\n ))\n mulstd_df = mulstd_df.assign(**{new_col: nan for new_col in columns})\n self._mulstd[kind.name] = mulstd_df\n\n @property\n def mulstd(self):\n return self._mulstd\n\n def age_time(self):\n yield from zip(np.repeat(self.ages, len(self.times)), np.tile(self.times, len(self.ages)))\n\n def __getitem__(self, age_time):\n \"\"\"\n Args:\n age_time (float, float): Gets all rows with this (age, time).\n\n Returns:\n pd.DataFrame or pd.Series with columns.\n \"\"\"\n try:\n age, time = age_time\n except TypeError as te:\n if \"not iterable\" in str(te):\n raise TypeError(f\"Index should be two floats for getting, not {age_time}.\")\n else:\n raise\n if isinstance(age, slice) or isinstance(time, slice):\n raise TypeError(f\"Cannot get a slice from an AgeTimeGrid.\")\n rows = self.grid.query(\"age == @age and time == @time\")\n if len(rows) > 0:\n return rows[self.columns]\n else:\n raise KeyError(f\"Age {age} and time {time} not found.\")\n\n def __setitem__(self, at_slice, value):\n \"\"\"\n Args:\n at_slice (slice, slice): What to change, as integer offset into ages and times.\n value (priors.Prior): The prior to set, containing dictionary of\n parameters.\n \"\"\"\n try:\n if len(at_slice) != 2:\n raise ValueError(\"Set value at an age and time, so two arguments.\")\n except TypeError:\n raise ValueError(\"Set value at an age and time, so two arguments\")\n at_range = list()\n for one_slice in at_slice:\n if not isinstance(one_slice, slice):\n one_slice = slice(one_slice, one_slice)\n if one_slice.step is not None:\n raise ValueError(\"Slice in age or time, without a step.\")\n start = one_slice.start if one_slice.start is not None else -inf\n stop = one_slice.stop if one_slice.stop is not None else inf\n at_range.append([start - GRID_SNAP_DISTANCE, stop + GRID_SNAP_DISTANCE])\n ages = self.ages[(at_range[0][0] <= self.ages) & (self.ages <= at_range[0][1])]\n times = self.times[(at_range[1][0] <= self.times) & (self.times <= at_range[1][1])]\n if len(ages) == 0:\n raise ValueError(f\"No ages within range {at_range[0]} \"\n \"Are you looking for a point not in the grid?\")\n if len(times) == 0:\n raise ValueError(f\"No times within range {at_range[1]} \"\n \"Are you looking for a point not in the grid?\")\n self.grid.loc[np.in1d(self.grid.age, ages) & np.in1d(self.grid.time, times), self.columns] = value\n\n def __len__(self):\n return self.variable_count()\n\n def variable_count(self):\n mulstd_cnt = sum(not df[self.columns].dropna(how=\"all\").empty for df in self._mulstd.values())\n return self.ages.shape[0] * self.times.shape[0] + mulstd_cnt\n\n def __str__(self):\n return f\"AgeTimeGrid({len(self.ages)}, {len(self.times)}) with {self.variable_count()} model variables.\"\n\n def __repr__(self):\n return f\"AgeTimeGrid({self.ages}, {self.times})\"\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n LOG.debug(f\"SmoothGrid not equal to {other}\")\n return NotImplemented\n if set(self.mulstd.keys()) != set(other.mulstd.keys()):\n LOG.debug(f\"Different number of mulstd keys\")\n return False\n for mul_key in self.mulstd.keys():\n try:\n pd.testing.assert_frame_equal(self.mulstd[mul_key], other.mulstd[mul_key])\n except AssertionError:\n LOG.debug(\"assert frame equal false on mulstd\")\n return False\n try:\n pd.testing.assert_frame_equal(self.grid, other.grid, check_like=True, check_exact=False)\n return True\n except AssertionError as ae:\n if \"values are different\" in str(ae):\n LOG.debug(\"assert frame equal false on grid\")\n return False\n else:\n raise\n" ]
[ [ "numpy.all", "numpy.random.RandomState", "numpy.isclose" ], [ "numpy.dtype" ], [ "numpy.atleast_1d", "numpy.in1d", "pandas.testing.assert_frame_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
jiangbestone/DetectRccn
[ "fb30491201f8c64d5ca75298d52aa1a20c4bc6e3" ]
[ "models/rcnn.py" ]
[ "\nfrom torch.autograd import Variable\nfrom models.proposal_target_layer_cascade import *\nimport torchvision.models as models\nfrom models.proposal import *\n#bocknet\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes=1000,dropout_prob=0.2):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.dropout = nn.Dropout(p=dropout_prob)\n self.avgpool = nn.AvgPool2d(7)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.dropout(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\nclass _fasterRCNN(nn.Module):\n \"\"\" faster RCNN \"\"\"\n def __init__(self, classes, class_agnostic):\n super(_fasterRCNN, self).__init__()\n self.classes = classes\n self.n_classes = len(classes)\n self.class_agnostic = class_agnostic\n # loss\n self.RCNN_loss_cls = 0\n self.RCNN_loss_bbox = 0\n\n\n\n def forward(self, im_data, im_info, gt_boxes, num_boxes):\n batch_size = im_data.size(0)\n\n im_info = im_info.data\n gt_boxes = gt_boxes.data\n num_boxes = num_boxes.data\n\n # feed image cfgs to base model to obtain base feature map\n base_feat = self.RCNN_base(im_data)\n\n # feed base feature map to RPN to obtain rois\n rois, rpn_loss_cls, rpn_loss_bbox = self.RCNN_rpn(base_feat, im_info, gt_boxes, num_boxes)\n\n # if it is training phase, then use ground truth bboxes for refining\n if self.training:\n roi_data = self.RCNN_proposal_target(rois, gt_boxes, num_boxes)\n rois, rois_label, rois_target, rois_inside_ws, rois_outside_ws = roi_data\n\n rois_label = Variable(rois_label.view(-1).long())\n else:\n rois_label = None\n rpn_loss_cls = 0\n rpn_loss_bbox = 0\n\n rois = Variable(rois)\n # do roi pooling based on predicted rois\n\n pooled_feat = self.RCNN_roi_pool(base_feat, rois.view(-1,5))\n\n # feed pooled features to top model\n pooled_feat = self._head_to_tail(pooled_feat)\n\n # compute bbox offset\n bbox_pred = self.RCNN_bbox_pred(pooled_feat)\n if self.training and not self.class_agnostic:\n # select the corresponding columns according to roi labels\n bbox_pred_view = bbox_pred.view(bbox_pred.size(0), int(bbox_pred.size(1) / 4), 4)\n bbox_pred_select = torch.gather(bbox_pred_view, 1, rois_label.view(rois_label.size(0), 1, 1).expand(rois_label.size(0), 1, 4))\n bbox_pred = bbox_pred_select.squeeze(1)\n\n # compute object classification probability\n cls_score = self.RCNN_cls_score(pooled_feat)\n cls_prob = F.softmax(cls_score, 1)\n\n RCNN_loss_cls = 0\n RCNN_loss_bbox = 0\n\n\n cls_prob = cls_prob.view(batch_size, rois.size(1), -1)\n bbox_pred = bbox_pred.view(batch_size, rois.size(1), -1)\n\n return rois, cls_prob, bbox_pred, rpn_loss_cls, rpn_loss_bbox, RCNN_loss_cls, RCNN_loss_bbox, rois_label\n\n def _init_weights(self):\n def normal_init(m, mean, stddev, truncated=False):\n \"\"\"\n weight initalizer: truncated normal and random normal.\n \"\"\"\n # x is a parameter\n if truncated:\n m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation\n else:\n m.weight.data.normal_(mean, stddev)\n m.bias.data.zero_()\n def create_architecture(self):\n self._init_modules()\n self._init_weights()\n\n\n\n#\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\nclass Model(nn.Module):\n def __init__(self, model_cfg='datanet.yaml', ch=3, nc=None):\n super(Model, self).__init__()\n if type(model_cfg) is dict:\n self.md = model_cfg\n else:\n import yaml\n with open(model_cfg) as f:\n self.md = yaml.load(f, Loader=yaml.FullLoader)\n\n if nc and nc != self.md['nc']:\n print('Overriding %s nc=%g with nc=%g' % (model_cfg, self.md['nc'], nc))\n self.md['nc'] = nc\n self.model, self.save = BasicBlock(self.md, ch=[ch])\n\n m = self.model[-1]\n if isinstance(m, Detect):\n s = 128\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])\n m.anchors /= m.stride.view(-1, 1, 1)\n check_anchor_order(m)\n self.stride = m.stride\n self._initialize_biases()\n\n torch_utils.initialize_weights(self)\n self._initialize_biases()\n torch_utils.model_info(self)\n print('')\n\n def forward(self, x, augment=False, profile=False):\n if augment:\n img_size = x.shape[-2:]\n s = [0.83, 0.67]\n y = []\n for i, xi in enumerate((x,\n torch_utils.scale_img(x.flip(3), s[0]),\n torch_utils.scale_img(x, s[1]),\n )):\n y.append(self.forward_once(xi)[0])\n\n y[1][..., :4] /= s[0] # scale\n y[1][..., 0] = img_size[1] - y[1][..., 0] # flip lr\n y[2][..., :4] /= s[1] # scale\n return torch.cat(y, 1), None\n else:\n return self.forward_once(x, profile)\n\n def forward_once(self, x, profile=False):\n y, dt = [], [] # outputs\n for m in self.model:\n if m.f != -1: # if not from previous layer\n x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers\n\n if profile:\n try:\n import thop\n o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS\n except:\n o = 0\n t = torch_utils.time_synchronized()\n for _ in range(10):\n _ = m(x)\n dt.append((torch_utils.time_synchronized() - t) * 100)\n print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))\n\n x = m(x) # run\n y.append(x if m.i in self.save else None) # save output\n\n if profile:\n print('%.1fms total' % sum(dt))\n return x\n\n def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency\n m = self.model[-1] # Detect() module\n for f, s in zip(m.f, m.stride): #  from\n mi = self.model[f % m.i]\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _print_biases(self):\n m = self.model[-1] # Detect() module\n for f in sorted([x % m.i for x in m.f]): #  from\n b = self.model[f].bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)\n print(('%g Conv2d.bias:' + '%10.3g' * 6) % (f, *b[:5].mean(1).tolist(), b[5:].mean()))\n\n\n def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers\n print('Fusing layers... ', end='')\n for m in self.model.modules():\n if type(m) is Conv:\n m.conv = torch_utils.fuse_conv_and_bn(m.conv, m.bn) # update conv\n m.bn = None # remove batchnorm\n m.forward = m.fuseforward # update forward\n torch_utils.model_info(self)\n return self\n\ndef BasicBlock(runwget, ch):\n anchors, nc, gd, gw = runwget['anchors'], runwget['nc'], runwget['depth_multiple'], runwget['width_multiple']\n na = (len(anchors[0]) // 2) # number of anchors\n no = na * (nc + 5) # number of outputs = anchors * (classes + 5)\n\n layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out\n for i, (f, n, m, args) in enumerate(runwget['backbone'] + runwget['head']): # from, number, module, args\n m = eval(m) if isinstance(m, str) else m # eval strings\n for j, a in enumerate(args):\n try:\n args[j] = eval(a) if isinstance(a, str) else a # eval strings\n except:\n pass\n\n n = max(round(n * gd), 1) if n > 1 else n # depth gain\n if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:\n c1, c2 = ch[f], args[0]\n c2 = make_divisible(c2 * gw, 8) if c2 != no else c2\n args = [c1, c2, *args[1:]]\n if m in [BottleneckCSP, C3]:\n args.insert(2, n)\n n = 1\n elif m is nn.BatchNorm2d:\n args = [ch[f]]\n elif m is Concat:\n c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])\n elif m is Detect:\n f = f or list(reversed([(-1 if j == i else j - 1) for j, x in enumerate(ch) if x == no]))\n else:\n c2 = ch[f]\n m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module\n t = str(m)[8:-2].replace('__main__.', '') # module type\n np = sum([x.numel() for x in m_.parameters()]) # number params\n m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params\n save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist\n layers.append(m_)\n ch.append(c2)\n return nn.Sequential(*layers), sorted(save)\n\nclass vgg16(_fasterRCNN):\n def __init__(self, classes, pretrained=False, class_agnostic=False):\n self.model_path = 'cfgs/pretrained_model/vgg16_caffe.pth'\n self.dout_base_model = 512\n self.pretrained = pretrained\n self.class_agnostic = class_agnostic\n\n _fasterRCNN.__init__(self, classes, class_agnostic)\n\n def _init_modules(self):\n vgg = models.vgg16()\n if self.pretrained:\n print(\"Loading pretrained weights from %s\" % (self.model_path))\n state_dict = torch.load(self.model_path)\n vgg.load_state_dict({k: v for k, v in state_dict.items() if k in vgg.state_dict()})\n\n vgg.classifier = nn.Sequential(*list(vgg.classifier._modules.values())[:-1])\n\n self.RCNN_base = nn.Sequential(*list(vgg.features._modules.values())[:-1])\n\n for layer in range(10):\n for p in self.RCNN_base[layer].parameters(): p.requires_grad = False\n\n self.RCNN_top = vgg.classifier\n\n self.RCNN_cls_score = nn.Linear(4096, self.n_classes)\n\n if self.class_agnostic:\n self.RCNN_bbox_pred = nn.Linear(4096, 4)\n else:\n self.RCNN_bbox_pred = nn.Linear(4096, 4 * self.n_classes)\n\n def _head_to_tail(self, pool5):\n\n pool5_flat = pool5.view(pool5.size(0), -1)\n fc7 = self.RCNN_top(pool5_flat)\n\n return fc7\n\n\n" ]
[ [ "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
httpsgithu/mindspore
[ "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64", "c29d6bb764e233b427319cb89ba79e420f1e2c64" ]
[ "tests/ut/python/dataset/test_rgb_hsv.py", "tests/st/sparse/test_csr.py", "mindspore/python/mindspore/dataset/transforms/c_transforms.py", "tests/ut/python/dataset/test_duplicate_op.py", "mindspore/python/mindspore/mindrecord/tools/cifar100_to_mr.py", "tests/ut/python/parallel/test_unsortedsegmentprod.py", "mindspore/python/mindspore/nn/metrics/confusion_matrix.py", "tests/st/ops/cpu/test_inplace_op.py", "tests/st/fallback/control_flow/test_fallback_001_single_while.py", "tests/ut/python/dataset/test_datasets_qmnist.py", "tests/st/ops/cpu/test_dropout_nd.py", "tests/st/ops/ascend/test_gru_op.py" ]
[ "# Copyright 2019 Huawei Technologies Co., Ltd\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\"\"\"\nTesting RgbToHsv and HsvToRgb op in DE\n\"\"\"\n\nimport colorsys\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nimport mindspore.dataset as ds\nimport mindspore.dataset.transforms.transforms\nimport mindspore.dataset.vision.transforms as vision\nimport mindspore.dataset.vision.py_transforms_util as util\n\nDATA_DIR = [\"../data/dataset/test_tf_file_3_images/train-0000-of-0001.data\"]\nSCHEMA_DIR = \"../data/dataset/test_tf_file_3_images/datasetSchema.json\"\n\n\ndef generate_numpy_random_rgb(shape):\n # Only generate floating points that are fractions like n / 256, since they\n # are RGB pixels. Some low-precision floating point types in this test can't\n # handle arbitrary precision floating points well.\n return np.random.randint(0, 256, shape) / 255.\n\n\ndef test_rgb_hsv_hwc():\n rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.float32)\n rgb_np = rgb_flat.reshape((8, 8, 3))\n hsv_base = np.array([\n colorsys.rgb_to_hsv(\n r.astype(np.float64), g.astype(np.float64), b.astype(np.float64))\n for r, g, b in rgb_flat\n ])\n hsv_base = hsv_base.reshape((8, 8, 3))\n hsv_de = util.rgb_to_hsvs(rgb_np, True)\n assert hsv_base.shape == hsv_de.shape\n assert_allclose(hsv_base.flatten(), hsv_de.flatten(), rtol=1e-5, atol=0)\n\n hsv_flat = hsv_base.reshape(64, 3)\n rgb_base = np.array([\n colorsys.hsv_to_rgb(\n h.astype(np.float64), s.astype(np.float64), v.astype(np.float64))\n for h, s, v in hsv_flat\n ])\n rgb_base = rgb_base.reshape((8, 8, 3))\n rgb_de = util.hsv_to_rgbs(hsv_base, True)\n assert rgb_base.shape == rgb_de.shape\n assert_allclose(rgb_base.flatten(), rgb_de.flatten(), rtol=1e-5, atol=0)\n\n\ndef test_rgb_hsv_batch_hwc():\n rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.float32)\n rgb_np = rgb_flat.reshape((4, 2, 8, 3))\n hsv_base = np.array([\n colorsys.rgb_to_hsv(\n r.astype(np.float64), g.astype(np.float64), b.astype(np.float64))\n for r, g, b in rgb_flat\n ])\n hsv_base = hsv_base.reshape((4, 2, 8, 3))\n hsv_de = util.rgb_to_hsvs(rgb_np, True)\n assert hsv_base.shape == hsv_de.shape\n assert_allclose(hsv_base.flatten(), hsv_de.flatten(), rtol=1e-5, atol=0)\n\n hsv_flat = hsv_base.reshape((64, 3))\n rgb_base = np.array([\n colorsys.hsv_to_rgb(\n h.astype(np.float64), s.astype(np.float64), v.astype(np.float64))\n for h, s, v in hsv_flat\n ])\n rgb_base = rgb_base.reshape((4, 2, 8, 3))\n rgb_de = util.hsv_to_rgbs(hsv_base, True)\n assert rgb_de.shape == rgb_base.shape\n assert_allclose(rgb_base.flatten(), rgb_de.flatten(), rtol=1e-5, atol=0)\n\n\ndef test_rgb_hsv_chw():\n rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.float32)\n rgb_np = rgb_flat.reshape((3, 8, 8))\n hsv_base = np.array([\n np.vectorize(colorsys.rgb_to_hsv)(\n rgb_np[0, :, :].astype(np.float64), rgb_np[1, :, :].astype(np.float64), rgb_np[2, :, :].astype(np.float64))\n ])\n hsv_base = hsv_base.reshape((3, 8, 8))\n hsv_de = util.rgb_to_hsvs(rgb_np, False)\n assert hsv_base.shape == hsv_de.shape\n assert_allclose(hsv_base.flatten(), hsv_de.flatten(), rtol=1e-5, atol=0)\n\n rgb_base = np.array([\n np.vectorize(colorsys.hsv_to_rgb)(\n hsv_base[0, :, :].astype(np.float64), hsv_base[1, :, :].astype(np.float64),\n hsv_base[2, :, :].astype(np.float64))\n ])\n rgb_base = rgb_base.reshape((3, 8, 8))\n rgb_de = util.hsv_to_rgbs(hsv_base, False)\n assert rgb_de.shape == rgb_base.shape\n assert_allclose(rgb_base.flatten(), rgb_de.flatten(), rtol=1e-5, atol=0)\n\n\ndef test_rgb_hsv_batch_chw():\n rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.float32)\n rgb_imgs = rgb_flat.reshape((4, 3, 2, 8))\n hsv_base_imgs = np.array([\n np.vectorize(colorsys.rgb_to_hsv)(\n img[0, :, :].astype(np.float64), img[1, :, :].astype(np.float64), img[2, :, :].astype(np.float64))\n for img in rgb_imgs\n ])\n hsv_de = util.rgb_to_hsvs(rgb_imgs, False)\n assert hsv_base_imgs.shape == hsv_de.shape\n assert_allclose(hsv_base_imgs.flatten(), hsv_de.flatten(), rtol=1e-5, atol=0)\n\n rgb_base = np.array([\n np.vectorize(colorsys.hsv_to_rgb)(\n img[0, :, :].astype(np.float64), img[1, :, :].astype(np.float64), img[2, :, :].astype(np.float64))\n for img in hsv_base_imgs\n ])\n rgb_de = util.hsv_to_rgbs(hsv_base_imgs, False)\n assert rgb_base.shape == rgb_de.shape\n assert_allclose(rgb_base.flatten(), rgb_de.flatten(), rtol=1e-5, atol=0)\n\n\ndef test_rgb_hsv_pipeline():\n # First dataset\n transforms1 = [\n vision.Decode(True),\n vision.Resize([64, 64]),\n vision.ToTensor()\n ]\n transforms1 = mindspore.dataset.transforms.transforms.Compose(transforms1)\n ds1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=[\"image\"], shuffle=False)\n ds1 = ds1.map(operations=transforms1, input_columns=[\"image\"])\n\n # Second dataset\n transforms2 = [\n vision.Decode(True),\n vision.Resize([64, 64]),\n vision.ToTensor(),\n vision.RgbToHsv(),\n vision.HsvToRgb()\n ]\n transform2 = mindspore.dataset.transforms.transforms.Compose(transforms2)\n ds2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=[\"image\"], shuffle=False)\n ds2 = ds2.map(operations=transform2, input_columns=[\"image\"])\n\n num_iter = 0\n for data1, data2 in zip(ds1.create_dict_iterator(num_epochs=1), ds2.create_dict_iterator(num_epochs=1)):\n num_iter += 1\n ori_img = data1[\"image\"].asnumpy()\n cvt_img = data2[\"image\"].asnumpy()\n assert_allclose(ori_img.flatten(), cvt_img.flatten(), rtol=1e-5, atol=0)\n assert ori_img.shape == cvt_img.shape\n\n\nif __name__ == \"__main__\":\n test_rgb_hsv_hwc()\n test_rgb_hsv_batch_hwc()\n test_rgb_hsv_chw()\n test_rgb_hsv_batch_chw()\n test_rgb_hsv_pipeline()\n", "# Copyright 2021 Huawei Technologies Co., Ltd\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\"\"\"smoke tests for CSR operations\"\"\"\n\nimport os\nimport pytest\nimport numpy as np\n\nfrom mindspore import Tensor, CSRTensor, ms_function, nn, ops\nfrom mindspore.ops.operations import _csr_ops\nfrom mindspore.common import dtype as mstype\nfrom mindspore.train.serialization import export, load\nfrom mindspore.ops import functional as F\n\nfrom .sparse_utils import get_platform, compare_res\n\n\ndef compare_csr(csr1, csr2):\n assert isinstance(csr1, CSRTensor)\n assert isinstance(csr2, CSRTensor)\n assert (csr1.indptr.asnumpy() == csr2.indptr.asnumpy()).all()\n assert (csr1.indices.asnumpy() == csr2.indices.asnumpy()).all()\n assert (csr1.values.asnumpy() == csr2.values.asnumpy()).all()\n assert csr1.shape == csr2.shape\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_make_csr():\n \"\"\"\n Feature: Test CSRTensor Constructor in Graph and PyNative.\n Description: Test CSRTensor(indptr, indices, values, shape) and CSRTensor(CSRTensor)\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([1, 2], dtype=mstype.float32)\n shape = (2, 6)\n def test_pynative():\n return CSRTensor(indptr, indices, values, shape)\n test_graph = ms_function(test_pynative)\n\n csr1 = test_pynative()\n csr2 = test_graph()\n compare_csr(csr1, csr2)\n csr3 = CSRTensor(csr_tensor=csr2)\n compare_csr(csr3, csr2)\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_csr_attr():\n \"\"\"\n Feature: Test CSRTensor GetAttr in Graph and PyNative.\n Description: Test CSRTensor.indptr, CSRTensor.indices, CSRTensor.values, CSRTensor.shape.\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([1, 2], dtype=mstype.float32)\n shape = (2, 6)\n csr = CSRTensor(indptr, indices, values, shape)\n\n def test_pynative_1():\n return csr.indptr, csr.indices\n\n def test_pynative_2():\n return csr.values, csr.shape\n\n def test_pynative_3():\n return csr.astype(mstype.int32)\n\n def test_pynative_4():\n return csr.to_tuple()\n\n test_graph_1 = ms_function(test_pynative_1)\n test_graph_2 = ms_function(test_pynative_2)\n test_graph_3 = ms_function(test_pynative_3)\n test_graph_4 = ms_function(test_pynative_4)\n\n py_indptr, py_indices = test_pynative_1()\n py_values, py_shape = test_pynative_2()\n py_csr = test_pynative_3()\n py_tuple = test_pynative_4()\n\n g_indptr, g_indices = test_graph_1()\n g_values, g_shape = test_graph_2()\n g_csr = test_graph_3()\n g_tuple = test_graph_4()\n\n csr1 = CSRTensor(py_indptr, py_indices, py_values, py_shape)\n csr2 = CSRTensor(g_indptr, g_indices, g_values, g_shape)\n # check csr attr\n compare_csr(csr1, csr2)\n # check astype\n compare_csr(py_csr, g_csr)\n # check to_tuple\n assert len(py_tuple) == len(g_tuple)\n for i, _ in enumerate(py_tuple):\n if isinstance(py_tuple[i], Tensor):\n assert (py_tuple[i].asnumpy() == g_tuple[i].asnumpy()).all()\n else:\n assert py_tuple[i] == g_tuple[i]\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_x86_gpu_training\[email protected]_onecard\ndef test_csr_tensor_in_while():\n \"\"\"\n Feature: Test CSRTensor in while loop.\n Description: Test CSRTensor computation in while loop.\n Expectation: Success.\n \"\"\"\n class CSRTensorValuesDouble(nn.Cell):\n\n def construct(self, x):\n indptr = x.indptr\n indices = x.indices\n values = x.values * 2\n shape = x.shape\n return CSRTensor(indptr, indices, values, shape)\n\n class CSRTensorValuesAdd2(nn.Cell):\n\n def construct(self, x):\n indptr = x.indptr\n indices = x.indices\n values = x.values + 2\n shape = x.shape\n return CSRTensor(indptr, indices, values, shape)\n\n class CSRTensorWithControlWhile(nn.Cell):\n def __init__(self, shape):\n super(CSRTensorWithControlWhile, self).__init__()\n self.op1 = CSRTensorValuesDouble()\n self.op2 = CSRTensorValuesAdd2()\n self.shape = shape\n\n @ms_function\n def construct(self, a, b, indptr, indices, values):\n x = CSRTensor(indptr, indices, values, self.shape)\n x = self.op2(x)\n while a > b:\n x = self.op1(x)\n b = b + 1\n return x\n a = Tensor(3, mstype.int32)\n b = Tensor(0, mstype.int32)\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([1, 2], dtype=mstype.float32)\n shape = (2, 6)\n net = CSRTensorWithControlWhile(shape)\n out = net(a, b, indptr, indices, values)\n assert np.allclose(out.indptr.asnumpy(), indptr.asnumpy(), .0, .0)\n assert np.allclose(out.indices.asnumpy(), indices.asnumpy(), .0, .0)\n assert np.allclose((values.asnumpy() + 2) * 8, out.values.asnumpy(), .0, .0)\n assert shape == out.shape\n\n # Test Export MindIR\n file_name = \"csrtensor_with_control_while_net\"\n export(net, a, b, indptr, indices, values, file_name=file_name, file_format=\"MINDIR\")\n mindir_name = file_name + \".mindir\"\n assert os.path.exists(mindir_name)\n\n graph = load(mindir_name)\n loaded_net = nn.GraphCell(graph)\n outputs_after_load = loaded_net(a, b, indptr, indices, values)\n assert np.allclose(out.indptr.asnumpy(), outputs_after_load.indptr.asnumpy())\n assert np.allclose(out.indices.asnumpy(), outputs_after_load.indices.asnumpy())\n assert np.allclose(out.values.asnumpy(), outputs_after_load.values.asnumpy())\n assert out.shape == outputs_after_load.shape\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_onecard\ndef test_csr_tensor_in_while_cpu():\n \"\"\"\n Feature: Test CSRTensor in while loop.\n Description: Test CSRTensor computation in while loop.\n Expectation: Success.\n \"\"\"\n class CSRTensorValuesDouble(nn.Cell):\n\n def construct(self, x):\n indptr = x.indptr\n indices = x.indices\n values = x.values * 2\n shape = x.shape\n return CSRTensor(indptr, indices, values, shape)\n\n class CSRTensorValuesAdd2(nn.Cell):\n\n def construct(self, x):\n indptr = x.indptr\n indices = x.indices\n values = x.values + 2\n shape = x.shape\n return CSRTensor(indptr, indices, values, shape)\n\n class CSRTensorWithControlWhile(nn.Cell):\n def __init__(self, shape):\n super(CSRTensorWithControlWhile, self).__init__()\n self.op1 = CSRTensorValuesDouble()\n self.op2 = CSRTensorValuesAdd2()\n self.shape = shape\n\n @ms_function\n def construct(self, a, b, indptr, indices, values):\n x = CSRTensor(indptr, indices, values, self.shape)\n x = self.op2(x)\n while a > b:\n x = self.op1(x)\n b = b + 1\n return x\n a = Tensor(3, mstype.int32)\n b = Tensor(0, mstype.int32)\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([1, 2], dtype=mstype.float32)\n shape = (2, 6)\n net = CSRTensorWithControlWhile(shape)\n out = net(a, b, indptr, indices, values)\n assert np.allclose(out.indptr.asnumpy(), indptr.asnumpy(), .0, .0)\n assert np.allclose(out.indices.asnumpy(), indices.asnumpy(), .0, .0)\n assert np.allclose((values.asnumpy() + 2) * 8, out.values.asnumpy(), .0, .0)\n assert shape == out.shape\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_csr_ops():\n \"\"\"\n Feature: Test CSR-related Ops.\n Description: Test CSRReduceSum, CSRMul, CSRMV.\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n csr_reducesum = _csr_ops.CSRReduceSum()\n csrmv = _csr_ops.CSRMV()\n\n indptr = Tensor([0, 1, 2], dtype=mstype.int32)\n indices = Tensor([0, 1], dtype=mstype.int32)\n values = Tensor([2, 1], dtype=mstype.float32)\n dense_shape = (2, 4)\n\n dense_tensor = Tensor([[1., 1, 1, 1], [1, 1, 1, 1]], dtype=mstype.float32)\n dense_vector = Tensor([[1.], [1], [1], [1]], dtype=mstype.float32)\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n\n def test_ops_pynative_dense():\n dense1 = csr_reducesum(csr_tensor, 1)\n dense2 = csrmv(csr_tensor, dense_vector)\n return dense1, dense2\n\n def test_ops_pynative_sparse():\n sparse1 = csr_tensor * dense_tensor\n sparse2 = dense_tensor * csr_tensor\n sparse3 = csr_tensor / dense_tensor\n return sparse1, sparse2, sparse3\n\n test_ops_graph_dense = ms_function(test_ops_pynative_dense)\n test_ops_graph_sparse = ms_function(test_ops_pynative_sparse)\n\n pynative_res_dense = test_ops_pynative_dense()\n graph_res_dense = test_ops_graph_dense()\n expect1 = np.array([[2.], [1.]], dtype=np.float32)\n expect2 = np.array([[2.], [1.]], dtype=np.float32)\n assert np.allclose(pynative_res_dense[0].asnumpy(), expect1)\n assert np.allclose(pynative_res_dense[1].asnumpy(), expect2)\n assert np.allclose(graph_res_dense[0].asnumpy(), expect1)\n assert np.allclose(graph_res_dense[1].asnumpy(), expect2)\n\n pynative_res_sparse = test_ops_pynative_sparse()\n graph_res_sparse = test_ops_graph_sparse()\n expect3 = np.array([2., 1.], dtype=np.float32)\n assert np.allclose(pynative_res_sparse[0].values.asnumpy(), expect3)\n assert np.allclose(pynative_res_sparse[1].values.asnumpy(), expect3)\n assert np.allclose(pynative_res_sparse[2].values.asnumpy(), expect3)\n assert np.allclose(graph_res_sparse[0].values.asnumpy(), expect3)\n assert np.allclose(graph_res_sparse[1].values.asnumpy(), expect3)\n assert np.allclose(graph_res_sparse[2].values.asnumpy(), expect3)\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_csrtensor_export_and_import_mindir():\n \"\"\"\n Feature: Test exporting and loading CSRTensor MindIR.\n Description: Test export and load.\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n class TestCSRTensor(nn.Cell):\n def __init__(self, shape):\n super(TestCSRTensor, self).__init__()\n self.shape = shape\n\n def construct(self, indptr, indices, values):\n return CSRTensor(indptr, indices, values, self.shape)\n\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([2, 1], dtype=mstype.float32)\n shape = (2, 4)\n net = TestCSRTensor(shape)\n\n file_name = \"csrtensor_net\"\n export(net, indptr, indices, values, file_name=file_name, file_format=\"MINDIR\")\n mindir_name = file_name + \".mindir\"\n assert os.path.exists(mindir_name)\n\n out = net(indptr, indices, values)\n graph = load(mindir_name)\n loaded_net = nn.GraphCell(graph)\n outputs_after_load = loaded_net(indptr, indices, values)\n assert np.allclose(out.indptr.asnumpy(), outputs_after_load.indptr.asnumpy())\n assert np.allclose(out.indices.asnumpy(), outputs_after_load.indices.asnumpy())\n assert np.allclose(out.values.asnumpy(), outputs_after_load.values.asnumpy())\n assert out.shape == outputs_after_load.shape\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_onecard\ndef test_csrops_export_and_import_mindir():\n \"\"\"\n Feature: Test exporting and loading CSRTensor MindIR in a net.\n Description: Test export and load.\n Expectation: Success.\n \"\"\"\n class TestCSRNet(nn.Cell):\n def __init__(self, shape):\n super(TestCSRNet, self).__init__()\n self.shape = shape\n self.csr_reducesum = _csr_ops.CSRReduceSum()\n self.csr_mv = _csr_ops.CSRMV()\n\n def construct(self, indptr, indices, values, dence_tensor, dense_vector):\n csr_tensor = CSRTensor(indptr, indices, values, self.shape)\n dense1 = self.csr_reducesum(csr_tensor, 1)\n dense2 = self.csr_mv(csr_tensor, dense_vector)\n dense3 = dense1 * dense2\n sparse1 = csr_tensor * dence_tensor\n sparse2 = dence_tensor * csr_tensor\n return dense1, dense2, dense3, sparse1, sparse2\n\n indptr = Tensor([0, 1, 2], dtype=mstype.int32)\n indices = Tensor([0, 1], dtype=mstype.int32)\n values = Tensor([2, 1], dtype=mstype.float32)\n shape = (2, 4)\n dense_tensor = Tensor([[1., 1, 1, 1], [1, 1, 1, 1]], dtype=mstype.float32)\n dense_vector = Tensor([[1.], [1], [1], [1]], dtype=mstype.float32)\n\n net = TestCSRNet(shape)\n file_name = \"csrops_net\"\n export(net, indptr, indices, values, dense_tensor, dense_vector, file_name=file_name, file_format=\"MINDIR\")\n mindir_name = file_name + \".mindir\"\n assert os.path.exists(mindir_name)\n\n out = net(indptr, indices, values, dense_tensor, dense_vector)\n expect0 = np.array([[2.], [1.]], dtype=np.float32)\n expect1 = np.array([[2.], [1.]], dtype=np.float32)\n expect2 = np.array([[4.], [1.]], dtype=np.float32)\n expect3 = np.array([2., 1.], dtype=np.float32)\n assert np.allclose(out[0].asnumpy(), expect0)\n assert np.allclose(out[1].asnumpy(), expect1)\n assert np.allclose(out[2].asnumpy(), expect2)\n assert np.allclose(out[3].values.asnumpy(), expect3)\n assert np.allclose(out[4].values.asnumpy(), expect3)\n\n graph = load(mindir_name)\n loaded_net = nn.GraphCell(graph)\n outputs_after_load = loaded_net(indptr, indices, values, dense_tensor, dense_vector)\n assert np.allclose(out[0].asnumpy(), outputs_after_load[0].asnumpy())\n assert np.allclose(out[1].asnumpy(), outputs_after_load[1].asnumpy())\n assert np.allclose(out[2].asnumpy(), outputs_after_load[2].asnumpy())\n assert np.allclose(out[3].values.asnumpy(), outputs_after_load[3].values.asnumpy())\n assert np.allclose(out[4].values.asnumpy(), outputs_after_load[4].values.asnumpy())\n assert out[3].shape == outputs_after_load[3].shape\n assert out[4].shape == outputs_after_load[4].shape\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_isinstance_csr_tensor():\n \"\"\"\n Feature: Test isinstance.\n Description: Test: isinstance(x, CSRTensor).\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([2, 1], dtype=mstype.float32)\n shape = (2, 4)\n\n def pynative_test_csr_tensor():\n x = CSRTensor(indptr, indices, values, shape)\n # Test input CSRTensor\n is_tensor = isinstance(x, Tensor)\n is_bool = isinstance(x, bool)\n is_float = isinstance(x, float)\n is_tuple = isinstance(x, (Tensor, CSRTensor, int, float))\n is_csr_tensor = isinstance(x, CSRTensor)\n\n # Test input Tensor\n is_tensor_2 = isinstance(indptr, CSRTensor)\n is_tuple_2 = isinstance(indptr, (Tensor, CSRTensor))\n return is_tensor, is_bool, is_float, is_tuple, is_csr_tensor, is_tensor_2, is_tuple_2\n graph_test_csr_tensor = ms_function(pynative_test_csr_tensor)\n\n out1 = pynative_test_csr_tensor()\n out2 = graph_test_csr_tensor()\n assert out1 == (False, False, False, True, True, False, True)\n assert out2 == (False, False, False, True, True, False, True)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_dtype_csr_tensor():\n \"\"\"\n Feature: Test F.dtype with CSRTensor.\n Description: Test: F.dtype(x).\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n indptr = Tensor([0, 1, 2])\n indices = Tensor([0, 1])\n values = Tensor([2, 1], dtype=mstype.float32)\n shape = (2, 4)\n\n def pynative_test():\n x = CSRTensor(indptr, indices, values, shape)\n return F.dtype(x), x.dtype\n graph_test = ms_function(pynative_test)\n\n out1, out2 = pynative_test()\n out3, out4 = graph_test()\n assert out1 in [mstype.float32]\n assert out2 in [mstype.float32]\n assert out3 in [mstype.float32]\n assert out4 in [mstype.float32]\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_bprop():\n \"\"\"\n Feature: Test back-propagation with CSR-related Ops.\n Description: Test CSRReduceSum, CSRMul, CSRDiv, CSRMV, CSRTensor.to_coo(), CSRTensor.to_dense().\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n csr_reduce_sum = _csr_ops.CSRReduceSum()\n csrmv = _csr_ops.CSRMV()\n grad_op = ops.GradOperation(get_all=True)\n\n @grad_op\n @ms_function\n def test_csr_mul(csr_tensor, dense):\n return csr_tensor * dense\n\n @grad_op\n @ms_function\n def test_csr_div(csr_tensor, dense):\n return csr_tensor / dense\n\n @grad_op\n @ms_function\n def test_csr_reduce_sum(csr_tensor, axis):\n return csr_reduce_sum(csr_tensor, axis)\n\n @grad_op\n @ms_function\n def test_csrmv(csr_tensor, dense):\n return csrmv(csr_tensor, dense)\n\n indptr = Tensor([0, 1, 4, 6], dtype=mstype.int32)\n indices = Tensor([3, 0, 1, 2, 1, 3], dtype=mstype.int32)\n values = Tensor(np.arange(6), dtype=mstype.float32)\n dense_shape = (3, 4)\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n\n csr_mv_arg = Tensor([[1], [2], [3], [4]], dtype=mstype.float32)\n csr_mv_expect_1 = np.array([4, 1, 2, 3, 2, 4], dtype=np.float32)\n csr_mv_expect_2 = np.array([[1], [6], [3], [5]], dtype=np.float32)\n csr_mv_output_1, csr_mv_output_2 = test_csrmv(csr_tensor, csr_mv_arg)\n assert np.allclose(csr_mv_output_1.values.asnumpy(), csr_mv_expect_1)\n assert np.allclose(csr_mv_output_2.asnumpy(), csr_mv_expect_2)\n\n csr_reduce_sum_expect_1 = np.ones(6, dtype=np.float32)\n csr_reduce_sum_output_1 = test_csr_reduce_sum(csr_tensor, 1)\n assert np.allclose(csr_reduce_sum_output_1[0].values.asnumpy(), csr_reduce_sum_expect_1)\n\n csr_mul_arg_1 = Tensor([[1], [2], [3]], dtype=mstype.float32)\n csr_mul_expect_1_1 = np.array([1, 2, 2, 2, 3, 3], dtype=np.float32)\n csr_mul_expect_1_2 = np.array([[0], [6], [9]], dtype=np.float32)\n csr_mul_output_1_1, csr_mul_output_1_2 = test_csr_mul(csr_tensor, csr_mul_arg_1)\n assert np.allclose(csr_mul_output_1_1.values.asnumpy(), csr_mul_expect_1_1)\n assert np.allclose(csr_mul_output_1_2.asnumpy(), csr_mul_expect_1_2)\n\n csr_mul_arg_2 = Tensor(np.arange(12).reshape(3, 4), dtype=mstype.float32)\n csr_mul_expect_2_1 = np.array([3, 4, 5, 6, 9, 11], dtype=np.float32)\n csr_mul_expect_2_2 = np.array([[0, 0, 0, 0], [1, 2, 3, 0], [0, 4, 0, 5]], np.float32)\n csr_mul_output_2_1, csr_mul_output_2_2 = test_csr_mul(csr_tensor, csr_mul_arg_2)\n assert np.allclose(csr_mul_output_2_1.values.asnumpy(), csr_mul_expect_2_1)\n assert np.allclose(csr_mul_output_2_2.asnumpy(), csr_mul_expect_2_2)\n\n csr_div_expect_1_1 = np.array([1, 0.5, 0.5, 0.5, 0.3333333, 0.3333333], dtype=np.float32)\n csr_div_expect_1_2 = np.array([[0], [-1.5], [-1]], dtype=np.float32)\n csr_div_arg_1 = Tensor([[1], [2], [3]], dtype=mstype.float32)\n csr_div_output_1_1, csr_div_output_1_2 = test_csr_div(csr_tensor, csr_div_arg_1)\n assert np.allclose(csr_div_output_1_1.values.asnumpy(), csr_div_expect_1_1)\n assert np.allclose(csr_div_output_1_2.asnumpy(), csr_div_expect_1_2)\n\n csr_div_arg_2 = Tensor(np.arange(1, 13).reshape(3, 4), dtype=mstype.float32)\n csr_div_expect_2_1 = np.array([0.25, 0.2, 0.16666667, 0.14285715, 0.1, 0.0833333], dtype=np.float32)\n csr_div_expect_2_2 = np.array(\n [[0, 0, 0, 0], [-0.04, -0.05555556, -0.06122449, 0], [0, -0.04, 0, -0.03472222]], dtype=np.float32)\n csr_div_output_2_1, csr_div_output_2_2 = test_csr_div(csr_tensor, csr_div_arg_2)\n assert np.allclose(csr_div_output_2_1.values.asnumpy(), csr_div_expect_2_1)\n assert np.allclose(csr_div_output_2_2.asnumpy(), csr_div_expect_2_2)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_csr_method():\n \"\"\"\n Feature: Test csr tensor methods.\n Description: Test csr_tensor.to_coo(), csr_tensor.to_dense().\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n class CSRToCOONet(nn.Cell):\n def construct(self, csr_tensor):\n return csr_tensor.to_coo()\n\n class CSRToDenseNet(nn.Cell):\n def construct(self, csr_tensor):\n return csr_tensor.to_dense()\n\n indptr = Tensor([0, 1, 4, 6], dtype=mstype.int32)\n indices = Tensor([3, 0, 1, 2, 1, 3], dtype=mstype.int32)\n values = Tensor(np.arange(6), dtype=mstype.float32)\n dense_shape = (3, 4)\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n\n to_coo_output = CSRToCOONet()(csr_tensor)\n to_coo_expect_1 = np.array([[0, 3], [1, 0], [1, 1], [1, 2], [2, 1], [2, 3]], dtype=np.int32)\n to_coo_expect_2 = np.arange(6).astype(np.float32)\n assert np.allclose(to_coo_output.indices.asnumpy(), to_coo_expect_1)\n assert np.allclose(to_coo_output.values.asnumpy(), to_coo_expect_2)\n\n to_dense_output = CSRToDenseNet()(csr_tensor)\n to_dense_expect = np.array([[0, 0, 0, 0], [1, 2, 3, 0], [0, 4, 0, 5]], np.float32)\n assert np.allclose(to_dense_output.asnumpy(), to_dense_expect)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_x86_cpu\[email protected]_onecard\ndef test_bprop2():\n \"\"\"\n Feature: Test back-propagation with CSR-related Ops.\n Description: Test back-propagation of make_csr, csr.attributes, csr.methods().\n Expectation: Success.\n \"\"\"\n if get_platform() != \"linux\":\n return\n grad_op = ops.GradOperation(get_all=True)\n indptr = Tensor([0, 1, 4, 6], dtype=mstype.int32)\n indices = Tensor([3, 0, 1, 2, 1, 3], dtype=mstype.int32)\n values = Tensor(np.arange(6) - 3.5, dtype=mstype.float32)\n dense_shape = (3, 4)\n\n @grad_op\n @ms_function\n def test_csr_tensor(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor\n\n @grad_op\n @ms_function\n def test_csr_indptr(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.indptr\n\n @grad_op\n @ms_function\n def test_csr_indices(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.indices\n\n @grad_op\n @ms_function\n def test_csr_values(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.values\n\n @grad_op\n @ms_function\n def test_csr_shape(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.shape\n\n @grad_op\n @ms_function\n def test_csr_cast(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.astype(mstype.int32)\n\n @grad_op\n @ms_function\n def test_csr_dtype(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.dtype\n\n @grad_op\n @ms_function\n def test_csr_to_tuple(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.to_tuple()\n\n @grad_op\n @ms_function\n def test_csr_to_abs(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.abs()\n\n @grad_op\n @ms_function\n def test_csr_to_coo(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.to_coo()\n\n @grad_op\n @ms_function\n def test_csr_to_dense(indptr, indices, values, dense_shape):\n csr_tensor = CSRTensor(indptr, indices, values, dense_shape)\n return csr_tensor.to_dense()\n\n all_zero = (np.zeros(indptr.shape, np.int32), np.zeros(indices.shape, np.int32), np.zeros(values.shape, np.float32))\n values_on = (np.zeros(indptr.shape, np.int32), np.zeros(indices.shape, np.int32), np.ones(values.shape, np.float32))\n values_absgrad = (np.zeros(indptr.shape, np.int32), np.zeros(indices.shape, np.int32), np.sign(values.asnumpy()))\n compare_res(test_csr_tensor(indptr, indices, values, dense_shape), values_on)\n compare_res(test_csr_indptr(indptr, indices, values, dense_shape), all_zero)\n compare_res(test_csr_indices(indptr, indices, values, dense_shape), all_zero)\n compare_res(test_csr_values(indptr, indices, values, dense_shape), values_on)\n compare_res(test_csr_cast(indptr, indices, values, dense_shape), values_on)\n compare_res(test_csr_shape(indptr, indices, values, dense_shape), all_zero)\n compare_res(test_csr_dtype(indptr, indices, values, dense_shape), all_zero)\n compare_res(test_csr_to_tuple(indptr, indices, values, dense_shape), values_on)\n compare_res(test_csr_to_abs(indptr, indices, values, dense_shape), values_absgrad)\n compare_res(test_csr_to_coo(indptr, indices, values, dense_shape), values_on)\n compare_res(test_csr_to_dense(indptr, indices, values, dense_shape), values_on)\n", "# Copyright 2019-2022 Huawei Technologies Co., Ltd\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\"\"\"\nThe module transforms.c_transforms provides common operations, including OneHotOp and TypeCast.\n\"\"\"\nfrom enum import IntEnum\nimport numpy as np\n\nfrom mindspore.common import dtype as mstype\nimport mindspore._c_dataengine as cde\n\nfrom .validators import check_num_classes, check_ms_type, check_fill_value, check_slice_option, check_slice_op, \\\n check_mask_op, check_pad_end, check_concat_type, check_random_transform_ops, check_plugin\nfrom ..core.datatypes import mstype_to_detype\n\n\n# pylint: disable=super-init-not-called\nclass TensorOperation:\n \"\"\"\n Base class Tensor Ops\n \"\"\"\n\n def __init__(self):\n self.callable_op_ = None\n\n def __call__(self, *input_tensor_list):\n tensor_row = []\n for tensor in input_tensor_list:\n try:\n tensor_row.append(cde.Tensor(np.asarray(tensor)))\n except RuntimeError:\n raise TypeError(\"Invalid user input. Got {}: {}, cannot be converted into tensor.\" \\\n .format(type(tensor), tensor))\n if not hasattr(self, 'callable_op_') or self.callable_op_ is None:\n self.callable_op_ = cde.Execute(self.parse())\n output_tensor_list = self.callable_op_(tensor_row)\n for i, element in enumerate(output_tensor_list):\n arr = element.as_array()\n if arr.dtype.char == 'S':\n output_tensor_list[i] = np.char.decode(arr)\n else:\n output_tensor_list[i] = arr\n return output_tensor_list[0] if len(output_tensor_list) == 1 else tuple(output_tensor_list)\n\n def parse(self):\n \"\"\"parse function - not yet implemented\"\"\"\n raise NotImplementedError(\"TensorOperation has to implement parse() method.\")\n\n\nclass OneHot(TensorOperation):\n \"\"\"\n Tensor operation to apply one hot encoding.\n\n Args:\n num_classes (int): Number of classes of objects in dataset.\n It should be larger than the largest label number in the dataset.\n\n Raises:\n TypeError: `num_classes` is not of type int.\n RuntimeError: Input tensor is not of type int.\n RuntimeError: Input tensor is not a 1-D tensor.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> # Assume that dataset has 10 classes, thus the label ranges from 0 to 9\n >>> onehot_op = c_transforms.OneHot(num_classes=10)\n >>> mnist_dataset = mnist_dataset.map(operations=onehot_op, input_columns=[\"label\"])\n \"\"\"\n\n @check_num_classes\n def __init__(self, num_classes):\n self.num_classes = num_classes\n\n def parse(self):\n return cde.OneHotOperation(self.num_classes)\n\n\nclass Fill(TensorOperation):\n \"\"\"\n Tensor operation to fill all elements in the tensor with the specified value.\n The output tensor will have the same shape and type as the input tensor.\n\n Args:\n fill_value (Union[str, bytes, int, float, bool]) : scalar value\n to fill the tensor with.\n\n Raises:\n TypeError: If `fill_value` is not of type str, float, bool, int or bytes.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> import numpy as np\n >>> # generate a 1D integer numpy array from 0 to 4\n >>> def generator_1d():\n ... for i in range(5):\n ... yield (np.array([i]),)\n >>> generator_dataset = ds.GeneratorDataset(generator_1d, column_names=\"col1\")\n >>> # [[0], [1], [2], [3], [4]]\n >>> fill_op = c_transforms.Fill(3)\n >>> generator_dataset = generator_dataset.map(operations=fill_op)\n >>> # [[3], [3], [3], [3], [3]]\n \"\"\"\n\n @check_fill_value\n def __init__(self, fill_value):\n self.fill_value = cde.Tensor(np.array(fill_value))\n\n def parse(self):\n return cde.FillOperation(self.fill_value)\n\n\nclass TypeCast(TensorOperation):\n \"\"\"\n Tensor operation to cast to a given MindSpore data type.\n\n Note:\n This operation supports running on Ascend or GPU platforms by Offload.\n\n Args:\n data_type (mindspore.dtype): mindspore.dtype to be cast to.\n\n Raises:\n TypeError: If `data_type` is not of type bool, int, float or string.\n\n Supported Platforms:\n ``CPU`` ``Ascend`` ``GPU``\n\n Examples:\n >>> import numpy as np\n >>> from mindspore import dtype as mstype\n >>>\n >>> # Generate 1d int numpy array from 0 - 63\n >>> def generator_1d():\n ... for i in range(64):\n ... yield (np.array([i]),)\n >>>\n >>> dataset = ds.GeneratorDataset(generator_1d, column_names='col')\n >>> type_cast_op = c_transforms.TypeCast(mstype.int32)\n >>> dataset = dataset.map(operations=type_cast_op)\n \"\"\"\n\n @check_ms_type\n def __init__(self, data_type):\n data_type = mstype_to_detype(data_type)\n self.data_type = str(data_type)\n\n def parse(self):\n return cde.TypeCastOperation(self.data_type)\n\n\nclass _SliceOption(cde.SliceOption):\n \"\"\"\n Internal class SliceOption to be used with SliceOperation\n\n Args:\n _SliceOption(Union[int, list(int), slice, None, Ellipsis, bool, _SliceOption]):\n\n 1. :py:obj:`int`: Slice this index only along the dimension. Negative index is supported.\n 2. :py:obj:`list(int)`: Slice these indices along the dimension. Negative indices are supported.\n 3. :py:obj:`slice`: Slice the generated indices from the slice object along the dimension.\n 4. :py:obj:`None`: Slice the whole dimension. Similar to :py:obj:`:` in Python indexing.\n 5. :py:obj:`Ellipsis`: Slice the whole dimension. Similar to :py:obj:`:` in Python indexing.\n 6. :py:obj:`boolean`: Slice the whole dimension. Similar to :py:obj:`:` in Python indexing.\n \"\"\"\n\n @check_slice_option\n def __init__(self, slice_option):\n if isinstance(slice_option, int) and not isinstance(slice_option, bool):\n slice_option = [slice_option]\n elif slice_option is Ellipsis:\n slice_option = True\n elif slice_option is None:\n slice_option = True\n super().__init__(slice_option)\n\n\nclass Slice(TensorOperation):\n \"\"\"\n Slice operation to extract a tensor out using the given n slices.\n\n The functionality of Slice is similar to NumPy's indexing feature (Currently only rank-1 tensors are supported).\n\n Args:\n slices (Union[int, list[int], slice, None, Ellipsis]):\n Maximum `n` number of arguments to slice a tensor of rank `n` .\n One object in slices can be one of:\n\n 1. :py:obj:`int`: Slice this index only along the first dimension. Negative index is supported.\n 2. :py:obj:`list(int)`: Slice these indices along the first dimension. Negative indices are supported.\n 3. :py:obj:`slice`: Slice the generated indices from the\n `slice <https://docs.python.org/3.7/library/functions.html?highlight=slice#slice>`_ object along the\n first dimension. Similar to start:stop:step.\n 4. :py:obj:`None`: Slice the whole dimension. Similar to :py:obj:`[:]` in Python indexing.\n 5. :py:obj:`Ellipsis`: Slice the whole dimension, same result with `None`.\n\n Raises:\n TypeError: If `slices` is not of type int, list[int], :py:obj:`slice`, :py:obj:`None` or :py:obj:`Ellipsis`.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> # Data before\n >>> # | col |\n >>> # +---------+\n >>> # | [1,2,3] |\n >>> # +---------|\n >>> data = [[1, 2, 3]]\n >>> numpy_slices_dataset = ds.NumpySlicesDataset(data, [\"col\"])\n >>> # slice indices 1 and 2 only\n >>> numpy_slices_dataset = numpy_slices_dataset.map(operations=c_transforms.Slice(slice(1,3)))\n >>> # Data after\n >>> # | col |\n >>> # +---------+\n >>> # | [2,3] |\n >>> # +---------|\n \"\"\"\n\n @check_slice_op\n def __init__(self, *slices):\n slice_input_ = list(slices)\n slice_input_ = [_SliceOption(slice_dim) for slice_dim in slice_input_]\n self.slice_input_ = slice_input_\n\n def parse(self):\n return cde.SliceOperation(self.slice_input_)\n\n\nclass Relational(IntEnum):\n \"\"\"\n Relationship operator.\n\n Possible enumeration values are: Relational.EQ, Relational.NE, Relational.GT, Relational.GE, Relational.LT,\n Relational.LE.\n\n - Relational.EQ: refers to Equality.\n - Relational.NE: refers not equal, or Inequality.\n - Relational.GT: refers to Greater than.\n - Relational.GE: refers to Greater than or equal to.\n - Relational.LT: refers to Less than.\n - Relational.LE: refers to Less than or equal to.\n \"\"\"\n EQ = 0\n NE = 1\n GT = 2\n GE = 3\n LT = 4\n LE = 5\n\n\nDE_C_RELATIONAL = {Relational.EQ: cde.RelationalOp.EQ,\n Relational.NE: cde.RelationalOp.NE,\n Relational.GT: cde.RelationalOp.GT,\n Relational.GE: cde.RelationalOp.GE,\n Relational.LT: cde.RelationalOp.LT,\n Relational.LE: cde.RelationalOp.LE}\n\n\nclass Mask(TensorOperation):\n r\"\"\"\n Mask content of the input tensor with the given predicate.\n Any element of the tensor that matches the predicate will be evaluated to True, otherwise False.\n\n Args:\n operator (Relational): relational operators, it can be any of [Relational.EQ, Relational.NE, Relational.LT,\n Relational.GT, Relational.LE, Relational.GE], take Relational.EQ as example, EQ refers to equal.\n constant (Union[str, int, float, bool]): Constant to be compared to.\n dtype (mindspore.dtype, optional): Type of the generated mask. Default: mindspore.dtype.bool\\_.\n\n Raises:\n TypeError: `operator` is not of type Relational.\n TypeError: `constant` is not of type string int, float or bool.\n TypeError: `dtype` is not of type mindspore.dtype.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> from mindspore.dataset.transforms.c_transforms import Relational\n >>> # Data before\n >>> # | col |\n >>> # +---------+\n >>> # | [1,2,3] |\n >>> # +---------+\n >>> data = [[1, 2, 3]]\n >>> numpy_slices_dataset = ds.NumpySlicesDataset(data, [\"col\"])\n >>> numpy_slices_dataset = numpy_slices_dataset.map(operations=c_transforms.Mask(Relational.EQ, 2))\n >>> # Data after\n >>> # | col |\n >>> # +--------------------+\n >>> # | [False,True,False] |\n >>> # +--------------------+\n \"\"\"\n\n @check_mask_op\n def __init__(self, operator, constant, dtype=mstype.bool_):\n self.operator = operator\n self.dtype = mstype_to_detype(dtype)\n self.constant = cde.Tensor(np.array(constant))\n\n def parse(self):\n return cde.MaskOperation(DE_C_RELATIONAL[self.operator], self.constant, self.dtype)\n\n\nclass PadEnd(TensorOperation):\n \"\"\"\n Pad input tensor according to pad_shape, input tensor needs to have same rank.\n\n Args:\n pad_shape (list(int)): List of integers representing the shape needed. Dimensions that set to `None` will\n not be padded (i.e., original dim will be used). Shorter dimensions will truncate the values.\n pad_value (Union[str, bytes, int, float, bool], optional): Value used to pad. Default to 0 or empty\n string in case of tensors of strings.\n\n Raises:\n TypeError: If `pad_shape` is not of type list.\n TypeError: If `pad_value` is not of type str, float, bool, int or bytes.\n TypeError: If elements of `pad_shape` is not of type int.\n ValueError: If elements of `pad_shape` is not of positive.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> # Data before\n >>> # | col |\n >>> # +---------+\n >>> # | [1,2,3] |\n >>> # +---------|\n >>> data = [[1, 2, 3]]\n >>> numpy_slices_dataset = ds.NumpySlicesDataset(data, [\"col\"])\n >>> numpy_slices_dataset = numpy_slices_dataset.map(operations=c_transforms.PadEnd(pad_shape=[4],\n ... pad_value=10))\n >>> # Data after\n >>> # | col |\n >>> # +------------+\n >>> # | [1,2,3,10] |\n >>> # +------------|\n \"\"\"\n\n @check_pad_end\n def __init__(self, pad_shape, pad_value=None):\n self.pad_shape = cde.TensorShape(pad_shape)\n self.pad_value = cde.Tensor(np.array(pad_value)) if pad_value is not None else pad_value\n\n def parse(self):\n return cde.PadEndOperation(self.pad_shape, self.pad_value)\n\n\nclass Concatenate(TensorOperation):\n \"\"\"\n Tensor operation that concatenates all columns into a single tensor.\n\n Args:\n axis (int, optional): Concatenate the tensors along given axis (Default=0).\n prepend (numpy.array, optional): NumPy array to be prepended to the already concatenated tensors\n (Default=None).\n append (numpy.array, optional): NumPy array to be appended to the already concatenated tensors (Default=None).\n\n Raises:\n TypeError: If `axis` is not of type int.\n TypeError: If `prepend` is not of type numpy.ndarray.\n TypeError: If `append` is not of type numpy.ndarray.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> import numpy as np\n >>> # concatenate string\n >>> prepend_tensor = np.array([\"dw\", \"df\"], dtype='S')\n >>> append_tensor = np.array([\"dwsdf\", \"df\"], dtype='S')\n >>> concatenate_op = c_transforms.Concatenate(0, prepend_tensor, append_tensor)\n >>> data = [[\"This\",\"is\",\"a\",\"string\"]]\n >>> dataset = ds.NumpySlicesDataset(data)\n >>> dataset = dataset.map(operations=concatenate_op)\n \"\"\"\n\n @check_concat_type\n def __init__(self, axis=0, prepend=None, append=None):\n self.axis = axis\n self.prepend = cde.Tensor(np.array(prepend)) if prepend is not None else prepend\n self.append = cde.Tensor(np.array(append)) if append is not None else append\n\n def parse(self):\n return cde.ConcatenateOperation(self.axis, self.prepend, self.append)\n\n\nclass Duplicate(TensorOperation):\n \"\"\"\n Duplicate the input tensor to output, only support transform one column each time.\n\n Raises:\n RuntimeError: If given tensor has two columns.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> # Data before\n >>> # | x |\n >>> # +---------+\n >>> # | [1,2,3] |\n >>> # +---------+\n >>> data = [[1,2,3]]\n >>> numpy_slices_dataset = ds.NumpySlicesDataset(data, [\"x\"])\n >>> numpy_slices_dataset = numpy_slices_dataset.map(operations=c_transforms.Duplicate(),\n ... input_columns=[\"x\"],\n ... output_columns=[\"x\", \"y\"],\n ... column_order=[\"x\", \"y\"])\n >>> # Data after\n >>> # | x | y |\n >>> # +---------+---------+\n >>> # | [1,2,3] | [1,2,3] |\n >>> # +---------+---------+\n \"\"\"\n\n def parse(self):\n return cde.DuplicateOperation()\n\n\nclass Unique(TensorOperation):\n \"\"\"\n Perform the unique operation on the input tensor, only support transform one column each time.\n\n Return 3 tensor: unique output tensor, index tensor, count tensor.\n\n - Output tensor contains all the unique elements of the input tensor\n in the same order that they occur in the input tensor.\n - Index tensor that contains the index of each element of the input tensor in the unique output tensor.\n - Count tensor that contains the count of each element of the output tensor in the input tensor.\n\n Note:\n Call batch op before calling this function.\n\n Raises:\n RuntimeError: If given Tensor has two columns.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> # Data before\n >>> # | x |\n >>> # +--------------------+\n >>> # | [[0,1,2], [1,2,3]] |\n >>> # +--------------------+\n >>> data = [[[0,1,2], [1,2,3]]]\n >>> dataset = ds.NumpySlicesDataset(data, [\"x\"])\n >>> dataset = dataset.map(operations=c_transforms.Unique(),\n ... input_columns=[\"x\"],\n ... output_columns=[\"x\", \"y\", \"z\"],\n ... column_order=[\"x\", \"y\", \"z\"])\n >>> # Data after\n >>> # | x | y |z |\n >>> # +---------+-----------------+---------+\n >>> # | [0,1,2,3] | [0,1,2,1,2,3] | [1,2,2,1]\n >>> # +---------+-----------------+---------+\n \"\"\"\n\n def parse(self):\n return cde.UniqueOperation()\n\n\nclass Compose(TensorOperation):\n \"\"\"\n Compose a list of transforms into a single transform.\n\n Args:\n transforms (list): List of transformations to be applied.\n\n Raises:\n TypeError: If `transforms` is not of type list.\n ValueError: If `transforms` is empty.\n TypeError: If elements of `transforms` are neither Python callable objects nor data\n processing operations in c_transforms.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> compose = c_transforms.Compose([c_vision.Decode(), c_vision.RandomCrop(512)])\n >>> image_folder_dataset = image_folder_dataset.map(operations=compose)\n \"\"\"\n\n @check_random_transform_ops\n def __init__(self, transforms):\n self.transforms = transforms\n\n def parse(self):\n operations = []\n for op in self.transforms:\n if op and getattr(op, 'parse', None):\n operations.append(op.parse())\n else:\n operations.append(op)\n return cde.ComposeOperation(operations)\n\n\nclass RandomApply(TensorOperation):\n \"\"\"\n Randomly perform a series of transforms with a given probability.\n\n Args:\n transforms (list): List of transformations to be applied.\n prob (float, optional): The probability to apply the transformation list (default=0.5).\n\n Raises:\n TypeError: If `transforms` is not of type list.\n ValueError: If `transforms` is empty.\n TypeError: If elements of `transforms` are neither Python callable objects nor data\n processing operations in c_transforms.\n TypeError: If `prob` is not of type float.\n ValueError: If `prob` is not in range [0.0, 1.0].\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> rand_apply = c_transforms.RandomApply([c_vision.RandomCrop(512)])\n >>> image_folder_dataset = image_folder_dataset.map(operations=rand_apply)\n \"\"\"\n\n @check_random_transform_ops\n def __init__(self, transforms, prob=0.5):\n self.transforms = transforms\n self.prob = prob\n\n def parse(self):\n operations = []\n for op in self.transforms:\n if op and getattr(op, 'parse', None):\n operations.append(op.parse())\n else:\n operations.append(op)\n return cde.RandomApplyOperation(self.prob, operations)\n\n\nclass RandomChoice(TensorOperation):\n \"\"\"\n Randomly select one transform from a list of transforms to perform operation.\n\n Args:\n transforms (list): List of transformations to be chosen from to apply.\n\n Raises:\n TypeError: If `transforms` is not of type list.\n ValueError: If `transforms` is empty.\n TypeError: If elements of `transforms` are neither Python callable objects nor data\n processing operations in c_transforms.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> rand_choice = c_transforms.RandomChoice([c_vision.CenterCrop(50), c_vision.RandomCrop(512)])\n >>> image_folder_dataset = image_folder_dataset.map(operations=rand_choice)\n \"\"\"\n\n @check_random_transform_ops\n def __init__(self, transforms):\n self.transforms = transforms\n\n def parse(self):\n operations = []\n for op in self.transforms:\n if op and getattr(op, 'parse', None):\n operations.append(op.parse())\n else:\n operations.append(op)\n return cde.RandomChoiceOperation(operations)\n\n\nclass Plugin(TensorOperation):\n \"\"\"\n Plugin support for MindData. Use this class to dynamically load a .so file (shared library) and execute its symbols.\n\n Args:\n lib_path (str): Path to .so file which is compiled to support MindData plugin.\n func_name (str): Name of the function to load from the .so file.\n user_args (str, optional): Serialized args to pass to the plugin. Only needed if \"func_name\" requires one.\n\n Raises:\n TypeError: If `lib_path` is not of type string.\n TypeError: If `func_name` is not of type string.\n TypeError: If `user_args` is not of type string.\n\n Supported Platforms:\n ``CPU``\n\n Examples:\n >>> plugin = c_transforms.Plugin(\"pluginlib.so\", \"PluginDecode\")\n >>> image_folder_dataset = image_folder_dataset.map(operations=plugin)\n \"\"\"\n\n @check_plugin\n def __init__(self, lib_path, func_name, user_args=None):\n self.lib_path = lib_path\n self.func_name = func_name\n self.user_args = str() if (user_args is None) else user_args\n\n def parse(self):\n return cde.PluginOperation(self.lib_path, self.func_name, self.user_args)\n", "# Copyright 2020 Huawei Technologies Co., Ltd\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\"\"\"\nTesting Duplicate op in DE\n\"\"\"\nimport numpy as np\n\nimport mindspore.dataset as ds\nimport mindspore.dataset.transforms.transforms as ops\n\n\ndef compare(array):\n data = ds.NumpySlicesDataset([array], column_names=\"x\")\n array = np.array(array)\n data = data.map(operations=ops.Duplicate(), input_columns=[\"x\"], output_columns=[\"x\", \"y\"],\n column_order=[\"x\", \"y\"])\n for d in data.create_dict_iterator(num_epochs=1, output_numpy=True):\n np.testing.assert_array_equal(array, d[\"x\"])\n np.testing.assert_array_equal(array, d[\"y\"])\n\n\ndef test_duplicate_basics():\n compare([1, 2, 3])\n compare([b\"1\", b\"2\", b\"3\"])\n\n\nif __name__ == \"__main__\":\n test_duplicate_basics()\n", "# Copyright 2019 Huawei Technologies Co., Ltd\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\"\"\"\nCifar100 convert tool for MindRecord.\n\"\"\"\n\nfrom importlib import import_module\nimport os\nimport numpy as np\n\nfrom mindspore import log as logger\nfrom .cifar100 import Cifar100\nfrom ..common.exceptions import PathNotExistsError\nfrom ..filewriter import FileWriter\nfrom ..shardutils import check_filename, ExceptionThread, SUCCESS, FAILED\n\ntry:\n cv2 = import_module(\"cv2\")\nexcept ModuleNotFoundError:\n cv2 = None\n\n__all__ = ['Cifar100ToMR']\n\n\nclass Cifar100ToMR:\n \"\"\"\n A class to transform from cifar100 to MindRecord.\n\n Note:\n For details about Examples, please refer to `Converting the CIFAR-10 Dataset <https://\n www.mindspore.cn/tutorials/zh-CN/master/advanced/dataset/record.html#converting-the-cifar-10-dataset>`_.\n\n Args:\n source (str): The cifar100 directory to be transformed.\n destination (str): MindRecord file path to transform into, ensure that no file with the same name\n exists in the directory.\n\n Raises:\n ValueError: If source or destination is invalid.\n \"\"\"\n\n def __init__(self, source, destination):\n check_filename(source)\n self.source = source\n\n files = os.listdir(self.source)\n train_data_flag = False\n test_data_flag = False\n for file in files:\n if file == \"train\":\n train_data_flag = True\n if file == \"test\":\n test_data_flag = True\n if not train_data_flag:\n raise PathNotExistsError(\"train\")\n\n if not test_data_flag:\n raise PathNotExistsError(\"test\")\n\n check_filename(destination)\n self.destination = destination\n self.writer = None\n\n def run(self, fields=None):\n \"\"\"\n Execute transformation from cifar100 to MindRecord.\n\n Args:\n fields (list[str]): A list of index field, e.g.[\"fine_label\", \"coarse_label\"]. Default: None.\n\n Returns:\n MSRStatus, SUCCESS or FAILED.\n \"\"\"\n if fields and not isinstance(fields, list):\n raise ValueError(\"The parameter fields should be None or list\")\n\n cifar100_data = Cifar100(self.source, False)\n cifar100_data.load_data()\n\n images = cifar100_data.images\n logger.info(\"train images: {}\".format(images.shape))\n fine_labels = cifar100_data.fine_labels\n logger.info(\"train images fine label: {}\".format(fine_labels.shape))\n coarse_labels = cifar100_data.coarse_labels\n logger.info(\"train images coarse label: {}\".format(coarse_labels.shape))\n\n test_images = cifar100_data.Test.images\n logger.info(\"test images: {}\".format(test_images.shape))\n test_fine_labels = cifar100_data.Test.fine_labels\n logger.info(\"test images fine label: {}\".format(fine_labels.shape))\n test_coarse_labels = cifar100_data.Test.coarse_labels\n logger.info(\"test images coarse label: {}\".format(coarse_labels.shape))\n\n data_list = _construct_raw_data(images, fine_labels, coarse_labels)\n test_data_list = _construct_raw_data(test_images, test_fine_labels, test_coarse_labels)\n\n if _generate_mindrecord(self.destination, data_list, fields, \"img_train\") != SUCCESS:\n return FAILED\n if _generate_mindrecord(self.destination + \"_test\", test_data_list, fields, \"img_test\") != SUCCESS:\n return FAILED\n return SUCCESS\n\n def transform(self, fields=None):\n \"\"\"\n Encapsulate the run function to exit normally\n\n Args:\n fields (list[str]): A list of index field, e.g.[\"fine_label\", \"coarse_label\"]. Default: None.\n\n Returns:\n MSRStatus, SUCCESS or FAILED.\n \"\"\"\n\n t = ExceptionThread(target=self.run, kwargs={'fields': fields})\n t.daemon = True\n t.start()\n t.join()\n if t.exitcode != 0:\n raise t.exception\n return t.res\n\n\ndef _construct_raw_data(images, fine_labels, coarse_labels):\n \"\"\"\n Construct raw data from cifar100 data.\n\n Args:\n images (list): image list from cifar100.\n fine_labels (list): fine label list from cifar100.\n coarse_labels (list): coarse label list from cifar100.\n\n Returns:\n list[dict], data dictionary constructed from cifar100.\n \"\"\"\n if not cv2:\n raise ModuleNotFoundError(\"opencv-python module not found, please use pip install it.\")\n\n raw_data = []\n for i, img in enumerate(images):\n fine_label = np.int(fine_labels[i][0])\n coarse_label = np.int(coarse_labels[i][0])\n _, img = cv2.imencode(\".jpeg\", img[..., [2, 1, 0]])\n row_data = {\"id\": int(i),\n \"data\": img.tobytes(),\n \"fine_label\": int(fine_label),\n \"coarse_label\": int(coarse_label)}\n raw_data.append(row_data)\n return raw_data\n\n\ndef _generate_mindrecord(file_name, raw_data, fields, schema_desc):\n \"\"\"\n Generate MindRecord file from raw data.\n\n Args:\n file_name (str): File name of MindRecord File.\n fields (list[str]): Fields would be set as index which\n could not belong to blob fields and type could not be 'array' or 'bytes'.\n raw_data (dict): Dict of raw data.\n schema_desc (str): String of schema description.\n\n Returns:\n MSRStatus, SUCCESS or FAILED.\n \"\"\"\n schema = {\"id\": {\"type\": \"int64\"}, \"fine_label\": {\"type\": \"int64\"},\n \"coarse_label\": {\"type\": \"int64\"}, \"data\": {\"type\": \"bytes\"}}\n\n logger.info(\"transformed MindRecord schema is: {}\".format(schema))\n\n writer = FileWriter(file_name, 1)\n writer.add_schema(schema, schema_desc)\n if fields and isinstance(fields, list):\n writer.add_index(fields)\n writer.write_raw_data(raw_data)\n return writer.commit()\n", "# Copyright 2022 Huawei Technologies Co., Ltd\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\nimport numpy as np\nimport pytest\n\nimport mindspore as ms\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore.common.api import _cell_graph_executor\nfrom mindspore.ops import composite as C\nfrom mindspore.ops import operations as P\nfrom tests.ut.python.ops.test_math_ops import VirtualLoss\n\ncontext.set_context(mode=context.GRAPH_MODE)\n\n\ngrad_all = C.GradOperation(get_all=True)\n\n\nclass Net(nn.Cell):\n def __init__(self, strategy1, strategy2, num_segments):\n super(Net, self).__init__()\n self.merge_op = P.UnsortedSegmentProd().shard((strategy1, strategy2))\n self.num_segments = num_segments\n\n def construct(self, vectors, segment_ids):\n predict = self.merge_op(vectors, segment_ids, self.num_segments)\n return predict\n\n\nclass GradWrap(nn.Cell):\n def __init__(self, network):\n super(GradWrap, self).__init__()\n self.network = network\n\n def construct(self, x, y):\n return grad_all(self.network)(x, y)\n\n\nclass NetWithLoss(nn.Cell):\n def __init__(self, network):\n super(NetWithLoss, self).__init__()\n self.network = network\n self.loss = VirtualLoss()\n\n def construct(self, x, y):\n predict = self.network(x, y)\n return self.loss(predict)\n\n\ndef compile_graph(x, y, segments, strategy1, strategy2, auto=False):\n if auto:\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\")\n else:\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net = GradWrap(NetWithLoss(Net(strategy1, strategy2, segments)))\n net.set_auto_parallel()\n net.set_train()\n _cell_graph_executor.compile(net, x, y)\n\n\ndef test_unsortedsegmentprod_model_parallel_slice_1d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with model parallel strategy, slice 1d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=8, global_rank=0)\n x = Tensor(np.ones(8), ms.float32)\n y = Tensor(np.ones(8), ms.int32)\n num_segments = 16\n strategy1 = (8,)\n strategy2 = (8,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_no_slice_1d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with no slice strategy in semi auto parallel, slice 1d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=8, global_rank=0)\n x = Tensor(np.ones(8), ms.float32)\n y = Tensor(np.ones(8), ms.int32)\n num_segments = 16\n strategy1 = (1,)\n strategy2 = (1,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_index_slice_2d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with model parallel strategy, slice 2d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 8)), ms.float32)\n y = Tensor(np.arange(4), ms.int32)\n num_segments = 4\n strategy1 = (4, 1)\n strategy2 = (4,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_index_slice_3d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with model parallel strategy, slice 3d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 4, 8)), ms.float32)\n y = Tensor(np.ones((4, 4)), ms.int32)\n num_segments = 16\n strategy1 = (2, 2, 1)\n strategy2 = (2, 2)\n with pytest.raises(ValueError):\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_vector_slice_2d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with model parallel strategy, slice 2d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 8)), ms.float32)\n y = Tensor(np.ones(4), ms.int32)\n num_segments = 4\n strategy1 = (1, 4)\n strategy2 = (1,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_vector_slice_3d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with model parallel, slice 3d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 8, 8)), ms.float32)\n y = Tensor(np.ones(4), ms.int32)\n num_segments = 4\n strategy1 = (1, 2, 2)\n strategy2 = (1,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_index_vector_slice_2d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with strategy in semi auto parallel, slice 2d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 8)), ms.float32)\n y = Tensor(np.ones(4), ms.int32)\n num_segments = 4\n strategy1 = (2, 2)\n strategy2 = (2,)\n compile_graph(x, y, num_segments, strategy1, strategy2)\n\n\ndef test_unsortedsegmentprod_model_parallel_index_vector_slice_3d():\n \"\"\"\n Feature: distribute operator unsorted_segment_prod in auto parallel.\n Description: unsorted_segment_prod net with strategy in semi auto parallel, slice 3d.\n Expectation: compile done without error.\n \"\"\"\n context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 4, 8)), ms.float32)\n y = Tensor(np.ones((4, 4)), ms.int32)\n num_segments = 16\n strategy1 = (2, 1, 2)\n strategy2 = (2, 1)\n with pytest.raises(ValueError):\n compile_graph(x, y, num_segments, strategy1, strategy2)\n", "# Copyright 2021 Huawei Technologies Co., Ltd\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\"\"\"ConfusionMatrixMetric & ConfusionMatrix.\"\"\"\nimport numpy as np\nfrom mindspore._checkparam import Validator as validator\nfrom .metric import Metric, rearrange_inputs\n\n\nclass ConfusionMatrix(Metric):\n \"\"\"\n Computes the confusion matrix, which is commonly used to evaluate the performance of classification models,\n including binary classification and multiple classification.\n\n If you only need confusion matrix, use this class. If you want to calculate other metrics, such as 'PPV',\n 'TPR', 'TNR', etc., use class 'mindspore.metrics.ConfusionMatrixMetric'.\n\n Args:\n num_classes (int): Number of classes in the dataset.\n normalize (str): Normalization mode for confusion matrix. Default: \"no_norm\". Choose from:\n\n - **'no_norm'** (None) - No Normalization is used. Default: None.\n - **'target'** (str) - Normalization based on target value.\n - **'prediction'** (str) - Normalization based on predicted value.\n - **'all'** (str) - Normalization over the whole matrix.\n\n threshold (float): The threshold used to compare with the input tensor. Default: 0.5.\n\n Supported Platforms:\n ``Ascend`` ``GPU`` ``CPU``\n\n Examples:\n >>> import numpy as np\n >>> from mindspore import nn, Tensor\n >>>\n >>> x = Tensor(np.array([1, 0, 1, 0]))\n >>> y = Tensor(np.array([1, 0, 0, 1]))\n >>> metric = nn.ConfusionMatrix(num_classes=2, normalize='no_norm', threshold=0.5)\n >>> metric.clear()\n >>> metric.update(x, y)\n >>> output = metric.eval()\n >>> print(output)\n [[1. 1.]\n [1. 1.]]\n \"\"\"\n def __init__(self, num_classes, normalize=\"no_norm\", threshold=0.5):\n super(ConfusionMatrix, self).__init__()\n\n self.num_classes = validator.check_value_type(\"num_classes\", num_classes, [int])\n if normalize not in [\"target\", \"prediction\", \"all\", \"no_norm\"]:\n raise ValueError(\"For 'ConfusionMatrix', the argument 'normalize' should be in \"\n \"['all', 'prediction', 'label', 'no_norm'(None)], but got {}.\".format(normalize))\n\n self.normalize = normalize\n self.threshold = validator.check_value_type(\"threshold\", threshold, [float])\n self.clear()\n\n def clear(self):\n \"\"\"Clears the internal evaluation result.\"\"\"\n self.confusion_matrix = np.zeros((self.num_classes, self.num_classes))\n self._is_update = False\n\n @rearrange_inputs\n def update(self, *inputs):\n \"\"\"\n Update state with y_pred and y.\n\n Args:\n inputs: Input `y_pred` and `y`. `y_pred` and `y` are a `Tensor`, list or numpy.ndarray.\n `y_pred` is the predicted value, `y` is the true value.\n The shape of `y_pred` is :math:`(N, C, ...)` or :math:`(N, ...)`.\n The shape of `y` is :math:`(N, ...)`.\n\n Raises:\n ValueError: If the number of inputs is not 2.\n ValueError: If the dim of y_pred and y are not equal.\n \"\"\"\n if len(inputs) != 2:\n raise ValueError(\"For 'ConfusionMatrix.update', it needs 2 inputs (predicted value, true value), \"\n \"but got {}.\".format(len(inputs)))\n\n y_pred = self._convert_data(inputs[0])\n y = self._convert_data(inputs[1])\n\n if not (y_pred.ndim == y.ndim or y_pred.ndim == y.ndim + 1):\n raise ValueError(f\"For 'ConfusionMatrix.update', predicted value (input[0]) and true value \"\n f\"(input[1]) should have same dimensions, or the dimension of predicted value \"\n f\"equals the dimension of true value add 1, but got predicted value ndim: \"\n f\"{y_pred.ndim}, true value ndim: {y.ndim}.\")\n\n if y_pred.ndim == y.ndim + 1:\n y_pred = np.argmax(y_pred, axis=1)\n\n if y_pred.ndim == y.ndim and y_pred.dtype in (np.float16, np.float32, np.float64):\n y_pred = (y_pred >= self.threshold).astype(int)\n\n trans = (y.reshape(-1) * self.num_classes + y_pred.reshape(-1)).astype(int)\n bincount = np.bincount(trans, minlength=self.num_classes ** 2)\n confusion_matrix = bincount.reshape(self.num_classes, self.num_classes)\n self.confusion_matrix += confusion_matrix\n self._is_update = True\n\n def eval(self):\n \"\"\"\n Computes confusion matrix.\n\n Returns:\n numpy.ndarray, the computed result.\n \"\"\"\n\n if not self._is_update:\n raise RuntimeError(\"Please call the 'update' method before calling 'eval' method.\")\n\n confusion_matrix = self.confusion_matrix.astype(float)\n\n matrix_target = confusion_matrix / confusion_matrix.sum(axis=1, keepdims=True)\n matrix_pred = confusion_matrix / confusion_matrix.sum(axis=0, keepdims=True)\n matrix_all = confusion_matrix / confusion_matrix.sum()\n normalize_dict = {\"target\": matrix_target,\n \"prediction\": matrix_pred,\n \"all\": matrix_all}\n\n if self.normalize == \"no_norm\":\n return confusion_matrix\n\n matrix = normalize_dict.get(self.normalize)\n if matrix[np.isnan(matrix)].size != 0:\n matrix[np.isnan(matrix)] = 0\n\n return matrix\n\n\nclass ConfusionMatrixMetric(Metric):\n r\"\"\"\n Computes metrics related to confusion matrix. The calculation based on full-scale tensor, average values of\n batch, class channel and iteration are collected. All metrics supported by the interface are listed in comments\n of `metric_name`.\n\n If you want to calculate metrics related to confusion matrix, such as 'PPV', 'TPR', 'TNR', use this class.\n If you only want to calculate confusion matrix, please use 'mindspore.metrics.ConfusionMatrix'.\n\n Args:\n skip_channel (bool): Whether to skip the measurement calculation on the first channel of the predicted output.\n Default: True.\n metric_name (str): Names of supported metrics , users can also set the industry common aliases for them. Choose\n from: [\"sensitivity\", \"specificity\", \"precision\", \"negative predictive value\", \"miss rate\",\n \"fall out\", \"false discovery rate\", \"false omission rate\", \"prevalence threshold\",\n \"threat score\", \"accuracy\", \"balanced accuracy\", \"f1 score\",\n \"matthews correlation coefficient\", \"fowlkes mallows index\", \"informedness\", \"markedness\"].\n Default: \"sensitivity\".\n calculation_method (bool): If true, the measurement for each sample will be calculated first.\n If not, the confusion matrix of all samples will be accumulated first.\n As for classification task, 'calculation_method' should be False. Default: False.\n decrease (str): The reduction method on data batch. `decrease` takes effect only when calculation_method\n is True. Default: \"mean\". Choose from:\n [\"none\", \"mean\", \"sum\", \"mean_batch\", \"sum_batch\", \"mean_channel\", \"sum_channel\"].\n\n Supported Platforms:\n ``Ascend`` ``GPU`` ``CPU``\n\n Examples:\n >>> import numpy as np\n >>> from mindspore import nn, Tensor\n >>>\n >>> metric = nn.ConfusionMatrixMetric(skip_channel=True, metric_name=\"tpr\",\n ... calculation_method=False, decrease=\"mean\")\n >>> metric.clear()\n >>> x = Tensor(np.array([[[0], [1]], [[1], [0]]]))\n >>> y = Tensor(np.array([[[0], [1]], [[0], [1]]]))\n >>> metric.update(x, y)\n >>> avg_output = metric.eval()\n >>> print(avg_output)\n [0.5]\n \"\"\"\n def __init__(self,\n skip_channel=True,\n metric_name=\"sensitivity\",\n calculation_method=False,\n decrease=\"mean\"):\n super(ConfusionMatrixMetric, self).__init__()\n\n self.confusion_matrix = _ConfusionMatrix(skip_channel=skip_channel, metric_name=metric_name,\n calculation_method=calculation_method, decrease=decrease)\n self.skip_channel = validator.check_value_type(\"skip_channel\", skip_channel, [bool])\n self.calculation_method = validator.check_value_type(\"calculation_method\", calculation_method, [bool])\n self.metric_name = validator.check_value_type(\"metric_name\", metric_name, [str])\n decrease_list = [\"none\", \"mean\", \"sum\", \"mean_batch\", \"sum_batch\", \"mean_channel\", \"sum_channel\"]\n decrease = validator.check_value_type(\"decrease\", decrease, [str])\n self.decrease = validator.check_string(decrease, decrease_list, \"decrease\")\n self.clear()\n\n def clear(self):\n \"\"\"Clears the internal evaluation result.\"\"\"\n self._total_num = 0\n self._class_num = 0\n self._total_tp = 0.0\n self._total_fp = 0.0\n self._total_tn = 0.0\n self._total_fn = 0.0\n\n @rearrange_inputs\n def update(self, *inputs):\n \"\"\"\n Update state with predictions and targets.\n\n Args:\n inputs: Input `y_pred` and `y`. `y_pred` and `y` are a `Tensor`, list or numpy.ndarray.\n `y_pred`: The batch data shape is :math:`(N, C, ...)` or :math:`(N, ...)`, representing onehot format\n or category index format respectively. As for classification tasks, y_pred should have the shape [BN]\n where N is larger than 1. As for segmentation tasks, the shape should be [BNHW] or [BNHWD].\n `y`: It must be one-hot format. The batch data shape is :math:`(N, C, ...)`.\n\n Raises:\n ValueError: If the number of the inputs is not 2.\n \"\"\"\n if len(inputs) != 2:\n raise ValueError(\"For 'ConfusionMatrixMetric.update', it needs 2 inputs (predicted value, true value), \"\n \"but got {}.\".format(len(inputs)))\n\n y_pred = self._convert_data(inputs[0])\n y = self._convert_data(inputs[1])\n\n if self.calculation_method:\n score, not_nans = self.confusion_matrix(y_pred, y)\n not_nans = int(not_nans.item())\n self._total_num += score.item() * not_nans\n self._class_num += not_nans\n else:\n confusion_matrix = self.confusion_matrix(y_pred, y)\n confusion_matrix, _ = _decrease_metric(confusion_matrix, \"sum\")\n self._total_tp += confusion_matrix[0].item()\n self._total_fp += confusion_matrix[1].item()\n self._total_tn += confusion_matrix[2].item()\n self._total_fn += confusion_matrix[3].item()\n\n def eval(self):\n \"\"\"\n Computes confusion matrix metric.\n\n Returns:\n ndarray, the computed result.\n \"\"\"\n\n if self.calculation_method:\n if self._class_num == 0:\n raise RuntimeError(\"The 'ConfusionMatrixMetric' can not be calculated, because the number of samples \"\n \"is 0, please check whether your inputs(predicted value, true value) are empty, or \"\n \"has called update method before calling eval method.\")\n\n return self._total_num / self._class_num\n\n confusion_matrix = np.array([self._total_tp, self._total_fp, self._total_tn, self._total_fn])\n return _compute_confusion_matrix_metric(self.metric_name, confusion_matrix)\n\n\nclass _ConfusionMatrix:\n \"\"\"\n Compute confusion matrix related metrics.\n\n Args:\n skip_channel (bool): Whether to skip the measurement calculation on the first channel of the predicted\n output. Default: True.\n metric_name (str): The names of indicators are in the following range. Of course, you can also set the industry\n common aliases for these indicators.\n calculation_method (bool): If true, the measurement for each sample will be calculated first. If not, the\n confusion matrix for each image (the output of function '_get_confusion_matrix')\n will be returned. In this way, users should achieve the confusion matrixes for all\n images during an epochand then use '_compute_confusion_matrix_metric' to calculate\n the metric. Default: False.\n decrease (Union[DecreaseMetric, str]): [\"none\", \"mean\", \"sum\", \"mean_batch\", \"sum_batch\", \"mean_channel\",\n \"sum_channel\"]\n Define the mode to reduce the calculation result of one batch of data.\n Decrease is used only if calculation_method is True. Default: \"mean\".\n \"\"\"\n\n def __init__(self, skip_channel=True, metric_name=\"hit_rate\", calculation_method=False,\n decrease=\"mean\"):\n super().__init__()\n self.skip_channel = skip_channel\n self.metric_name = metric_name\n self.calculation_method = calculation_method\n self.decrease = decrease\n\n def __call__(self, y_pred, y):\n \"\"\"\n 'y_preds' is expected to have binarized predictions and 'y' should be in one-hot format.\n\n Args:\n - **y_pred** (ndarray) - Input data to compute. It must be one-hot format and first dim is batch.\n - **y** (ndarray) - Ground truth to compute the metric. It must be one-hot format and first dim is batch.\n\n Raises:\n ValueError: If `metric_name` is empty.\n ValueError: when `y_pred` has less than two dimensions.\n \"\"\"\n if not np.all(y.astype(np.uint8) == y):\n raise ValueError(\"For 'ConfusionMatrix.update', the true value (input[1]) should be a binarized ndarray.\")\n\n dims = y_pred.ndim\n if dims < 2:\n raise ValueError(f\"For 'ConfusionMatrix.update', the predicted value (input[0]) should have at least 2 \"\n f\"dimensions, but got {dims}.\")\n\n if dims == 2 or (dims == 3 and y_pred.shape[-1] == 1):\n if self.calculation_method:\n self.calculation_method = False\n\n confusion_matrix = _get_confusion_matrix(y_pred=y_pred, y=y, skip_channel=self.skip_channel)\n\n if self.calculation_method:\n if isinstance(self.metric_name, str):\n sub_confusion_matrix = _compute_confusion_matrix_metric(self.metric_name, confusion_matrix)\n chart, not_nans = _decrease_metric(sub_confusion_matrix, self.decrease)\n return chart, not_nans\n\n if not self.metric_name:\n raise ValueError(\"For 'ConfusionMatrix', the argument 'metric_name' cannot be None.\")\n\n results = []\n for metric_name in self.metric_name:\n sub_confusion_matrix = _compute_confusion_matrix_metric(metric_name, confusion_matrix)\n chart, not_nans = _decrease_metric(sub_confusion_matrix, self.decrease)\n results.append(chart)\n results.append(not_nans)\n return results\n\n return confusion_matrix\n\n\ndef _get_confusion_matrix(y_pred, y, skip_channel=True):\n \"\"\"\n The confusion matrix is calculated. An array of shape [BC4] is returned. The third dimension represents each channel\n of each sample in the input batch.Where B is the batch size and C is the number of classes to be calculated.\n\n Args:\n y_pred (ndarray): input data to compute. It must be one-hot format and first dim is batch.\n The values should be binarized.\n y (ndarray): ground truth to compute the metric. It must be one-hot format and first dim is batch.\n The values should be binarized.\n skip_channel (bool): whether to skip metric computation on the first channel of the predicted output.\n Default: True.\n\n Raises:\n ValueError: when `y_pred` and `y` have different shapes.\n \"\"\"\n\n if not skip_channel:\n y = y[:, 1:] if y.shape[1] > 1 else y\n y_pred = y_pred[:, 1:] if y_pred.shape[1] > 1 else y_pred\n\n y = y.astype(float)\n y_pred = y_pred.astype(float)\n validator.check('y_shape', y.shape, 'y_pred_shape', y_pred.shape)\n batch_size, n_class = y_pred.shape[:2]\n y_pred = y_pred.reshape(batch_size, n_class, -1)\n y = y.reshape(batch_size, n_class, -1)\n tp = ((y_pred + y) == 2).astype(float)\n tn = ((y_pred + y) == 0).astype(float)\n tp = tp.sum(axis=2)\n tn = tn.sum(axis=2)\n p = y.sum(axis=2)\n n = y.shape[-1] - p\n fn = p - tp\n fp = n - tn\n\n return np.stack([tp, fp, tn, fn], axis=-1)\n\n\ndef _decrease_mean(not_nans, chart):\n not_nans = not_nans.sum(axis=1)\n chart = np.where(not_nans > 0, chart.sum(axis=1) / not_nans, np.zeros(1, dtype=float))\n\n not_nans = (not_nans > 0).astype(float).sum(axis=0)\n chart = np.where(not_nans > 0, chart.sum(axis=0) / not_nans, np.zeros(1, dtype=float))\n\n return not_nans, chart\n\n\ndef _decrease_sum(not_nans, chart):\n not_nans = not_nans.sum(axis=(0, 1))\n chart = np.sum(chart, axis=(0, 1))\n\n return not_nans, chart\n\n\ndef _decrease_mean_batch(not_nans, chart):\n not_nans = not_nans.sum(axis=0)\n chart = np.where(not_nans > 0, chart.sum(axis=0) / not_nans, np.zeros(1, dtype=float))\n\n return not_nans, chart\n\n\ndef _decrease_sum_batch(not_nans, chart):\n not_nans = not_nans.sum(axis=0)\n chart = chart.sum(axis=0)\n\n return not_nans, chart\n\n\ndef _decrease_mean_channel(not_nans, chart):\n not_nans = not_nans.sum(axis=1)\n chart = np.where(not_nans > 0, chart.sum(axis=1) / not_nans, np.zeros(1, dtype=float))\n\n return not_nans, chart\n\n\ndef _decrease_sum_channel(not_nans, chart):\n not_nans = not_nans.sum(axis=1)\n chart = chart.sum(axis=1)\n\n return not_nans, chart\n\n\ndef _decrease_none(not_nans, chart):\n return not_nans, chart\n\n\ndef _decrease_metric(chart, decrease=\"mean\"):\n \"\"\"\n This function is used to reduce the calculated metrics for each class of each example.\n\n Args:\n chart (ndarray): A data table containing the calculated measurement scores for each batch and class.\n The first two dims should be batch and class.\n decrease (str): Define the mode to reduce computation result of 1 batch data. Decrease will only be employed\n when 'calculation_method' is True. Default: \"mean\".\n \"\"\"\n\n nans = np.isnan(chart)\n not_nans = (~nans).astype(float)\n chart[nans] = 0\n\n decrease_dict = {\"mean\": _decrease_mean(not_nans, chart),\n \"sum\": _decrease_sum(not_nans, chart),\n \"mean_batch\": _decrease_mean_batch,\n \"sum_batch\": _decrease_sum_batch(not_nans, chart),\n \"mean_channel\": _decrease_mean_channel(not_nans, chart),\n \"sum_channel\": _decrease_sum_channel(not_nans, chart),\n \"none\": _decrease_none(not_nans, chart)}\n not_nans, chart = decrease_dict.get(decrease)\n\n return chart, not_nans\n\n\ndef _calculate_tpr(tp, p):\n \"\"\"Calculate tpr.\"\"\"\n return tp, p\n\n\ndef _calculate_tnr(tn, n):\n \"\"\"Calculate tnr.\"\"\"\n return tn, n\n\n\ndef _calculate_ppv(tp, fp):\n \"\"\"Calculate ppv.\"\"\"\n return tp, (tp + fp)\n\n\ndef _calculate_npv(tn, fn):\n \"\"\"Calculate npv.\"\"\"\n return tn, (tn + fn)\n\n\ndef _calculate_fnr(fn, p):\n \"\"\"Calculate fnr.\"\"\"\n return fn, p\n\n\ndef _calculate_fpr(fp, n):\n \"\"\"Calculate fpr.\"\"\"\n return fp, n\n\n\ndef _calculate_fdr(tp, fp):\n \"\"\"Calculate fdr.\"\"\"\n return fp, (fp + tp)\n\n\ndef _calculate_for(tn, fn):\n \"\"\"Calculate for.\"\"\"\n return fn, (fn + tn)\n\n\ndef _calculate_pt(tp, tn, p, n):\n \"\"\"Calculate pt.\"\"\"\n tpr = np.where(p > 0, tp / p, np.array(float(\"nan\")))\n tnr = np.where(n > 0, tn / n, np.array(float(\"nan\")))\n numerator = np.sqrt(tpr * (1.0 - tnr)) + tnr - 1.0\n denominator = tpr + tnr - 1.0\n\n return numerator, denominator\n\n\ndef _calculate_ts(tp, fp, fn):\n \"\"\"Calculate ts.\"\"\"\n return tp, (tp + fn + fp)\n\n\ndef _calculate_acc(tp, tn, p, n):\n \"\"\"Calculate acc.\"\"\"\n return (tp + tn), (p + n)\n\n\ndef _calculate_ba(tp, tn, p, n):\n \"\"\"Calculate ba.\"\"\"\n tpr = np.where(p > 0, tp / p, np.array(float(\"nan\")))\n tnr = np.where(n > 0, tn / n, np.array(float(\"nan\")))\n numerator, denominator = (tpr + tnr), 2.0\n\n return numerator, denominator\n\n\ndef _calculate_f1(tp, fp, fn):\n \"\"\"Calculate f1.\"\"\"\n return tp * 2.0, (tp * 2.0 + fn + fp)\n\n\ndef _calculate_mcc(tp, fp, tn, fn):\n \"\"\"Calculate mcc.\"\"\"\n numerator = tp * tn - fp * fn\n denominator = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))\n\n return numerator, denominator\n\n\ndef _calculate_fm(tp, fp, p):\n \"\"\"Calculate fm.\"\"\"\n tpr = np.where(p > 0, tp / p, np.array(float(\"nan\")))\n ppv = np.where((tp + fp) > 0, tp / (tp + fp), np.array(float(\"nan\")))\n numerator = np.sqrt(ppv * tpr)\n denominator = 1.0\n\n return numerator, denominator\n\n\ndef _calculate_bm(tp, tn, p, n):\n \"\"\"Calculate bm.\"\"\"\n tpr = np.where(p > 0, tp / p, np.array(float(\"nan\")))\n tnr = np.where(n > 0, tn / n, np.array(float(\"nan\")))\n numerator = tpr + tnr - 1.0\n denominator = 1.0\n\n return numerator, denominator\n\n\ndef _calculate_mk(tp, fp, tn, fn):\n \"\"\"Calculate mk.\"\"\"\n ppv = np.where((tp + fp) > 0, tp / (tp + fp), np.array(float(\"nan\")))\n npv = np.where((tn + fn) > 0, tn / (tn + fn), np.array(float(\"nan\")))\n npv = tn / (tn + fn)\n numerator = ppv + npv - 1.0\n denominator = 1.0\n\n return numerator, denominator\n\n\ndef _compute_confusion_matrix_metric(metric_name, confusion_matrix):\n \"\"\"\n This function is used to compute confusion matrix related metric.\n\n Args:\n metric_name (str): Refer to conflusionmatrixmetric 'metric_name'. Some of the metrics have multiple aliases\n (as shown in the wikipedia page aforementioned), and you can also input those names instead.\n confusion_matrix (ndarray): Refer to '_get_confusion_matrix'.\n\n Raises:\n ValueError: when the size of the last dimension of confusion_matrix is not 4.\n NotImplementedError: when specify a not implemented metric_name.\n\n \"\"\"\n\n metric = _check_metric_name(metric_name)\n\n input_dim = confusion_matrix.ndim\n if input_dim == 1:\n confusion_matrix = np.expand_dims(confusion_matrix, 0)\n if confusion_matrix.shape[-1] != 4:\n raise ValueError(f\"For 'ConfusionMatrix', the size of the last dimension of confusion_matrix should be 4, \"\n f\"but got {confusion_matrix.shape[-1]}.\")\n\n tp = confusion_matrix[..., 0]\n fp = confusion_matrix[..., 1]\n tn = confusion_matrix[..., 2]\n fn = confusion_matrix[..., 3]\n p = tp + fn\n n = fp + tn\n\n metric_name_dict = {\"tpr\": _calculate_tpr(tp, p),\n \"tnr\": _calculate_tnr(tn, n),\n \"ppv\": _calculate_ppv(tp, fp),\n \"npv\": _calculate_npv(tn, fn),\n \"fnr\": _calculate_fnr(fn, p),\n \"fpr\": _calculate_fpr(fp, n),\n \"fdr\": _calculate_fdr(tp, fp),\n \"for\": _calculate_for(tn, fn),\n \"pt\": _calculate_pt(tp, tn, p, n),\n \"ts\": _calculate_ts(tp, fp, fn),\n \"acc\": _calculate_acc(tp, tn, p, n),\n \"ba\": _calculate_ba(tp, tn, p, n),\n \"f1\": _calculate_f1(tp, fp, fn),\n \"mcc\": _calculate_mcc(tp, fp, tn, fn),\n \"fm\": _calculate_fm(tp, fp, p),\n \"bm\": _calculate_bm(tp, tn, p, n),\n \"mk\": _calculate_mk(tp, fp, tn, fn)}\n numerator, denominator = metric_name_dict.get(metric)\n\n if isinstance(denominator, np.ndarray):\n result = np.where(denominator != 0, numerator / denominator, np.array(float(\"nan\")))\n else:\n result = numerator / denominator\n return result\n\n\ndef _check_metric_name(metric_name):\n \"\"\"\n There are many metrics related to confusion matrix, and some of the metrics have more than one names. In addition,\n some of the names are very long. Therefore, this function is used to check and simplify the name.\n\n Returns:\n Simplified metric name.\n\n Raises:\n NotImplementedError: when the metric is not implemented.\n \"\"\"\n metric_name = metric_name.replace(\" \", \"_\")\n metric_name = metric_name.lower()\n metric_name_dict = {\"sensitivity\": \"tpr\",\n \"recall\": \"tpr\",\n \"hit_rate\": \"tpr\",\n \"true_positive_rate\": \"tpr\",\n \"tpr\": \"tpr\",\n \"specificity\": \"tnr\",\n \"selectivity\": \"tnr\",\n \"true_negative_rate\": \"tnr\",\n \"tnr\": \"tnr\",\n \"precision\": \"ppv\",\n \"positive_predictive_value\": \"ppv\",\n \"ppv\": \"ppv\",\n \"negative_predictive_value\": \"npv\",\n \"npv\": \"npv\",\n \"miss_rate\": \"fnr\",\n \"false_negative_rate\": \"fnr\",\n \"fnr\": \"fnr\",\n \"fall_out\": \"fpr\",\n \"false_positive_rate\": \"fpr\",\n \"fpr\": \"fpr\",\n \"false_discovery_rate\": \"fdr\",\n \"fdr\": \"fdr\",\n \"false_omission_rate\": \"for\",\n \"for\": \"for\",\n \"prevalence_threshold\": \"pt\",\n \"pt\": \"pt\",\n \"threat_score\": \"ts\",\n \"critical_success_index\": \"ts\",\n \"ts\": \"ts\",\n \"csi\": \"ts\",\n \"accuracy\": \"acc\",\n \"acc\": \"acc\",\n \"balanced_accuracy\": \"ba\",\n \"ba\": \"ba\",\n \"f1_score\": \"f1\",\n \"f1\": \"f1\",\n \"matthews_correlation_coefficient\": \"mcc\",\n \"mcc\": \"mcc\",\n \"fowlkes_mallows_index\": \"fm\",\n \"fm\": \"fm\",\n \"informedness\": \"bm\",\n \"bookmaker_informedness\": \"bm\",\n \"bm\": \"bm\",\n \"markedness\": \"mk\",\n \"deltap\": \"mk\",\n \"mk\": \"mk\"}\n\n metric_name_info = metric_name_dict.get(metric_name)\n\n if metric_name_info is None:\n raise NotImplementedError(\"The metric is not implemented.\")\n\n return metric_name_info\n", "# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport pytest\n\nfrom mindspore import context, Tensor\nfrom mindspore.ops import operations as P\n\n\ndef inplace_op_np(op, x: np.ndarray, v: np.ndarray, indices):\n result = x.copy()\n if v.shape[0] == 1:\n v = np.squeeze(v, axis=0)\n if op == 'add':\n result[indices, :] += v\n elif op == 'sub':\n result[indices, :] -= v\n return result\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_onecard\[email protected]('shape, indice_len', [((10, 4, 3, 2), 4), ((5, 2, 4, 6), 3)])\[email protected]('dtype', [np.float32, np.float16, np.int32])\ndef test_inplace_add(shape, indice_len, dtype):\n \"\"\"\n Feature: test InplaceAdd\n Description: test InplaceAdd\n Expectation: result is the same as expected\n \"\"\"\n context.set_context(device_target='CPU')\n x = np.random.random(shape).astype(dtype)\n v = np.random.random((indice_len,) + shape[1:]).astype(dtype)\n indices = np.random.choice(list(range(shape[0])), indice_len, replace=False)\n indices = tuple((int(i) for i in indices))\n\n result = P.InplaceAdd(indices)(Tensor(x), Tensor(v))\n expected = inplace_op_np('add', x, v, indices)\n np.allclose(result.asnumpy(), expected)\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_onecard\[email protected]('shape, indice', [((10, 4, 3, 2), 4), ((5, 2, 4, 6), 3)])\[email protected]('dtype', [np.float32, np.float16, np.int32])\ndef test_inplace_add_1d(shape, indice, dtype):\n \"\"\"\n Feature: test InplaceAdd\n Description: test InplaceAdd\n Expectation: result is the same as expected\n \"\"\"\n context.set_context(device_target='CPU')\n x = np.random.random(shape).astype(dtype)\n v = np.random.random((1,) + shape[1:]).astype(dtype)\n\n result = P.InplaceAdd(indice)(Tensor(x), Tensor(v))\n expected = inplace_op_np('add', x, v, indice)\n np.allclose(result.asnumpy(), expected)\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_onecard\[email protected]('shape, indice_len', [((10, 4, 3, 2), 4), ((5, 2, 4, 6), 3)])\[email protected]('dtype', [np.float32, np.float16, np.int32])\ndef test_inplace_sub(shape, indice_len, dtype):\n \"\"\"\n Feature: test InplaceSub\n Description: test InplaceSub\n Expectation: result is the same as expected\n \"\"\"\n context.set_context(device_target='CPU')\n x = np.random.random(shape).astype(dtype)\n v = np.random.random((indice_len,) + shape[1:]).astype(dtype)\n indices = np.random.choice(list(range(shape[0])), indice_len, replace=False)\n indices = tuple((int(i) for i in indices))\n\n result = P.InplaceSub(indices)(Tensor(x), Tensor(v))\n expected = inplace_op_np('sub', x, v, indices)\n np.allclose(result.asnumpy(), expected)\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_onecard\[email protected]('shape, indice', [((10, 4, 3, 2), 4), ((5, 2, 4, 6), 3)])\[email protected]('dtype', [np.float32, np.float16, np.int32])\ndef test_inplace_sub_1d(shape, indice, dtype):\n \"\"\"\n Feature: test InplaceAdd\n Description: test InplaceAdd\n Expectation: result is the same as expected\n \"\"\"\n context.set_context(device_target='CPU')\n x = np.random.random(shape).astype(dtype)\n v = np.random.random((1,) + shape[1:]).astype(dtype)\n\n result = P.InplaceSub(indice)(Tensor(x), Tensor(v))\n expected = inplace_op_np('sub', x, v, indice)\n np.allclose(result.asnumpy(), expected)\n", "# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\" test graph fallback control flow.\"\"\"\nimport pytest\nimport numpy as np\nimport mindspore as ms\nfrom mindspore import Tensor, ms_function, context, Parameter\nfrom mindspore import dtype as mstype\nfrom mindspore.nn import Cell\n\ncontext.set_context(mode=context.GRAPH_MODE)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_1():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(1)\n while x < Tensor(7):\n x *= 2\n return x\n res = control_flow_while()\n assert res == 8\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_2():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(7).astype(\"int32\")\n y = Tensor(0).astype(\"int32\")\n while x >= y:\n y += x\n return y\n res = control_flow_while()\n assert res == 14\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_3():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(7).astype(\"int32\")\n y = Tensor(0).astype(\"int32\")\n while x >= Tensor(0).astype(\"int32\"):\n y += x\n x = Tensor(-1).astype(\"int32\")\n return y\n res = control_flow_while()\n assert res == 7\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_two_cond_1():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(1)\n y = Tensor(8)\n z = Tensor(12)\n while x < y and x + y <= z:\n y = x + y + z\n x += Tensor(3)\n return x + y\n res = control_flow_while()\n assert res == 25\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_two_cond_2():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(7).astype(\"int32\")\n y = Tensor(0).astype(\"int32\")\n while Tensor(0).astype(\"int32\") < x and y >= x - Tensor(7).astype(\"int32\"):\n y += x\n x += Tensor(-6).astype(\"int32\")\n return y\n res = control_flow_while()\n assert res == 8\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_two_cond_3():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = np.array([1, 2, 3, 4, 5])\n y = Tensor(1)\n while sum(x) > 0 and y >= 0:\n x -= 3\n return Tensor(sum(x))\n res = control_flow_while()\n assert res == 0\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_param():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n class Net(Cell):\n def __init__(self):\n super(Net, self).__init__()\n self.param_a = Parameter(Tensor([1], ms.float32), name=\"name_a\")\n\n def construct(self):\n x = Tensor(7).astype(\"int32\")\n y = Tensor(0).astype(\"int32\")\n while x >= self.param_a:\n y += x\n x -= Tensor(-2).astype(\"int32\")\n self.param_a += y\n return self.param_a\n\n net = Net()\n res = net()\n assert res == 24\n\n\[email protected](reason='Not support graph fallback feature yet')\ndef test_single_while_numpy():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = np.array([1, 2, 3, 4, 5])\n y = np.array([0, 2, 4, 6, 8])\n while (x == y).any():\n x[x == 2] = 1\n return Tensor(x)\n res = control_flow_while()\n assert (res.asnumpy() == [1, 1, 3, 4, 5]).all()\n\n\[email protected](reason='Not support variable in graph fallback feature yet')\ndef test_single_while_builtin_function_abs_tensor():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(-11, mstype.float32)\n y = Tensor(0)\n while abs(x) > Tensor(2):\n x += Tensor(4)\n y += Tensor(1)\n return x, y\n res_x, res_y = control_flow_while()\n assert res_x == 1\n assert res_y == 3\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_builtin_function_abs_numpy():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = np.array(-11)\n y = np.array(0)\n while abs(x) > 2:\n x += np.array(4)\n y += np.array(1)\n return Tensor(x), Tensor(y)\n res_x, res_y = control_flow_while()\n assert res_x == 1\n assert res_y == 3\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_builtin_function_abs():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = -11\n y = 0\n while abs(x) > 2:\n x += 4\n y += 1\n return Tensor(x), Tensor(y)\n res_x, res_y = control_flow_while()\n assert res_x == 1\n assert res_y == 3\n\n\[email protected](reason='Not support variable in graph fallback feature yet')\ndef test_single_while_builtin_function_max_tensor():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = Tensor(3)\n y = Tensor(5)\n while max(x, y) > 3:\n x -= Tensor(4)\n y -= Tensor(1)\n return x, y\n res_x, res_y = control_flow_while()\n assert res_x == -5\n assert res_y == 3\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_single_while_builtin_function_max_numpy():\n \"\"\"\n Feature: JIT Fallback\n Description: Test fallback with control flow.\n Expectation: No exception.\n \"\"\"\n @ms_function\n def control_flow_while():\n x = np.array(3)\n y = np.array(5)\n while max(x, y) > 3:\n x -= np.array(4)\n y -= np.array(1)\n return Tensor(x), Tensor(y)\n res_x, res_y = control_flow_while()\n assert res_x == -5\n assert res_y == 3\n", "# Copyright 2021-2022 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"\r\nTest QMnistDataset operator\r\n\"\"\"\r\nimport os\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport mindspore.dataset as ds\r\nimport mindspore.dataset.vision.transforms as vision\r\nfrom mindspore import log as logger\r\n\r\nDATA_DIR = \"../data/dataset/testQMnistData\"\r\n\r\n\r\ndef load_qmnist(path, usage, compat=True):\r\n \"\"\"\r\n load QMNIST data\r\n \"\"\"\r\n image_path = []\r\n label_path = []\r\n image_ext = \"images-idx3-ubyte\"\r\n label_ext = \"labels-idx2-int\"\r\n train_prefix = \"qmnist-train\"\r\n test_prefix = \"qmnist-test\"\r\n nist_prefix = \"xnist\"\r\n assert usage in [\"train\", \"test\", \"nist\", \"all\"]\r\n if usage == \"train\":\r\n image_path.append(os.path.realpath(os.path.join(path, train_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, train_prefix + \"-\" + label_ext)))\r\n elif usage == \"test\":\r\n image_path.append(os.path.realpath(os.path.join(path, test_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, test_prefix + \"-\" + label_ext)))\r\n elif usage == \"nist\":\r\n image_path.append(os.path.realpath(os.path.join(path, nist_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, nist_prefix + \"-\" + label_ext)))\r\n elif usage == \"all\":\r\n image_path.append(os.path.realpath(os.path.join(path, train_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, train_prefix + \"-\" + label_ext)))\r\n image_path.append(os.path.realpath(os.path.join(path, test_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, test_prefix + \"-\" + label_ext)))\r\n image_path.append(os.path.realpath(os.path.join(path, nist_prefix + \"-\" + image_ext)))\r\n label_path.append(os.path.realpath(os.path.join(path, nist_prefix + \"-\" + label_ext)))\r\n\r\n assert len(image_path) == len(label_path)\r\n\r\n images = []\r\n labels = []\r\n for i, _ in enumerate(image_path):\r\n with open(image_path[i], 'rb') as image_file:\r\n image_file.read(16)\r\n image = np.fromfile(image_file, dtype=np.uint8)\r\n image = image.reshape(-1, 28, 28, 1)\r\n images.append(image)\r\n with open(label_path[i], 'rb') as label_file:\r\n label_file.read(12)\r\n label = np.fromfile(label_file, dtype='>u4')\r\n label = label.reshape(-1, 8)\r\n labels.append(label)\r\n\r\n images = np.concatenate(images, 0)\r\n labels = np.concatenate(labels, 0)\r\n if compat:\r\n return images, labels[:, 0]\r\n return images, labels\r\n\r\n\r\ndef visualize_dataset(images, labels):\r\n \"\"\"\r\n Helper function to visualize the dataset samples\r\n \"\"\"\r\n num_samples = len(images)\r\n for i in range(num_samples):\r\n plt.subplot(1, num_samples, i + 1)\r\n plt.imshow(images[i].squeeze(), cmap=plt.cm.gray)\r\n plt.title(labels[i])\r\n plt.show()\r\n\r\n\r\ndef test_qmnist_content_check():\r\n \"\"\"\r\n Validate QMnistDataset image readings\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset Op with content check\")\r\n for usage in [\"train\", \"test\", \"nist\", \"all\"]:\r\n data1 = ds.QMnistDataset(DATA_DIR, usage, True, num_samples=10, shuffle=False)\r\n images, labels = load_qmnist(DATA_DIR, usage, True)\r\n num_iter = 0\r\n # in this example, each dictionary has keys \"image\" and \"label\"\r\n image_list, label_list = [], []\r\n for i, data in enumerate(data1.create_dict_iterator(num_epochs=1, output_numpy=True)):\r\n image_list.append(data[\"image\"])\r\n label_list.append(\"label {}\".format(data[\"label\"]))\r\n np.testing.assert_array_equal(data[\"image\"], images[i])\r\n np.testing.assert_array_equal(data[\"label\"], labels[i])\r\n num_iter += 1\r\n assert num_iter == 10\r\n\r\n for usage in [\"train\", \"test\", \"nist\", \"all\"]:\r\n data1 = ds.QMnistDataset(DATA_DIR, usage, False, num_samples=10, shuffle=False)\r\n images, labels = load_qmnist(DATA_DIR, usage, False)\r\n num_iter = 0\r\n # in this example, each dictionary has keys \"image\" and \"label\"\r\n image_list, label_list = [], []\r\n for i, data in enumerate(data1.create_dict_iterator(num_epochs=1, output_numpy=True)):\r\n image_list.append(data[\"image\"])\r\n label_list.append(\"label {}\".format(data[\"label\"]))\r\n np.testing.assert_array_equal(data[\"image\"], images[i])\r\n np.testing.assert_array_equal(data[\"label\"], labels[i])\r\n num_iter += 1\r\n assert num_iter == 10\r\n\r\n\r\ndef test_qmnist_basic():\r\n \"\"\"\r\n Validate QMnistDataset\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset Op\")\r\n\r\n # case 1: test loading whole dataset\r\n data1 = ds.QMnistDataset(DATA_DIR, \"train\", True)\r\n num_iter1 = 0\r\n for _ in data1.create_dict_iterator(num_epochs=1):\r\n num_iter1 += 1\r\n assert num_iter1 == 10\r\n\r\n # case 2: test num_samples\r\n data2 = ds.QMnistDataset(DATA_DIR, \"train\", True, num_samples=5)\r\n num_iter2 = 0\r\n for _ in data2.create_dict_iterator(num_epochs=1):\r\n num_iter2 += 1\r\n assert num_iter2 == 5\r\n\r\n # case 3: test repeat\r\n data3 = ds.QMnistDataset(DATA_DIR, \"train\", True)\r\n data3 = data3.repeat(5)\r\n num_iter3 = 0\r\n for _ in data3.create_dict_iterator(num_epochs=1):\r\n num_iter3 += 1\r\n assert num_iter3 == 50\r\n\r\n # case 4: test batch with drop_remainder=False\r\n data4 = ds.QMnistDataset(DATA_DIR, \"train\", True, num_samples=10)\r\n assert data4.get_dataset_size() == 10\r\n assert data4.get_batch_size() == 1\r\n data4 = data4.batch(batch_size=7) # drop_remainder is default to be False\r\n assert data4.get_dataset_size() == 2\r\n assert data4.get_batch_size() == 7\r\n num_iter4 = 0\r\n for _ in data4.create_dict_iterator(num_epochs=1):\r\n num_iter4 += 1\r\n assert num_iter4 == 2\r\n\r\n # case 5: test batch with drop_remainder=True\r\n data5 = ds.QMnistDataset(DATA_DIR, \"train\", True, num_samples=10)\r\n assert data5.get_dataset_size() == 10\r\n assert data5.get_batch_size() == 1\r\n data5 = data5.batch(batch_size=3, drop_remainder=True) # the rest of incomplete batch will be dropped\r\n assert data5.get_dataset_size() == 3\r\n assert data5.get_batch_size() == 3\r\n num_iter5 = 0\r\n for _ in data5.create_dict_iterator(num_epochs=1):\r\n num_iter5 += 1\r\n assert num_iter5 == 3\r\n\r\n # case 6: test get_col_names\r\n dataset = ds.QMnistDataset(DATA_DIR, \"train\", True, num_samples=10)\r\n assert dataset.get_col_names() == [\"image\", \"label\"]\r\n\r\n\r\ndef test_qmnist_pk_sampler():\r\n \"\"\"\r\n Test QMnistDataset with PKSampler\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset Op with PKSampler\")\r\n golden = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n sampler = ds.PKSampler(10)\r\n data = ds.QMnistDataset(DATA_DIR, \"nist\", True, sampler=sampler)\r\n num_iter = 0\r\n label_list = []\r\n for item in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n label_list.append(item[\"label\"])\r\n num_iter += 1\r\n np.testing.assert_array_equal(golden, label_list)\r\n assert num_iter == 10\r\n\r\n\r\ndef test_qmnist_sequential_sampler():\r\n \"\"\"\r\n Test QMnistDataset with SequentialSampler\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset Op with SequentialSampler\")\r\n num_samples = 10\r\n sampler = ds.SequentialSampler(num_samples=num_samples)\r\n data1 = ds.QMnistDataset(DATA_DIR, \"train\", True, sampler=sampler)\r\n data2 = ds.QMnistDataset(DATA_DIR, \"train\", True, shuffle=False, num_samples=num_samples)\r\n label_list1, label_list2 = [], []\r\n num_iter = 0\r\n for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):\r\n label_list1.append(item1[\"label\"].asnumpy())\r\n label_list2.append(item2[\"label\"].asnumpy())\r\n num_iter += 1\r\n np.testing.assert_array_equal(label_list1, label_list2)\r\n assert num_iter == num_samples\r\n\r\n\r\ndef test_qmnist_exception():\r\n \"\"\"\r\n Test error cases for QMnistDataset\r\n \"\"\"\r\n logger.info(\"Test error cases for MnistDataset\")\r\n error_msg_1 = \"sampler and shuffle cannot be specified at the same time\"\r\n with pytest.raises(RuntimeError, match=error_msg_1):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, shuffle=False, sampler=ds.PKSampler(3))\r\n\r\n error_msg_2 = \"sampler and sharding cannot be specified at the same time\"\r\n with pytest.raises(RuntimeError, match=error_msg_2):\r\n ds.QMnistDataset(DATA_DIR, \"nist\", True, sampler=ds.PKSampler(1), num_shards=2, shard_id=0)\r\n\r\n error_msg_3 = \"num_shards is specified and currently requires shard_id as well\"\r\n with pytest.raises(RuntimeError, match=error_msg_3):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, num_shards=10)\r\n\r\n error_msg_4 = \"shard_id is specified but num_shards is not\"\r\n with pytest.raises(RuntimeError, match=error_msg_4):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, shard_id=0)\r\n\r\n error_msg_5 = \"Input shard_id is not within the required interval\"\r\n with pytest.raises(ValueError, match=error_msg_5):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, num_shards=5, shard_id=-1)\r\n with pytest.raises(ValueError, match=error_msg_5):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, num_shards=5, shard_id=5)\r\n with pytest.raises(ValueError, match=error_msg_5):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, num_shards=2, shard_id=5)\r\n\r\n error_msg_6 = \"num_parallel_workers exceeds\"\r\n with pytest.raises(ValueError, match=error_msg_6):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, shuffle=False, num_parallel_workers=0)\r\n with pytest.raises(ValueError, match=error_msg_6):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, shuffle=False, num_parallel_workers=256)\r\n with pytest.raises(ValueError, match=error_msg_6):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, shuffle=False, num_parallel_workers=-2)\r\n\r\n error_msg_7 = \"Argument shard_id\"\r\n with pytest.raises(TypeError, match=error_msg_7):\r\n ds.QMnistDataset(DATA_DIR, \"train\", True, num_shards=2, shard_id=\"0\")\r\n\r\n def exception_func(item):\r\n raise Exception(\"Error occur!\")\r\n\r\n error_msg_8 = \"The corresponding data files\"\r\n with pytest.raises(RuntimeError, match=error_msg_8):\r\n data = ds.QMnistDataset(DATA_DIR, \"train\", True)\r\n data = data.map(operations=exception_func, input_columns=[\"image\"], num_parallel_workers=1)\r\n for _ in data.__iter__():\r\n pass\r\n with pytest.raises(RuntimeError, match=error_msg_8):\r\n data = ds.QMnistDataset(DATA_DIR, \"train\", True)\r\n data = data.map(operations=vision.Decode(), input_columns=[\"image\"], num_parallel_workers=1)\r\n data = data.map(operations=exception_func, input_columns=[\"image\"], num_parallel_workers=1)\r\n for _ in data.__iter__():\r\n pass\r\n with pytest.raises(RuntimeError, match=error_msg_8):\r\n data = ds.QMnistDataset(DATA_DIR, \"train\", True)\r\n data = data.map(operations=exception_func, input_columns=[\"label\"], num_parallel_workers=1)\r\n for _ in data.__iter__():\r\n pass\r\n\r\n\r\ndef test_qmnist_visualize(plot=False):\r\n \"\"\"\r\n Visualize QMnistDataset results\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset visualization\")\r\n\r\n data1 = ds.QMnistDataset(DATA_DIR, \"train\", True, num_samples=10, shuffle=False)\r\n num_iter = 0\r\n image_list, label_list = [], []\r\n for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n image = item[\"image\"]\r\n label = item[\"label\"]\r\n image_list.append(image)\r\n label_list.append(\"label {}\".format(label))\r\n assert isinstance(image, np.ndarray)\r\n assert image.shape == (28, 28, 1)\r\n assert image.dtype == np.uint8\r\n assert label.dtype == np.uint32\r\n num_iter += 1\r\n assert num_iter == 10\r\n if plot:\r\n visualize_dataset(image_list, label_list)\r\n\r\n\r\ndef test_qmnist_usage():\r\n \"\"\"\r\n Validate QMnistDataset image readings\r\n \"\"\"\r\n logger.info(\"Test QMnistDataset usage flag\")\r\n\r\n def test_config(usage, path=None):\r\n path = DATA_DIR if path is None else path\r\n try:\r\n data = ds.QMnistDataset(path, usage=usage, compat=True, shuffle=False)\r\n num_rows = 0\r\n for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):\r\n num_rows += 1\r\n except (ValueError, TypeError, RuntimeError) as e:\r\n return str(e)\r\n return num_rows\r\n\r\n assert test_config(\"train\") == 10\r\n assert test_config(\"test\") == 10\r\n assert test_config(\"nist\") == 10\r\n assert test_config(\"all\") == 30\r\n assert \"usage is not within the valid set of ['train', 'test', 'test10k', 'test50k', 'nist', 'all']\" in\\\r\n test_config(\"invalid\")\r\n assert \"Argument usage with value ['list'] is not of type [<class 'str'>]\" in test_config([\"list\"])\r\n\r\n\r\nif __name__ == '__main__':\r\n test_qmnist_content_check()\r\n test_qmnist_basic()\r\n test_qmnist_pk_sampler()\r\n test_qmnist_sequential_sampler()\r\n test_qmnist_exception()\r\n test_qmnist_visualize(plot=True)\r\n test_qmnist_usage()\r\n", "# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nimport numpy as np\nimport pytest\n\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nimport mindspore.context as context\nfrom mindspore.ops import operations as P\n\n\ndef check_dropout_nd_by_keep_prob(input_x, output, output_mask, keep_prob):\n \"\"\"\n Feature: check mindspore Dropout2D or Dropout3D's output and mask.\n Description: output shape, mask shap and keep_pro will be checked.\n Expectation: match to mindspore Dropout2D or Dropout3D.\n \"\"\"\n # Check input, output, mask all have same shape\n assert input_x.shape == output.shape == output_mask.shape\n data_type = input_x.dtype\n error = 1e-6\n if data_type == np.float16:\n error = 1e-3\n data_shape = input_x.shape\n channels = data_shape[0] * data_shape[1]\n features = 1\n if len(input_x.shape) == 4:\n # HW\n features = features * data_shape[-2] * data_shape[-1]\n else:\n # DHW\n features = features * data_shape[-3] * data_shape[-2] * data_shape[-1]\n if keep_prob == 0.0:\n input_x_by_keep_prob = input_x.astype(data_type).reshape(channels, features)\n else:\n input_x_by_keep_prob = (input_x / keep_prob).astype(data_type).reshape(channels, features)\n output_reshape = output.reshape(channels, features)\n mask_reshape = output_mask.reshape(channels, features)\n # Check each channel is entirely True or False and output match to input_x\n for channel in range(channels):\n if np.all(output_reshape[channel] == 0):\n assert int(np.all(mask_reshape[channel])) == 0\n else:\n assert np.all(mask_reshape[channel])\n np.allclose(input_x_by_keep_prob[channel], output_reshape[channel], error, error)\n\n\nclass Dropout3DNet(nn.Cell):\n def __init__(self, keep_prob):\n super(Dropout3DNet, self).__init__()\n self.drop = P.Dropout3D(keep_prob)\n\n def construct(self, x):\n return self.drop(x)\n\n\nclass Dropout2DNet(nn.Cell):\n def __init__(self, keep_prob):\n super(Dropout2DNet, self).__init__()\n self.drop = P.Dropout2D(keep_prob)\n\n def construct(self, x):\n return self.drop(x)\n\n\[email protected]\[email protected]_onecard\[email protected]_x86_cpu\[email protected](\"keep_prob\", [0.0, 0.4, 1.0])\[email protected](\"data_shape\", [(32, 16, 4, 5), (32, 16, 2, 5, 4)])\[email protected](\"data_type\", [np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64])\ndef test_dropout_nd(data_shape, data_type, keep_prob):\n \"\"\"\n Feature: Test Dropout2D and Dropout3D.\n Description: The input shape is 4d or 5d.\n Expectation: check it by function check_dropout_nd_by_keep_prob.\n \"\"\"\n input_data = np.ones(data_shape).astype(data_type)\n if len(input_data.shape) == 4:\n dropout_nd = Dropout2DNet(keep_prob)\n else:\n dropout_nd = Dropout3DNet(keep_prob)\n output, mask = dropout_nd(Tensor(input_data))\n context.set_context(mode=context.GRAPH_MODE)\n check_dropout_nd_by_keep_prob(input_data, output.asnumpy(), mask.asnumpy(), keep_prob)\n context.set_context(mode=context.PYNATIVE_MODE)\n output, mask = dropout_nd(Tensor(input_data))\n check_dropout_nd_by_keep_prob(input_data, output.asnumpy(), mask.asnumpy(), keep_prob)\n", "# Copyright 2021 Huawei Technologies Co., Ltd\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\nimport math\nimport pytest\nimport numpy as np\nfrom mindspore import context\nfrom mindspore import nn\nfrom mindspore import Tensor\nfrom mindspore.common.parameter import ParameterTuple\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.ops import composite as c\n\n\nclass GradOfAllInputsAndParams(nn.Cell):\n def __init__(self, network, sens_param):\n super(GradOfAllInputsAndParams, self).__init__()\n self.grad = c.GradOperation(get_all=True, get_by_list=True, sens_param=sens_param)\n self.network = network\n self.params = ParameterTuple(self.network.trainable_params())\n\n def construct(self, *inputs):\n gout = self.grad(self.network, self.params)(*inputs)\n return gout\n\n\nclass GRU(nn.Cell):\n def __init__(self, input_size, hidden_size, num_layers, has_bias, batch_first, bidirectional, dropout):\n super(GRU, self).__init__()\n self.gru = nn.GRU(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, has_bias=has_bias,\n batch_first=batch_first, bidirectional=bidirectional, dropout=dropout)\n\n def construct(self, inp, h0):\n return self.gru(inp, h0)\n\n\nclass GRUWeightBias():\n def __init__(self, num_layers, has_bias, input_size, num_directions, hidden_size, bidirectional):\n self.num_layers = num_layers\n self.has_bias = has_bias\n self.input_size = input_size\n self.num_directions = num_directions\n self.hidden_size = hidden_size\n self.bidirectional = bidirectional\n\n def get_weight_bias(self):\n gate_size = 3 * self.hidden_size\n\n w_ih_list = []\n w_hh_list = []\n b_ih_list = []\n b_hh_list = []\n stdv = 1 / math.sqrt(self.hidden_size)\n for layer in range(self.num_layers):\n for direction in range(self.num_directions):\n layer_input_size = self.input_size if layer == 0 else self.hidden_size * self.num_directions\n suffix = '_reverse' if direction == 1 else ''\n\n w_ih_list.append(Parameter(\n Tensor(np.random.uniform(-stdv, stdv, (gate_size, layer_input_size)).astype(np.float32)),\n name='weight_ih_l{}{}'.format(layer, suffix)))\n w_hh_list.append(Parameter(\n Tensor(np.random.uniform(-stdv, stdv, (gate_size, self.hidden_size)).astype(np.float32)),\n name='weight_hh_l{}{}'.format(layer, suffix)))\n if self.has_bias:\n b_ih_list.append(Parameter(\n Tensor(np.random.uniform(-stdv, stdv, (gate_size)).astype(np.float32)),\n name='bias_ih_l{}{}'.format(layer, suffix)))\n b_hh_list.append(Parameter(\n Tensor(np.random.uniform(-stdv, stdv, (gate_size)).astype(np.float32)),\n name='bias_hh_l{}{}'.format(layer, suffix)))\n w_ih_list = ParameterTuple(w_ih_list)\n w_hh_list = ParameterTuple(w_hh_list)\n b_ih_list = ParameterTuple(b_ih_list)\n b_hh_list = ParameterTuple(b_hh_list)\n return w_ih_list, w_hh_list, b_ih_list, b_hh_list\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_sit_gru_forward_input_3_32_32_is_32_hs_16():\n input_size = 32\n hidden_size = 16\n has_bias = True\n bidirectional = False\n num_layers = 1\n num_directions = 1\n\n fact = GRUWeightBias(num_layers, has_bias, input_size, num_directions, hidden_size, bidirectional)\n w_ih_list, w_hh_list, b_ih_list, b_hh_list = fact.get_weight_bias()\n\n h0 = Tensor(np.random.randn(num_layers * num_directions, 32, 16).astype(np.float32))\n input_ms = Tensor(np.random.randn(3, 32, 32).astype(np.float32))\n\n # graph mode\n context.set_context(mode=context.GRAPH_MODE)\n net = GRU(input_size=input_size, hidden_size=16, num_layers=num_layers, has_bias=has_bias, batch_first=False,\n bidirectional=bidirectional, dropout=0.0)\n net.gru.w_ih_list = w_ih_list\n net.gru.w_hh_list = w_hh_list\n net.gru.b_ih_list = b_ih_list\n net.gru.b_hh_list = b_hh_list\n out, hy = net(input_ms, h0)\n\n # pynative mode\n context.set_context(mode=context.PYNATIVE_MODE)\n net_pynative = GRU(input_size=input_size, hidden_size=16, num_layers=num_layers, has_bias=has_bias,\n batch_first=False, bidirectional=bidirectional, dropout=0.0)\n net_pynative.gru.w_ih_list = w_ih_list\n net_pynative.gru.w_hh_list = w_hh_list\n net_pynative.gru.b_ih_list = b_ih_list\n net_pynative.gru.b_hh_list = b_hh_list\n out_pynative, hy_pynative = net_pynative(input_ms, h0)\n\n assert np.allclose(out.asnumpy(), out_pynative.asnumpy(), 0.001, 0.001)\n assert np.allclose(hy.asnumpy(), hy_pynative.asnumpy(), 0.001, 0.001)\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_sit_gru_grad_input_3_32_32_is_32_hs_16():\n input_size = 32\n hidden_size = 16\n has_bias = True\n bidirectional = False\n num_layers = 1\n num_directions = 1\n\n fact = GRUWeightBias(num_layers, has_bias, input_size, num_directions, hidden_size, bidirectional)\n w_ih_list, w_hh_list, b_ih_list, b_hh_list = fact.get_weight_bias()\n\n h0 = Tensor(np.random.randn(num_layers * num_directions, 32, 16).astype(np.float32))\n input_ms = Tensor(np.random.randn(3, 32, 32).astype(np.float32))\n\n # graph mode\n context.set_context(mode=context.GRAPH_MODE)\n net = GRU(input_size=input_size, hidden_size=16, num_layers=num_layers, has_bias=has_bias, batch_first=False,\n bidirectional=bidirectional, dropout=0.0)\n net.gru.w_ih_list = w_ih_list\n net.gru.w_hh_list = w_hh_list\n net.gru.b_ih_list = b_ih_list\n net.gru.b_hh_list = b_hh_list\n\n grad_net_inp = GradOfAllInputsAndParams(net, sens_param=False)\n grad_net_inp.set_train()\n out_grad, _ = grad_net_inp(input_ms, h0)\n x_grad = out_grad[0].asnumpy()\n h_grad = out_grad[1].asnumpy()\n\n # pynative mode\n context.set_context(mode=context.PYNATIVE_MODE)\n net_pynative = GRU(input_size=input_size, hidden_size=16, num_layers=num_layers, has_bias=has_bias,\n batch_first=False, bidirectional=bidirectional, dropout=0.0)\n net_pynative.gru.w_ih_list = w_ih_list\n net_pynative.gru.w_hh_list = w_hh_list\n net_pynative.gru.b_ih_list = b_ih_list\n net_pynative.gru.b_hh_list = b_hh_list\n\n grad_net_inp_pynative = GradOfAllInputsAndParams(net_pynative, sens_param=False)\n grad_net_inp_pynative.set_train()\n out_grad_pynative, _ = grad_net_inp_pynative(input_ms, h0)\n x_grad_pynative = out_grad_pynative[0].asnumpy()\n h_grad_pynative = out_grad_pynative[1].asnumpy()\n\n assert np.allclose(x_grad, x_grad_pynative, 0.001, 0.001)\n assert np.allclose(h_grad, h_grad_pynative, 0.001, 0.001)\n" ]
[ [ "numpy.vectorize", "numpy.random.randint" ], [ "numpy.arange", "numpy.array", "numpy.zeros", "numpy.ones" ], [ "numpy.asarray", "numpy.array", "numpy.char.decode" ], [ "numpy.testing.assert_array_equal", "numpy.array" ], [ "numpy.int" ], [ "numpy.arange", "numpy.ones" ], [ "numpy.expand_dims", "numpy.sqrt", "numpy.isnan", "numpy.stack", "numpy.argmax", "numpy.bincount", "numpy.array", "numpy.zeros", "numpy.sum" ], [ "numpy.squeeze", "numpy.random.random" ], [ "numpy.array" ], [ "numpy.fromfile", "matplotlib.pyplot.title", "numpy.concatenate", "numpy.testing.assert_array_equal", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ], [ "numpy.all", "numpy.allclose", "numpy.ones" ], [ "numpy.random.uniform", "numpy.random.randn", "numpy.allclose" ] ]
[ { "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": [] }, { "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": [] } ]
rtloftin/strategically_efficient_rl
[ "85a702b9361211d345a58cc60696e4e851d48ec4", "85a702b9361211d345a58cc60696e4e851d48ec4" ]
[ "algorithms/agents/intrinsic.py", "train_multiagent.py" ]
[ "import numpy as np\nimport scipy.signal\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.evaluation.postprocessing import Postprocessing\n\nfrom algorithms.curiosity import INTRINSIC_REWARD\n\nINTRINSIC_VALUE_TARGETS = \"intrinsic_value_targets\"\nINTRINSIC_VF_PREDS = \"intrinsic_vf_preds\"\n\n\ndef discount(x, gamma):\n return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]\n\n\ndef compute_advantages_intrinsic(rollout,\n last_r,\n last_intrinsic_r,\n gamma=0.9,\n intrinsic_gamma=0.9,\n lambda_=1.0,\n intrinsic_lambda_=1.0):\n \"\"\"\n Given a rollout, compute its value targets and the advantage. Assumes we are using separate\n value function heads for the extrinsic and intrinsic rewards\n Args:\n rollout (SampleBatch): SampleBatch of a single trajectory\n last_r (float): Value estimation for last observation\n gamma (float): Discount factor\n intrinsic_gamma (float): Discount factor\n lambda_ (float): Parameter for GAE\n intrinsic_lambda_ (float): Parameter for intrinsic GAE\n Returns:\n SampleBatch (SampleBatch): Object with experience from rollout and\n processed rewards.\n \"\"\"\n\n traj = {}\n trajsize = len(rollout[SampleBatch.ACTIONS])\n for key in rollout:\n traj[key] = np.stack(rollout[key])\n\n # Extrinsic value predictions and targets\n vpred_t = np.concatenate([rollout[SampleBatch.VF_PREDS], np.array([last_r])])\n delta_t = (traj[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1])\n advantages = discount(delta_t, gamma * lambda_)\n\n traj[Postprocessing.VALUE_TARGETS] = (\n advantages + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32)\n\n # Intrinsic value predictions\n intrinsic_vpred_t = np.concatenate([rollout[INTRINSIC_VF_PREDS], np.array([last_intrinsic_r])])\n intrinsic_delta_t = (traj[INTRINSIC_REWARD] + intrinsic_gamma * intrinsic_vpred_t[1:] - intrinsic_vpred_t[:-1])\n intrinsic_advantages = discount(intrinsic_delta_t, intrinsic_gamma * intrinsic_lambda_)\n\n traj[INTRINSIC_VALUE_TARGETS] = (\n intrinsic_advantages + traj[INTRINSIC_VF_PREDS]).copy().astype(np.float32)\n\n traj[Postprocessing.ADVANTAGES] = (advantages + intrinsic_advantages).copy().astype(np.float32)\n\n assert all(val.shape[0] == trajsize for val in traj.values()), \\\n \"Rollout stacked incorrectly!\"\n\n return SampleBatch(traj)\n", "#!/usr/bin/env python3\n\n'''\nTrains independent learners in a multi-agent environment. Logs intrinsic reward if present.\n'''\n\nimport argparse\nimport yaml\n\nimport numpy as np\nimport ray\nfrom ray.tune import run_experiments\nfrom ray.tune.registry import ENV_CREATOR, _global_registry\n\nimport algorithms\nimport environments\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Generic training script for any registered multi-agent environment, logs intrinsic reward stats\")\n\n parser.add_argument(\"-f\", \"--config-file\", default=None, type=str, action=\"append\",\n help=\"If specified, use config options from these files.\")\n parser.add_argument(\"--local-dir\", type=str, default=\"../ray_results\",\n help=\"path to save training results\")\n parser.add_argument(\"--num-cpus\", type=int, default=7,\n help=\"the maximum number of CPUs ray is allowed to us, useful for running locally\")\n parser.add_argument(\"--num-gpus\", type=int, default=0,\n help=\"the maximum number of GPUs ray is allowed to use\")\n parser.add_argument(\"--num-workers\", type=int, default=3,\n help=\"the number of parallel workers per experiment\")\n parser.add_argument(\"--nash-conv\", action=\"store_true\",\n help='compute and record NashConv losses if environment supports this')\n\n \n return parser.parse_args()\n\n\ndef nash_conv(trainer, eval_workers):\n local_worker = eval_workers.local_worker()\n\n env = local_worker.env_creator(local_worker.policy_config[\"env_config\"])\n mapping_fn = local_worker.policy_config[\"multiagent\"][\"policy_mapping_fn\"]\n\n if hasattr(env, \"nash_conv\"):\n policy_dict = {pid: local_worker.get_policy(mapping_fn(pid)) for pid in env.action_space_dict.keys()}\n return env.nash_conv(policy_dict)\n\n\ndef log_intrinsic(info):\n episode = info[\"episode\"]\n batch = info[\"post_batch\"]\n\n if \"intrinsic_reward\" in batch:\n reward = np.sum(batch[\"intrinsic_reward\"])\n\n if \"intrinsic_reward\" not in episode.custom_metrics:\n episode.custom_metrics[\"intrinsic_reward\"] = reward\n else:\n episode.custom_metrics[\"intrinsic_reward\"] += reward\n\n\ndef main(args):\n EXPERIMENTS = dict()\n\n if args.config_file:\n for config_file in args.config_file:\n with open(config_file) as f:\n EXPERIMENTS.update(yaml.load(f, Loader=yaml.FullLoader))\n else:\n EXPERIMENTS = {\n \"RND_deep_sea\": {\n \"run\": \"PPO_CURIOSITY\",\n \"stop\": {\n \"timesteps_total\": 500000,\n },\n \"checkpoint_at_end\": True, # Make sure we have a final checkpoint for evaluation\n \"config\": {\n \"env\": \"roshambo\",\n \"env_config\": {},\n \"model\": {\n \"custom_options\": {\n \"weight\": 0.5,\n \"decay\": 0.02,\n \"burn_in\": 10000,\n \"delay\": 5000,\n \"curiosity_module\": \"RND\",\n \"curiosity_config\": {\n \"fcnet_activation\": \"relu\",\n \"fcnet_hiddens\": [256, 256],\n \"fcnet_outputs\": 32,\n \"agent_action\": True,\n \"joint_action\": False,\n },\n },\n },\n \"horizon\": 1000,\n \"intrinsic_gamma\": 0.95,\n \"intrinsic_lambda\": 0.95,\n \"num_agents\": 1, # Controls whether we are using multi-agent or single-agent curiosity\n \"lambda\": 0.95,\n \"gamma\": 0.95,\n \"entropy_coeff\": 0.001,\n \"clip_param\": 0.1,\n \"lr\": 0.001,\n \"num_sgd_iter\": 8,\n \"num_workers\": 4,\n \"train_batch_size\": 4000,\n \"rollout_fragment_length\": 500,\n },\n },\n }\n\n # Add intrinsic reward logging and multiagent configuration\n for experiment in EXPERIMENTS.values():\n exp_config = experiment[\"config\"]\n\n # Create temporary env instance to query observation space, action space and number of agents\n env_name = exp_config[\"env\"]\n\n if _global_registry.contains(ENV_CREATOR, env_name):\n env_creator = _global_registry.get(ENV_CREATOR, env_name)\n else:\n import gym\n env_creator = lambda env_config: gym.make(env_name)\n\n env = env_creator(exp_config.get(\"env_config\", {}))\n\n # One policy per agent for multiple individual learners # NOTE: Will this work for single-agent environments?\n policies = dict()\n for pid in env.observation_space_dict.keys():\n policies[f\"policy_{pid}\"] = (\n None,\n env.observation_space_dict[pid],\n env.action_space_dict[pid],\n {}\n )\n \n exp_config[\"multiagent\"] = {\"policies\": policies,\n \"policy_mapping_fn\": lambda pid: f\"policy_{pid}\"}\n\n # Set local directory for checkpoints\n experiment[\"local_dir\"] = str(args.local_dir)\n\n # Set num workers\n experiment[\"config\"][\"num_workers\"] = args.num_workers\n\n # Define custom NashConv evaluation function if needed\n if args.nash_conv:\n exp_config[\"custom_eval_function\"] = nash_conv\n exp_config[\"evaluation_config\"] = exp_config.get(\"evaluation_config\", {\n \"in_evaluation\": True,\n })\n\n # Add intrinsic reward logging\n experiment[\"config\"][\"callbacks\"] = {\n \"on_postprocess_traj\": log_intrinsic\n } \n\n # Modify config to reduce TensorFlow thrashing\n experiment[\"config\"][\"tf_session_args\"] = {\n \"intra_op_parallelism_threads\": 1,\n \"inter_op_parallelism_threads\": 1,\n }\n\n experiment[\"config\"][\"local_tf_session_args\"] = {\n \"intra_op_parallelism_threads\": 1,\n \"inter_op_parallelism_threads\": 1,\n }\n\n ray.init(num_cpus=args.num_cpus, num_gpus=args.num_gpus)\n run_experiments(EXPERIMENTS, verbose=1)\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n" ]
[ [ "numpy.array", "numpy.stack" ], [ "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KaihuaTang/scene-graph-benchmark.pytorch
[ "45cd54f7465b81d3154e94fcab2b554a09637f6f", "45cd54f7465b81d3154e94fcab2b554a09637f6f" ]
[ "maskrcnn_benchmark/modeling/roi_heads/relation_head/model_transformer.py", "maskrcnn_benchmark/solver/build.py" ]
[ "\"\"\"\nBased on the implementation of https://github.com/jadore801120/attention-is-all-you-need-pytorch\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom maskrcnn_benchmark.modeling.utils import cat\nfrom .utils_motifs import obj_edge_vectors, to_onehot, nms_overlaps, encode_box_info\n\nclass ScaledDotProductAttention(nn.Module):\n ''' Scaled Dot-Product Attention '''\n def __init__(self, temperature, attn_dropout=0.1):\n super().__init__()\n self.temperature = temperature\n self.dropout = nn.Dropout(attn_dropout)\n self.softmax = nn.Softmax(dim=2)\n\n def forward(self, q, k, v, mask=None):\n \"\"\"\n Args:\n q (bsz, len_q, dim_q)\n k (bsz, len_k, dim_k)\n v (bsz, len_v, dim_v)\n Note: len_k==len_v, and dim_q==dim_k\n Returns:\n output (bsz, len_q, dim_v)\n attn (bsz, len_q, len_k)\n \"\"\"\n attn = torch.bmm(q, k.transpose(1, 2))\n attn = attn / self.temperature\n\n if mask is not None:\n attn = attn.masked_fill(mask, -np.inf)\n\n attn = self.softmax(attn)\n attn = self.dropout(attn)\n output = torch.bmm(attn, v)\n\n return output, attn\n\n\nclass MultiHeadAttention(nn.Module):\n ''' Multi-Head Attention module '''\n def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):\n super().__init__()\n self.n_head = n_head\n self.d_k = d_k\n self.d_v = d_v\n\n self.w_qs = nn.Linear(d_model, n_head * d_k)\n self.w_ks = nn.Linear(d_model, n_head * d_k)\n self.w_vs = nn.Linear(d_model, n_head * d_v)\n nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))\n nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))\n nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))\n\n self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.fc = nn.Linear(n_head * d_v, d_model)\n nn.init.xavier_normal_(self.fc.weight)\n\n self.dropout = nn.Dropout(dropout)\n\n\n def forward(self, q, k, v, mask=None):\n \"\"\"\n Args:\n q (bsz, len_q, dim_q)\n k (bsz, len_k, dim_k)\n v (bsz, len_v, dim_v)\n Note: len_k==len_v, and dim_q==dim_k\n Returns:\n output (bsz, len_q, d_model)\n attn (bsz, len_q, len_k)\n \"\"\"\n d_k, d_v, n_head = self.d_k, self.d_v, self.n_head\n\n sz_b, len_q, _ = q.size()\n sz_b, len_k, _ = k.size()\n sz_b, len_v, _ = v.size() # len_k==len_v\n\n residual = q\n\n q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)\n k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)\n v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)\n\n q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk\n k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk\n v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv\n\n mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..\n output, attn = self.attention(q, k, v, mask=mask)\n\n output = output.view(n_head, sz_b, len_q, d_v)\n output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)\n\n output = self.dropout(self.fc(output))\n output = self.layer_norm(output + residual)\n\n return output, attn\n\n\nclass PositionwiseFeedForward(nn.Module):\n ''' A two-feed-forward-layer module '''\n def __init__(self, d_in, d_hid, dropout=0.1):\n super().__init__()\n self.w_1 = nn.Conv1d(d_in, d_hid, 1) # position-wise\n self.w_2 = nn.Conv1d(d_hid, d_in, 1) # position-wise\n self.layer_norm = nn.LayerNorm(d_in)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n \"\"\"\n Merge adjacent information. Equal to linear layer if kernel size is 1\n Args:\n x (bsz, len, dim)\n Returns:\n output (bsz, len, dim)\n \"\"\"\n residual = x\n output = x.transpose(1, 2)\n output = self.w_2(F.relu(self.w_1(output)))\n output = output.transpose(1, 2)\n output = self.dropout(output)\n output = self.layer_norm(output + residual)\n return output\n\n\nclass EncoderLayer(nn.Module):\n ''' Compose with two layers '''\n def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1):\n super(EncoderLayer, self).__init__()\n self.slf_attn = MultiHeadAttention(\n n_head, d_model, d_k, d_v, dropout=dropout)\n self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)\n\n def forward(self, enc_input, non_pad_mask=None, slf_attn_mask=None):\n enc_output, enc_slf_attn = self.slf_attn(\n enc_input, enc_input, enc_input, mask=slf_attn_mask)\n enc_output *= non_pad_mask.float()\n\n enc_output = self.pos_ffn(enc_output)\n enc_output *= non_pad_mask.float()\n\n return enc_output, enc_slf_attn\n\n\nclass TransformerEncoder(nn.Module):\n \"\"\"\n A encoder model with self attention mechanism.\n \"\"\"\n def __init__(self, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1):\n super().__init__()\n self.layer_stack = nn.ModuleList([\n EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout)\n for _ in range(n_layers)])\n\n def forward(self, input_feats, num_objs):\n \"\"\"\n Args:\n input_feats [Tensor] (#total_box, d_model) : bounding box features of a batch\n num_objs [list of int] (bsz, ) : number of bounding box of each image\n Returns:\n enc_output [Tensor] (#total_box, d_model)\n \"\"\"\n original_input_feats = input_feats\n input_feats = input_feats.split(num_objs, dim=0)\n input_feats = nn.utils.rnn.pad_sequence(input_feats, batch_first=True)\n\n # -- Prepare masks\n bsz = len(num_objs)\n device = input_feats.device\n pad_len = max(num_objs)\n num_objs_ = torch.LongTensor(num_objs).to(device).unsqueeze(1).expand(-1, pad_len)\n slf_attn_mask = torch.arange(pad_len, device=device).view(1, -1).expand(bsz, -1).ge(num_objs_).unsqueeze(1).expand(-1, pad_len, -1) # (bsz, pad_len, pad_len)\n non_pad_mask = torch.arange(pad_len, device=device).to(device).view(1, -1).expand(bsz, -1).lt(num_objs_).unsqueeze(-1) # (bsz, pad_len, 1)\n\n # -- Forward\n enc_output = input_feats\n for enc_layer in self.layer_stack:\n enc_output, enc_slf_attn = enc_layer(\n enc_output,\n non_pad_mask=non_pad_mask,\n slf_attn_mask=slf_attn_mask)\n\n enc_output = enc_output[non_pad_mask.squeeze(-1)]\n return enc_output\n\n\nclass TransformerContext(nn.Module):\n def __init__(self, config, obj_classes, rel_classes, in_channels):\n super().__init__()\n self.cfg = config\n # setting parameters\n if self.cfg.MODEL.ROI_RELATION_HEAD.USE_GT_BOX:\n self.mode = 'predcls' if self.cfg.MODEL.ROI_RELATION_HEAD.USE_GT_OBJECT_LABEL else 'sgcls'\n else:\n self.mode = 'sgdet'\n self.obj_classes = obj_classes\n self.rel_classes = rel_classes\n self.num_obj_cls = len(obj_classes)\n self.num_rel_cls = len(rel_classes)\n self.in_channels = in_channels\n self.obj_dim = in_channels\n self.embed_dim = self.cfg.MODEL.ROI_RELATION_HEAD.EMBED_DIM\n self.hidden_dim = self.cfg.MODEL.ROI_RELATION_HEAD.CONTEXT_HIDDEN_DIM\n self.nms_thresh = self.cfg.TEST.RELATION.LATER_NMS_PREDICTION_THRES\n\n self.dropout_rate = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.DROPOUT_RATE \n self.obj_layer = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.OBJ_LAYER \n self.edge_layer = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.REL_LAYER \n self.num_head = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.NUM_HEAD \n self.inner_dim = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.INNER_DIM \n self.k_dim = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.KEY_DIM \n self.v_dim = self.cfg.MODEL.ROI_RELATION_HEAD.TRANSFORMER.VAL_DIM \n\n\n # the following word embedding layer should be initalize by glove.6B before using\n embed_vecs = obj_edge_vectors(self.obj_classes, wv_dir=self.cfg.GLOVE_DIR, wv_dim=self.embed_dim)\n self.obj_embed1 = nn.Embedding(self.num_obj_cls, self.embed_dim)\n self.obj_embed2 = nn.Embedding(self.num_obj_cls, self.embed_dim)\n with torch.no_grad():\n self.obj_embed1.weight.copy_(embed_vecs, non_blocking=True)\n self.obj_embed2.weight.copy_(embed_vecs, non_blocking=True)\n\n # position embedding\n self.bbox_embed = nn.Sequential(*[\n nn.Linear(9, 32), nn.ReLU(inplace=True), nn.Dropout(0.1),\n nn.Linear(32, 128), nn.ReLU(inplace=True), nn.Dropout(0.1),\n ])\n self.lin_obj = nn.Linear(self.in_channels + self.embed_dim + 128, self.hidden_dim)\n self.lin_edge = nn.Linear(self.embed_dim + self.hidden_dim + self.in_channels, self.hidden_dim)\n self.out_obj = nn.Linear(self.hidden_dim, self.num_obj_cls)\n self.context_obj = TransformerEncoder(self.obj_layer, self.num_head, self.k_dim, \n self.v_dim, self.hidden_dim, self.inner_dim, self.dropout_rate)\n self.context_edge = TransformerEncoder(self.edge_layer, self.num_head, self.k_dim, \n self.v_dim, self.hidden_dim, self.inner_dim, self.dropout_rate)\n\n \n def forward(self, roi_features, proposals, logger=None):\n # labels will be used in DecoderRNN during training\n use_gt_label = self.training or self.cfg.MODEL.ROI_RELATION_HEAD.USE_GT_OBJECT_LABEL\n obj_labels = cat([proposal.get_field(\"labels\") for proposal in proposals], dim=0) if use_gt_label else None\n\n # label/logits embedding will be used as input\n if self.cfg.MODEL.ROI_RELATION_HEAD.USE_GT_OBJECT_LABEL:\n obj_embed = self.obj_embed1(obj_labels)\n else:\n obj_logits = cat([proposal.get_field(\"predict_logits\") for proposal in proposals], dim=0).detach()\n obj_embed = F.softmax(obj_logits, dim=1) @ self.obj_embed1.weight\n \n # bbox embedding will be used as input\n assert proposals[0].mode == 'xyxy'\n pos_embed = self.bbox_embed(encode_box_info(proposals))\n\n # encode objects with transformer\n obj_pre_rep = cat((roi_features, obj_embed, pos_embed), -1)\n num_objs = [len(p) for p in proposals]\n obj_pre_rep = self.lin_obj(obj_pre_rep)\n obj_feats = self.context_obj(obj_pre_rep, num_objs)\n\n # predict obj_dists and obj_preds\n if self.mode == 'predcls':\n obj_preds = obj_labels\n obj_dists = to_onehot(obj_preds, self.num_obj_cls)\n edge_pre_rep = cat((roi_features, obj_feats, self.obj_embed2(obj_labels)), dim=-1)\n else:\n obj_dists = self.out_obj(obj_feats)\n use_decoder_nms = self.mode == 'sgdet' and not self.training\n if use_decoder_nms:\n boxes_per_cls = [proposal.get_field('boxes_per_cls') for proposal in proposals]\n obj_preds = self.nms_per_cls(obj_dists, boxes_per_cls, num_objs)\n else:\n obj_preds = obj_dists[:, 1:].max(1)[1] + 1\n edge_pre_rep = cat((roi_features, obj_feats, self.obj_embed2(obj_preds)), dim=-1)\n\n # edge context\n edge_pre_rep = self.lin_edge(edge_pre_rep)\n edge_ctx = self.context_edge(edge_pre_rep, num_objs)\n\n return obj_dists, obj_preds, edge_ctx\n\n def nms_per_cls(self, obj_dists, boxes_per_cls, num_objs):\n obj_dists = obj_dists.split(num_objs, dim=0)\n obj_preds = []\n for i in range(len(num_objs)):\n is_overlap = nms_overlaps(boxes_per_cls[i]).cpu().numpy() >= self.nms_thresh # (#box, #box, #class)\n\n out_dists_sampled = F.softmax(obj_dists[i], -1).cpu().numpy()\n out_dists_sampled[:, 0] = -1\n\n out_label = obj_dists[i].new(num_objs[i]).fill_(0)\n\n for i in range(num_objs[i]):\n box_ind, cls_ind = np.unravel_index(out_dists_sampled.argmax(), out_dists_sampled.shape)\n out_label[int(box_ind)] = int(cls_ind)\n out_dists_sampled[is_overlap[box_ind,:,cls_ind], cls_ind] = 0.0\n out_dists_sampled[box_ind] = -1.0 # This way we won't re-sample\n\n obj_preds.append(out_label.long())\n obj_preds = torch.cat(obj_preds, dim=0)\n return obj_preds\n", "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport torch\n\nfrom .lr_scheduler import WarmupMultiStepLR, WarmupReduceLROnPlateau\n\n\ndef make_optimizer(cfg, model, logger, slow_heads=None, slow_ratio=5.0, rl_factor=1.0):\n params = []\n for key, value in model.named_parameters():\n if not value.requires_grad:\n continue\n lr = cfg.SOLVER.BASE_LR\n weight_decay = cfg.SOLVER.WEIGHT_DECAY\n if \"bias\" in key:\n lr = cfg.SOLVER.BASE_LR * cfg.SOLVER.BIAS_LR_FACTOR\n weight_decay = cfg.SOLVER.WEIGHT_DECAY_BIAS\n if slow_heads is not None:\n for item in slow_heads:\n if item in key:\n logger.info(\"SLOW HEADS: {} is slow down by ratio of {}.\".format(key, str(slow_ratio)))\n lr = lr / slow_ratio\n break\n params += [{\"params\": [value], \"lr\": lr * rl_factor, \"weight_decay\": weight_decay}]\n\n optimizer = torch.optim.SGD(params, lr=cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM)\n return optimizer\n\n\ndef make_lr_scheduler(cfg, optimizer, logger=None):\n if cfg.SOLVER.SCHEDULE.TYPE == \"WarmupMultiStepLR\":\n return WarmupMultiStepLR(\n optimizer,\n cfg.SOLVER.STEPS,\n cfg.SOLVER.GAMMA,\n warmup_factor=cfg.SOLVER.WARMUP_FACTOR,\n warmup_iters=cfg.SOLVER.WARMUP_ITERS,\n warmup_method=cfg.SOLVER.WARMUP_METHOD,\n )\n \n elif cfg.SOLVER.SCHEDULE.TYPE == \"WarmupReduceLROnPlateau\":\n return WarmupReduceLROnPlateau(\n optimizer,\n cfg.SOLVER.SCHEDULE.FACTOR,\n warmup_factor=cfg.SOLVER.WARMUP_FACTOR,\n warmup_iters=cfg.SOLVER.WARMUP_ITERS,\n warmup_method=cfg.SOLVER.WARMUP_METHOD,\n patience=cfg.SOLVER.SCHEDULE.PATIENCE,\n threshold=cfg.SOLVER.SCHEDULE.THRESHOLD,\n cooldown=cfg.SOLVER.SCHEDULE.COOLDOWN,\n logger=logger,\n )\n \n else:\n raise ValueError(\"Invalid Schedule Type\")\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Dropout", "torch.nn.functional.softmax", "torch.LongTensor", "numpy.sqrt", "torch.cat", "numpy.power", "torch.nn.utils.rnn.pad_sequence", "torch.nn.init.xavier_normal_", "torch.arange", "torch.nn.Embedding", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.no_grad", "torch.bmm", "torch.nn.Conv1d", "torch.nn.ReLU" ], [ "torch.optim.SGD" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lenna-project/birds-plugin
[ "c548790dcb0593b80ea6da4605e7aa32e3f141ae" ]
[ "scripts/train.py" ]
[ "import logging\nimport numpy as np\nimport os\nimport PIL\nimport PIL.Image\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Layer, Conv2D, MaxPool2D, Dense, Flatten, Dropout, GlobalAveragePooling2D\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\n\nimg_height = 224\nimg_width = 224\nbatch_size = 64\n\ndata_dir = './100-bird-species/'\ndata_dir_train = os.path.join(data_dir, 'train')\ndata_dir_valid = os.path.join(data_dir, 'valid')\ndata_dir_test = os.path.join(data_dir, 'test')\n\ntrain_ds = tf.keras.utils.image_dataset_from_directory(\n data_dir_train,\n label_mode='categorical',\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n\nvalid_ds = tf.keras.utils.image_dataset_from_directory(\n data_dir_valid,\n label_mode='categorical',\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n\ntest_ds = tf.keras.utils.image_dataset_from_directory(\n data_dir_test,\n label_mode='categorical',\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n\n\ndef normalize(img, label):\n return img / 255.0, label\n\n\ndata_augmentation = tf.keras.Sequential([\n tf.keras.layers.RandomFlip(\"horizontal\"),\n tf.keras.layers.RandomRotation(0.2),\n tf.keras.layers.RandomZoom(0.2)\n])\n\ntrain_dataset = (train_ds\n .map(normalize)\n .map(lambda x, y: (data_augmentation(x), y))\n .prefetch(tf.data.AUTOTUNE))\n\nvalid_dataset = valid_ds.map(normalize)\ntest_dataset = test_ds.map(normalize)\n\n\ndef get_birds_mobilenet():\n pre_trained_model = MobileNetV2(\n include_top=False,\n input_shape=(img_height, img_width, 3),\n classifier_activation='softmax'\n )\n\n for layer in pre_trained_model.layers:\n layer.trainable = False\n\n last_layer = pre_trained_model.output\n last_layer.trainable = True\n\n x = GlobalAveragePooling2D()(last_layer)\n x = Dense(1024, activation='relu')(x)\n x = layers.Dense(325, activation='softmax')(x)\n\n model = Model(pre_trained_model.input, x)\n return model\n\n\nmodel = get_birds_mobilenet()\nmodel.summary()\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\ncheckpoint_path = \"./checkpoints/birds_mobilenet/\"\n\nmodel.load_weights(checkpoint_path)\n\nmodel_history = model.fit(\n train_dataset,\n validation_data=valid_dataset,\n epochs=200,\n callbacks=[\n #tf.keras.callbacks.EarlyStopping(patience=5),\n tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_path, verbose=0, save_freq=\"epoch\")\n ])\n" ]
[ [ "tensorflow.keras.utils.image_dataset_from_directory", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.layers.RandomFlip", "tensorflow.keras.layers.Dense", "tensorflow.keras.Model", "tensorflow.keras.layers.RandomZoom", "tensorflow.keras.layers.RandomRotation", "tensorflow.keras.applications.MobileNetV2" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
tpimentelms/meaning2form
[ "624b3947b3ac2a7a521cf35c762fb56508236f74" ]
[ "learn_pipe/model/lstm.py" ]
[ "import torch.nn as nn\n\nfrom .base import BaseLM\n\n\nclass IpaLM(BaseLM):\n name = 'lstm'\n\n def __init__(self, vocab_size, hidden_size, nlayers=1, dropout=0.1, embedding_size=None, **kwargs):\n super().__init__(\n vocab_size, hidden_size, nlayers=nlayers, dropout=dropout, embedding_size=embedding_size, **kwargs)\n\n self.embedding = nn.Embedding(vocab_size, self.embedding_size)\n self.lstm = nn.LSTM(\n self.embedding_size, hidden_size, nlayers, dropout=(dropout if nlayers > 1 else 0), batch_first=True)\n self.dropout = nn.Dropout(dropout)\n self.out = nn.Linear(hidden_size, vocab_size)\n\n def forward(self, x, idx):\n h_old = self.context(idx)\n x_emb = self.dropout(self.get_embedding(x))\n\n c_t, h_t = self.lstm(x_emb, h_old)\n c_t = self.dropout(c_t).contiguous()\n\n logits = self.out(c_t)\n return logits, h_t\n\n def get_embedding(self, x):\n return self.embedding(x)\n\n def initHidden(self, bsz=1):\n weight = next(self.parameters()).data\n return weight.new(self.nlayers, bsz, self.hidden_size).zero_(), \\\n weight.new(self.nlayers, bsz, self.hidden_size).zero_()\n" ]
[ [ "torch.nn.Linear", "torch.nn.Dropout", "torch.nn.Embedding", "torch.nn.LSTM" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
j-towns/jax
[ "49f3f991d4faae22fcd9d8248f3d36575b5004f6" ]
[ "tests/lax_numpy_einsum_test.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nimport itertools\n\nimport numpy as onp\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport jax.numpy as np\nimport jax.test_util as jtu\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\n\ndef rng():\n return onp.random.RandomState(0)\n\n\nclass EinsumTest(jtu.JaxTestCase):\n\n def _check(self, s, *ops):\n a = onp.einsum(s, *ops)\n b = np.einsum(s, *ops)\n self.assertAllClose(a, b, atol=1e-4, rtol=1e-4, check_dtypes=True)\n\n def test_three_operands_1(self):\n r = rng()\n x = r.randn(3)\n y = r.randn(4)\n z = r.randn(5)\n s = 'i,j,k->ijk'\n self._check(s, x, y, z)\n\n def test_three_operands_2(self):\n r = rng()\n x = r.randn(3)\n y = r.randn(4)\n z = r.randn(5)\n s = 'i,j,k->ijk'\n self._check(s, x, y, z)\n\n def test_two_operands_1(self):\n r = rng()\n x = r.randn(3, 4)\n y = r.randn(4)\n s = 'ij,j->i'\n self._check(s, x, y)\n\n def test_two_operands_2(self):\n r = rng()\n x = r.randn(3, 4, 5)\n y = r.randn(4)\n s = 'ijk,j->i'\n self._check(s, x, y)\n\n def test_two_operands_3(self):\n r = rng()\n x = r.randn(3, 4, 3)\n y = r.randn(3)\n s = 'iji,i->j'\n self._check(s, x, y)\n\n def test_two_operands_4(self):\n r = rng()\n x = r.randn(3, 4)\n y = r.randn(3, 4)\n s = 'ij,ij->'\n self._check(s, x, y)\n\n def test_two_operands_5(self):\n r = rng()\n x = r.randn(10, 2, 3)\n y = r.randn(3, 4)\n s = 'nij,jk->nik'\n self._check(s, x, y)\n\n def test_two_operands_6(self):\n # based on https://github.com/google/jax/issues/37#issuecomment-448572187\n r = rng()\n x = r.randn(2, 1)\n y = r.randn(2, 3, 4)\n s = 'sa,shb->shab'\n self._check(s, x, y)\n\n def test_one_operand_1(self):\n r = rng()\n x = r.randn(3, 4, 5)\n s = 'ijk->j'\n self._check(s, x)\n\n def test_one_operand_2(self):\n r = rng()\n x = r.randn(3, 4, 5)\n s = 'ijk->kij'\n self._check(s, x)\n\n def test_one_operand_3(self):\n r = rng()\n x = r.randn(3, 4, 5)\n s = 'ijk->ki'\n self._check(s, x)\n\n def test_one_operand_4(self):\n r = rng()\n x = r.randn(3, 4, 5)\n s = 'ijk->ki'\n self._check(s, x)\n\n def test_one_operand_5(self):\n r = rng()\n x = r.randn(2, 3, 4, 5)\n s = '...ijk->...ki'\n self._check(s, x)\n\n def test_one_operand_6(self):\n r = rng()\n x = r.randn(3, 4, 5)\n s = '...ijk->ki'\n self._check(s, x)\n\n def test_one_operand_7(self):\n r = rng()\n x = r.randn(3, 3)\n s = 'ii->'\n self._check(s, x)\n\n def test_one_operand_8(self):\n r = rng()\n x = r.randn(3, 3)\n s = 'ij->'\n self._check(s, x)\n\n def test_one_operand_9(self):\n r = rng()\n x = r.randn(3, 3, 3)\n s = 'iii->'\n self._check(s, x)\n\n def test_one_operand_10(self):\n r = rng()\n x = r.randn(3, 3)\n s = 'ii->i'\n self._check(s, x)\n\n def test_one_operand_11(self):\n r = rng()\n x = r.randn(3, 3, 4)\n s = 'iij->i'\n self._check(s, x)\n\n def test_one_operand_12(self):\n r = rng()\n x = r.randn(3, 3, 3)\n s = 'iii->i'\n self._check(s, x)\n\n def test_one_operand_13(self):\n r = rng()\n x = r.randn(3, 3, 5, 4, 4)\n s = 'iijkk->i'\n self._check(s, x)\n\n def test_one_operand_14(self):\n r = rng()\n x = r.randn(3, 3, 5, 4, 4)\n s = 'iijkk->ik'\n self._check(s, x)\n\n def test_one_operand_15(self):\n r = rng()\n x = r.randn(3, 3, 5, 4, 4)\n s = 'iijkl->il'\n self._check(s, x)\n\n def test_one_operand_16(self):\n r = rng()\n x = r.randn(3, 3)\n s = 'ij->ij'\n self._check(s, x)\n\n def test_tf_unsupported_1(self):\n # from https://www.tensorflow.org/api_docs/python/tf/einsum\n r = rng()\n x = r.randn(2, 3, 5, 1)\n y = r.randn(3, 4, 5, 1)\n s = 'ij...,jk...->ik...'\n self._check(s, x, y)\n\n def test_tf_unsupported_2(self):\n # from https://www.tensorflow.org/api_docs/python/tf/einsum\n r = rng()\n x = r.randn(2, 3, 3)\n y = r.randn(4)\n s = 'ijj,k->ik'\n self._check(s, x, y)\n\n def test_tf_unsupported_3(self):\n # from https://www.tensorflow.org/api_docs/python/tf/einsum\n r = rng()\n x = r.randn(2, 3)\n y = r.randn(2, 3)\n z = r.randn(3, 4)\n s = 'ij,ij,jk->ik'\n self._check(s, x, y, z)\n\n # these tests are based on https://github.com/dask/dask/pull/3412/files\n @parameterized.named_parameters(\n {\"testcase_name\": \"_{}\".format(einstr), \"einstr\": einstr}\n for einstr in [\n 'abc,bad->abcd',\n 'abcdef,bcdfg->abcdeg',\n 'ea,fb,abcd,gc,hd->efgh',\n 'ab,b',\n 'aa',\n 'a,a->',\n 'a,a->a',\n 'a,a',\n 'a,b',\n 'a,b,c',\n 'a',\n 'ba,b',\n 'ba,b->',\n 'defab,fedbc->defac',\n 'ab...,bc...->ac...',\n 'a...a',\n 'abc...->cba...',\n '...ab->...a',\n 'a...a->a...',\n # Following 2 from # https://stackoverflow.com/a/19203475/1611416\n '...abc,...abcd->...d',\n 'ab...,b->ab...',\n # https://github.com/dask/dask/pull/3412#discussion_r182413444\n 'aa->a',\n 'ab,ab,c->c',\n 'aab,bc->ac',\n 'aab,bcc->ac',\n 'fdf,cdd,ccd,afe->ae',\n 'fff,fae,bef,def->abd',\n ])\n def test_from_dask(self, einstr):\n r = rng()\n if '->' in einstr:\n input_str, result_names = einstr.split('->')\n else:\n input_str = einstr\n input_names = input_str.split(',')\n\n dims = itertools.cycle([2, 3, 4])\n shapes = defaultdict(lambda: next(dims))\n input_shapes = [tuple(shapes[c] for c in names.replace('...', '01'))\n for names in input_names]\n operands = [r.randn(*shape) for shape in input_shapes]\n\n self._check(einstr, *operands)\n\n def test_ordered_front_batch_dim_case(self):\n x = onp.ones((1,8,20,4))\n y = onp.ones((1,8,20,4))\n s = 'ijkl,ijml->ijkm'\n self._check(s, x, y)\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "numpy.random.RandomState", "numpy.einsum", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tanzhenyu/image_augmentation
[ "d1f8cc35cf25438556e7934e8e6c78827819ea9d" ]
[ "image_augmentation/callbacks/extra_eval.py" ]
[ "import tensorflow as tf\nfrom tensorflow.keras.callbacks import Callback\n\n\nclass ExtraValidation(Callback):\n \"\"\"Log evaluation metrics of an extra validation set. This callback\n is useful for model training scenarios where multiple validation sets\n are used for evaluation (as Keras by default, provides functionality for\n evaluating on a single validation set only).\n\n The evaluation metrics are also logged to TensorBoard.\n\n Args:\n validation_data: A tf.data.Dataset pipeline used to evaluate the\n model, essentially an extra validation dataset.\n tensorboard_path: Path to the TensorBoard logging directory.\n validation_freq: Number of epochs to wait before performing\n subsequent evaluations.\n \"\"\"\n def __init__(self, validation_data, tensorboard_path, validation_freq=1):\n super(ExtraValidation, self).__init__()\n\n self.validation_data = validation_data\n self.tensorboard_path = tensorboard_path\n\n self.tensorboard_writer = tf.summary.create_file_writer(self.tensorboard_path)\n\n self.validation_freq = validation_freq\n\n def on_epoch_end(self, epoch, logs=None):\n # evaluate at an interval of `validation_freq` epochs\n if (epoch + 1) % self.validation_freq == 0:\n # gather metric names form model\n metric_names = ['{}_{}'.format('epoch', metric.name)\n for metric in self.model.metrics]\n # TODO: fix `model.evaluate` memory leak on TPU\n # gather the evaluation metrics\n scores = self.model.evaluate(self.validation_data, verbose=2)\n\n # gather evaluation metrics to TensorBoard\n with self.tensorboard_writer.as_default():\n for metric_name, score in zip(metric_names, scores):\n tf.summary.scalar(metric_name, score, step=epoch)\n" ]
[ [ "tensorflow.summary.scalar", "tensorflow.summary.create_file_writer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cristianMeli/ubatch
[ "fb3c6dccf0a9e25e25f5956e2e91ed70e9ea01ee" ]
[ "examples/flask_app.py" ]
[ "import random\nimport numpy as np\n\nfrom typing import Dict, List\n\nfrom flask import Flask\nfrom flask_restx import Resource, Api\n\n# from numpy import genfromtxt\n\nfrom ubatch import ubatch_decorator\n\n# from keras.models import load_model\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.model_selection import train_test_split\n\n\nfrom joblib import load\n\nngd = fetch_20newsgroups(subset=\"all\")\n\nX = ngd.data\ny = ngd.target\n_, X_test, _, _ = train_test_split(X, y, test_size=0.33)\n\n\nmodel = load(\"xgbregressor.joblib\")\n# X_test = genfromtxt(\"xgbregressor_inputs.csv\", delimiter=\",\")\n\napp = Flask(__name__)\napi = Api(app)\n\n\n@ubatch_decorator(max_size=100, timeout=0.01)\ndef predict(data: List[np.array]) -> List[np.float32]:\n return model.predict(np.array(data)) # type: ignore\n\n\[email protected](\"/predict_ubatch\")\nclass BatchPredict(Resource):\n def post(self) -> Dict[str, float]:\n output = predict.ubatch(random.choice(X_test))\n return {\"prediction\": float(output)}\n\n\[email protected](\"/predict\")\nclass Predict(Resource):\n def post(self) -> Dict[str, float]:\n output = predict([random.choice(X_test)])[0]\n return {\"prediction\": float(output)}\n" ]
[ [ "numpy.array", "sklearn.model_selection.train_test_split", "sklearn.datasets.fetch_20newsgroups" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
simonharris/pykmeans
[ "4d47eb12a2bbaf1b05d7ccfd0cfc9ccf78ddf86d" ]
[ "tests/initialisations/test_bradleyfayyad1998.py" ]
[ "\"\"\"\nTest for Bradley & Fayyad 1998 initialisation algorithm\n\"\"\"\n\nimport unittest\n\nimport numpy as np\n\nfrom datasets import testloader\nfrom initialisations import bradley as bfinit\nimport kmeans\n\n# pylint: disable=R0201,W0212\n\n\nclass BfTestSuite(unittest.TestCase):\n \"\"\"Test suite for B&F\"\"\"\n\n def test_code_runs(self):\n \"\"\"At least prove it runs\"\"\"\n\n dataset = testloader.load_iris()\n centroids = bfinit.generate(dataset.data, 3)\n self.assertEqual((3, 4), centroids.shape)\n\n def test_with_hartigan(self):\n \"\"\"A tiny dataset which can't possibly work here\"\"\"\n\n dataset = testloader.load_hartigan()\n\n with self.assertRaises(ValueError):\n bfinit.generate(dataset.data, 3)\n\n def test_find_furthest(self):\n \"\"\"Find the data point furthest from its cluster center\"\"\"\n\n distances = np.array([\n [1, 2, 3], # 1\n [7, 5, 16], # 5\n [7, 26, 4], # 4\n [19, 20, 21], # 19\n [6, 18, 8] # 6\n ])\n\n np.testing.assert_equal(bfinit._find_furthest(distances), [3])\n np.testing.assert_equal(np.sort(bfinit._find_furthest(distances, 2)),\n [3, 4])\n np.testing.assert_equal(np.sort(bfinit._find_furthest(distances, 3)),\n [1, 3, 4])\n\n def test_with_1_empty(self):\n \"\"\"Seeds and data known to leave one empty cluster after k_means(),\n and thus trigger k_means_mod() to reassign a centroid\"\"\"\n\n seeds = np.array([\n [5.4, 3.0, 4.5, 1.5],\n [6.7, 3.0, 5.0, 1.7],\n [5.1, 3.8, 1.5, 0.3], # Doesn't get any data points assigned\n ])\n\n data = np.array([\n # Assigned to 0 but is furthest, so becomes the new 2\n [6.4, 2.9, 4.3, 1.3],\n [6.3, 3.4, 5.6, 2.4],\n [6.8, 3.0, 5.5, 2.1],\n [5.0, 2.0, 3.5, 1.0],\n [5.8, 2.7, 5.1, 1.9],\n ])\n\n expected_labels = [2, 1, 1, 0, 0]\n\n expected_centroids = [\n [5.4, 2.35, 4.3, 1.45],\n [6.55, 3.2, 5.55, 2.25],\n [6.4, 2.9, 4.3, 1.3], # The new 2\n ]\n\n centroids = bfinit._k_means_mod(seeds, data, len(seeds))\n labels = kmeans.distance_table(data, centroids).argmin(1)\n\n np.testing.assert_array_equal(labels, expected_labels)\n np.testing.assert_array_equal(centroids, expected_centroids)\n\n def _test_with_n_empty(self):\n \"\"\"Seeds and data known to leave more than one empty cluster\n\n This is left as TODO for now, since no way can I force sklearn to\n give me more than one empty cluster.\n \"\"\"\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
swharden/SWHLab
[ "a86c3c65323cec809a4bd4f81919644927094bf5" ]
[ "doc/oldcode/swhlab/core/memtest.py" ]
[ "\"\"\"\nMembrane test routines for voltage clamp experiments.\ncreates abf.MTs[sweep]={} #with keys like Ih, Ra, Rm, etc\n\nExample usage:\n abf=swhlab.ABF('../abfs/group/16701010.abf')\n swhlab.memtest.memtest(abf) #performs memtest on all sweeps\n swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did\n pylab.show()\n\"\"\"\n\nimport os\nimport sys\nimport pylab\nimport numpy as np\nimport time\n\nimport swhlab\nimport swhlab.core.common as cm\nexampleABF=swhlab.ABF()\n\ndef memtestSweepVC(abf=exampleABF):\n \"\"\"\n perform memtest on current sweep in VC mode. Return Ih, Ra, Rm, etc.\n All variable names are explained in /swhlab/docs/memtest.ppt\n \"\"\"\n if abf.protoSeqY[1]>abf.protoSeqY[0] or len(abf.protoSeqY)<3:\n return \"protocol doesn't step down and back up\"\n TA,TB=int(abf.protoSeqX[1]),int(abf.protoSeqX[2])\n dT=int(TB-TA)\n T1A=int(TA+.5*dT)\n T1B=int(TA+.9*dT)\n T2A=T1A+dT\n T2B=T1B+dT\n P1=np.average(abf.dataY[T1A:T1B])\n P2=np.average(abf.dataY[T2A:T2B])\n dI=P2-P1\n dV=abf.protoSeqY[2]-abf.protoSeqY[1]\n PP=np.max(abf.dataY[TB:TB+100])# peak found within first 100 points\n TP=np.where(abf.dataY[TB:TB+150]==PP)[0][0]+TB\n dP=PP-P1\n dTC=PP-P2\n PCA=P2+.9*dTC # upper fraction for Cm detection\n PCB=P2+.1*dTC # upper fraction for Cm detection\n PCtau=P2+.37*dTC # crossing point of theoretical tau\n TCA=np.where(abf.dataY[TP:T2A]<PCA)[0][0]+TP\n TCB=np.where(abf.dataY[TP:T2A]<PCB)[0][0]+TP\n dTCT=TCB-TCA #number of points available for fitting\n Ih=P2\n Ra=(dV*10**3)/(PP-P2) #MOhm=uV/pA\n Rm=(dV*10**3)/(P2-P1) #MOhm=uV/pA\n fitM,fitT,fitB,fitTau=cm.fit_exp(abf.dataY[TCA:TCB]) #same units as given\n fitTau=fitTau*1000/abf.rate #time constant convert to ms units\n Tv=fitTau #time constant of extrinsic voltage clamp\n Cm=Tv/Ra*1000 #us/MOhm is pF\n Tm=Rm*Cm/1000 #time constant of cell membrane (intrinsic voltage clamp)\n del abf\n return locals()\n\ndef memtestIC(abf=exampleABF):\n \"\"\"\n IC memtest is different. Make an average sweep, then curve fit it.\n This only RETURNS the memtest, it does not assign it.\n \"\"\"\n if abf.protoSeqY[1]>abf.protoSeqY[0] or len(abf.protoSeqY)<3:\n return \"protocol doesn't step down and back up\"\n abf.baseline=[abf.protoSeqX[1]/abf.rate*.75,abf.protoSeqX[1]/abf.rate]\n T1A,T1B=np.array(abf.baseline)*abf.rate\n Xs,Ys,Er=abf.average_sweep()\n T2A=abf.protoSeqX[2]-abf.protoSeqX[1]\n T2B=abf.protoSeqX[2]\n M2=np.average(Ys[T2A:T2B])\n MCA=.1*M2 # set 90% here\n MCB=.9*M2 # set 10% here\n TCA=np.where(Ys<MCA)[0][0]\n TCB=np.where(Ys<MCB)[0][0]\n m,t,b,tc=cm.fit_exp(Ys[TCA:TCB]) #do the fit!\n dI=abs(abf.protoSeqY[2]-abf.protoSeqY[1]) #pA\n dV=abs(M2) #mV\n Rm=dV/dI*1000 #uV/pA = MOhm\n Cm=tc/Rm #ms/MOhm\n del abf,Ys,Xs,Er\n return locals() #convert to structured array\n\ndef memtest(abf=exampleABF,firstSweepOnly=False,plotToo=False,saveToo=True):\n \"\"\"perform memtest on all sweeps.\"\"\"\n timeStart=time.clock()\n if abf.units==\"mV\":\n abf.MTs = memtestIC(abf)\n else:\n abf.MTs=[None]*abf.sweeps\n for sweep in range(abf.sweeps):\n abf.setSweep(sweep)\n result=memtestSweepVC(abf)\n if type(result) is dict:\n abf.MTs[abf.currentSweep]=result\n else:\n print(\"MEMTEST FAILED - sweep %d -\"%sweep,result)\n if firstSweepOnly:\n return\n abf.MTs = cm.matrixfromDicts(abf.MTs) #convert to structured array\n took=time.clock()-timeStart\n print(\" -- memtest performed on %d sweeps in %.02f ms\"%(abf.sweeps,took*1000))\n if saveToo:\n abf.saveThing(abf.MTs,\"MTs\")\n\ndef plot_standard4(abf=exampleABF):\n \"\"\"make a standard memtest plot showing Ih, Ra, etc. with time.\"\"\"\n if abf.sweeps<2:\n return\n swhlab.plot.new(abf)\n Xs=np.arange(abf.sweeps)*abf.sweepInterval/60\n subplots=[221,222,223,224]\n features=['Ih','Ra','Rm','Cm']\n units=['pA','MOhm','MOhm','pF']\n for subplot,feature,unit in zip(subplots,features,units):\n pylab.subplot(subplot)\n pylab.grid(alpha=.5)\n #pylab.title(feature)\n pylab.plot(Xs,cm.dictVals(abf.MTs,feature),'.-',alpha=.5)\n pylab.xlabel(None)\n pylab.ylabel(\"%s (%s)\"%(feature,unit))\n swhlab.plot.comments(abf,True)\n pylab.margins(0,.1)\n\ndef checkSweepIC(abf=exampleABF,sweep=0):\n \"\"\"Produce an eyeball-ready indication how the MT was calculated in IC.\"\"\"\n _keys = abf.MTs.dtype.names\n for key in _keys:\n globals()[key]=abf.MTs[key] # only global for this module, that's fine\n fitted=cm.algo_exp(np.arange(TCB-TCA),m,t,b)\n swhlab.plot.new(abf,forceNewFigure=True)\n Xs,Ys,Er=abf.average_sweep()\n for subplot in [121,122]:\n pylab.subplot(subplot)\n pylab.axhline(0,color='b',lw=2,alpha=.5,ls=\"--\")\n pylab.axhline(M2,color='b',lw=2,alpha=.5,ls=\"--\")\n swhlab.plot.sweep(abf,'all',rainbow=False,color='#CCCCCC',alpha=.5)\n pylab.plot(Xs,Ys,color='k',alpha=.5)\n pylab.plot(Xs[T1A:T1B],Ys[T1A:T1B],color='b',lw=2)\n pylab.plot(Xs[T2A:T2B],Ys[T2A:T2B],color='b',lw=2)\n pylab.plot(abf.dataX[TCA:TCB],fitted,color='r',lw=2,ls='--')\n pylab.axis([(TCA-100)/abf.rate,(TCB+100)/abf.rate,None,None])\n pylab.tight_layout()\n msg=\"tau: %.02f ms\\n\"%(tc/abf.rate*1000)\n msg+=\"Rm: %.02f MOhm\\n\"%(Rm)\n msg+=\"Cm: %.02f pF\"%(Cm)\n pylab.annotate(msg,(.75,.95),ha='left',va='top',weight='bold',family='monospace',\n xycoords='figure fraction',size=12,color='g')\n swhlab.plot.annotate(abf)\n return\n\ndef checkSweep(abf=exampleABF,sweep=0):\n \"\"\"Produce an eyeball-ready indication how the MT was calculated in VC.\"\"\"\n if abf.units==\"mV\":\n return checkSweepIC(abf,sweep)\n if abf.MTs[sweep] is None:\n return False #no memtest data even found\n _keys = abf.MTs[sweep].dtype.names\n for key in _keys:\n globals()[key]=abf.MTs[sweep][key] # only global for this module, that's fine.\n _msg2=\"Average (n=%d)\\n\"%abf.sweeps\n _msg=\"\"\n for i in range(len(_keys)):\n _msg+=\"%s=%s\\n\"%(_keys[i],abf.MTs[sweep][i])\n if _keys[i] in ['Ih','Ra','Rm','Cm','Tv','Tm']:\n _msg2+=\"%s=%.02f\\n\"%(_keys[i],abf.MTs[sweep][i])\n fitted=cm.algo_exp(np.arange(TCB-TCA),fitM,fitT,fitB)\n pylab.figure(figsize=(8,8))\n for subplot in [211,212]:\n pylab.subplot(subplot)\n #pylab.plot(abf.dataX,abf.dataY,alpha=.2,color='k',lw=2)\n pylab.plot(abf.dataX[:TCA],abf.dataY[:TCA],alpha=.2,color='k',lw=2)\n pylab.plot(abf.dataX[TCB:],abf.dataY[TCB:],alpha=.2,color='k',lw=2)\n pylab.plot(abf.dataX[TCA:TCB],abf.dataY[TCA:TCB],'o',alpha=.5,lw=4,mfc='none',mec='r')\n pylab.plot(abf.dataX[T1A:T1B],abf.dataY[T1A:T1B],alpha=.4,color='b')\n pylab.plot(abf.dataX[T2A:T2B],abf.dataY[T2A:T2B],alpha=.4,color='b')\n pylab.plot(abf.dataX[TCA:TCB],fitted,color='k',lw=2,ls=\"--\")\n for i in [TA, TB]:\n pylab.axvline(i/abf.rate,color='k',ls='--',alpha=.4)\n for i in [P1,P2]:\n pylab.axhline(i,color='b',ls=\"--\",alpha=.5)\n for i in [PCA,PCB,PP]:\n pylab.axhline(i,color='g',ls=\"--\",alpha=.5)\n pylab.tight_layout()\n pylab.subplots_adjust(right=0.75)\n pylab.annotate(_msg,(.8,.75),ha='left',va='top',alpha=.5,\n xycoords='figure fraction',family='monospace',size=10)\n pylab.annotate(_msg2,(.8,.95),ha='left',va='top',weight='bold',family='monospace',\n xycoords='figure fraction',size=12,color='g')\n pylab.subplot(211)\n pylab.axis([None,abf.dataX[T2B]+.05,None,None])\n pylab.subplot(212)\n pylab.axis([(TB-20)/abf.rate,(TCB+20)/abf.rate,P1-20,PP+20])\n swhlab.plot.annotate(abf)\n for key in _keys:\n del key #be clean about screwing with globals()\n return\n\ndef test():\n \"\"\"voltage clamp MT.\"\"\"\n abf=swhlab.ABF(r'C:\\Apps\\pythonModules\\abfs\\16701010.abf')\n swhlab.memtest.memtest(abf) #performs memtest on all sweeps\n swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did\n pylab.show()\n\ndef test2():\n \"\"\"current clamp MT.\"\"\"\n abf=swhlab.ABF(r'C:\\Apps\\pythonModules\\abfs\\16701006.abf')\n swhlab.memtest.memtest(abf) #performs memtest on all sweeps\n swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did\n pylab.show()\n\nif __name__==\"__main__\":\n #test()\n #test2()\n test3()\n print(\"DONE\")" ]
[ [ "numpy.arange", "numpy.max", "numpy.average", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JelleAalbers/lenstronomy
[ "6db785667ff099fa8338e972b66253b2901b2827" ]
[ "lenstronomy/LensModel/MultiPlane/multi_plane_base.py" ]
[ "import numpy as np\nfrom lenstronomy.Cosmo.background import Background\nfrom lenstronomy.LensModel.profile_list_base import ProfileListBase\nimport lenstronomy.Util.constants as const\n\n__all__ = ['MultiPlaneBase']\n\n\nclass MultiPlaneBase(ProfileListBase):\n\n \"\"\"\n Multi-plane lensing class\n\n The lens model deflection angles are in units of reduced deflections from the specified redshift of the lens to the\n source redshift of the class instance.\n \"\"\"\n\n def __init__(self, lens_model_list, lens_redshift_list, z_source_convention, cosmo=None,\n numerical_alpha_class=None, cosmo_interp=False, z_interp_stop=None, num_z_interp=100):\n \"\"\"\n A description of the recursive multi-plane formalism can be found e.g. here: https://arxiv.org/abs/1312.1536\n\n :param lens_model_list: list of lens model strings\n :param lens_redshift_list: list of floats with redshifts of the lens models indicated in lens_model_list\n :param z_source_convention: float, redshift of a source to define the reduced deflection angles of the lens\n models. If None, 'z_source' is used.\n :param cosmo: instance of astropy.cosmology\n :param numerical_alpha_class: an instance of a custom class for use in NumericalAlpha() lens model\n (see documentation in Profiles/numerical_alpha)\n\n \"\"\"\n if z_interp_stop is None:\n z_interp_stop = z_source_convention\n self._cosmo_bkg = Background(cosmo, interp=cosmo_interp, z_stop=z_interp_stop, num_interp=num_z_interp)\n self._z_source_convention = z_source_convention\n if len(lens_redshift_list) > 0:\n z_lens_max = np.max(lens_redshift_list)\n if z_lens_max >= z_source_convention:\n raise ValueError('deflector redshifts higher or equal the source redshift convention (%s >= %s for the reduced lens'\n ' model quantities not allowed (leads to negative reduced deflection angles!'\n % (z_lens_max, z_source_convention))\n if not len(lens_model_list) == len(lens_redshift_list):\n raise ValueError(\"The length of lens_model_list does not correspond to redshift_list\")\n\n self._lens_redshift_list = lens_redshift_list\n super(MultiPlaneBase, self).__init__(lens_model_list, numerical_alpha_class=numerical_alpha_class,\n lens_redshift_list=lens_redshift_list,\n z_source_convention=z_source_convention)\n\n if len(lens_model_list) < 1:\n self._sorted_redshift_index = []\n else:\n self._sorted_redshift_index = self._index_ordering(lens_redshift_list)\n z_before = 0\n T_z = 0\n self._T_ij_list = []\n self._T_z_list = []\n # Sort redshift for vectorized reduced2physical factor calculation\n if len(lens_model_list)<1:\n self._reduced2physical_factor = []\n else:\n z_sort = np.array(self._lens_redshift_list)[self._sorted_redshift_index]\n z_source_array = np.ones(z_sort.shape)*z_source_convention\n self._reduced2physical_factor = self._cosmo_bkg.d_xy(0, z_source_convention) / self._cosmo_bkg.d_xy(z_sort, z_source_array)\n for idex in self._sorted_redshift_index:\n z_lens = self._lens_redshift_list[idex]\n if z_before == z_lens:\n delta_T = 0\n else:\n T_z = self._cosmo_bkg.T_xy(0, z_lens)\n delta_T = self._cosmo_bkg.T_xy(z_before, z_lens)\n self._T_ij_list.append(delta_T)\n self._T_z_list.append(T_z)\n z_before = z_lens\n\n def ray_shooting_partial(self, x, y, alpha_x, alpha_y, z_start, z_stop, kwargs_lens,\n include_z_start=False, T_ij_start=None, T_ij_end=None):\n \"\"\"\n ray-tracing through parts of the coin, starting with (x,y) co-moving distances and angles (alpha_x, alpha_y)\n at redshift z_start and then backwards to redshift z_stop\n\n :param x: co-moving position [Mpc]\n :param y: co-moving position [Mpc]\n :param alpha_x: ray angle at z_start [arcsec]\n :param alpha_y: ray angle at z_start [arcsec]\n :param z_start: redshift of start of computation\n :param z_stop: redshift where output is computed\n :param kwargs_lens: lens model keyword argument list\n :param include_z_start: bool, if True, includes the computation of the deflection angle at the same redshift as\n the start of the ray-tracing. ATTENTION: deflection angles at the same redshift as z_stop will be computed always!\n This can lead to duplications in the computation of deflection angles.\n :param T_ij_start: transverse angular distance between the starting redshift to the first lens plane to follow.\n If not set, will compute the distance each time this function gets executed.\n :param T_ij_end: transverse angular distance between the last lens plane being computed and z_end.\n If not set, will compute the distance each time this function gets executed.\n :return: co-moving position and angles at redshift z_stop\n \"\"\"\n x = np.array(x, dtype=float)\n y = np.array(y, dtype=float)\n alpha_x = np.array(alpha_x)\n alpha_y = np.array(alpha_y)\n z_lens_last = z_start\n first_deflector = True\n\n for i, idex in enumerate(self._sorted_redshift_index):\n z_lens = self._lens_redshift_list[idex]\n\n if self._start_condition(include_z_start, z_lens, z_start) and z_lens <= z_stop:\n if first_deflector is True:\n if T_ij_start is None:\n if z_start == 0:\n delta_T = self._T_ij_list[0]\n else:\n delta_T = self._cosmo_bkg.T_xy(z_start, z_lens)\n else:\n delta_T = T_ij_start\n first_deflector = False\n else:\n delta_T = self._T_ij_list[i]\n x, y = self._ray_step_add(x, y, alpha_x, alpha_y, delta_T)\n alpha_x, alpha_y = self._add_deflection(x, y, alpha_x, alpha_y, kwargs_lens, i)\n\n z_lens_last = z_lens\n if T_ij_end is None:\n if z_lens_last == z_stop:\n delta_T = 0\n else:\n delta_T = self._cosmo_bkg.T_xy(z_lens_last, z_stop)\n else:\n delta_T = T_ij_end\n x, y = self._ray_step_add(x, y, alpha_x, alpha_y, delta_T)\n return x, y, alpha_x, alpha_y\n\n def transverse_distance_start_stop(self, z_start, z_stop, include_z_start=False):\n \"\"\"\n computes the transverse distance (T_ij) that is required by the ray-tracing between the starting redshift and\n the first deflector afterwards and the last deflector before the end of the ray-tracing.\n\n :param z_start: redshift of the start of the ray-tracing\n :param z_stop: stop of ray-tracing\n :param include_z_start: boolean, if True includes the computation of the starting position if the first\n deflector is at z_start\n :return: T_ij_start, T_ij_end\n \"\"\"\n z_lens_last = z_start\n first_deflector = True\n T_ij_start = None\n for i, idex in enumerate(self._sorted_redshift_index):\n z_lens = self._lens_redshift_list[idex]\n if self._start_condition(include_z_start, z_lens, z_start) and z_lens <= z_stop:\n if first_deflector is True:\n T_ij_start = self._cosmo_bkg.T_xy(z_start, z_lens)\n first_deflector = False\n z_lens_last = z_lens\n T_ij_end = self._cosmo_bkg.T_xy(z_lens_last, z_stop)\n return T_ij_start, T_ij_end\n\n def geo_shapiro_delay(self, theta_x, theta_y, kwargs_lens, z_stop, T_z_stop=None, T_ij_end=None):\n \"\"\"\n geometric and Shapiro (gravitational) light travel time relative to a straight path through the coordinate (0,0)\n Negative sign means earlier arrival time\n\n :param theta_x: angle in x-direction on the image\n :param theta_y: angle in y-direction on the image\n :param kwargs_lens: lens model keyword argument list\n :param z_stop: redshift of the source to stop the backwards ray-tracing\n :param T_z_stop: optional, transversal angular distance from z=0 to z_stop\n :param T_ij_end: optional, transversal angular distance between the last lensing plane and the source plane\n :return: dt_geo, dt_shapiro, [days]\n \"\"\"\n dt_grav = np.zeros_like(theta_x, dtype=float)\n dt_geo = np.zeros_like(theta_x, dtype=float)\n x = np.zeros_like(theta_x, dtype=float)\n y = np.zeros_like(theta_y, dtype=float)\n alpha_x = np.array(theta_x, dtype=float)\n alpha_y = np.array(theta_y, dtype=float)\n i = 0\n z_lens_last = 0\n for i, index in enumerate(self._sorted_redshift_index):\n z_lens = self._lens_redshift_list[index]\n if z_lens <= z_stop:\n T_ij = self._T_ij_list[i]\n x_new, y_new = self._ray_step(x, y, alpha_x, alpha_y, T_ij)\n if i == 0:\n pass\n elif T_ij > 0:\n T_j = self._T_z_list[i]\n T_i = self._T_z_list[i - 1]\n beta_i_x, beta_i_y = x / T_i, y / T_i\n beta_j_x, beta_j_y = x_new / T_j, y_new / T_j\n dt_geo_new = self._geometrical_delay(beta_i_x, beta_i_y, beta_j_x, beta_j_y, T_i, T_j, T_ij)\n dt_geo += dt_geo_new\n x, y = x_new, y_new\n dt_grav_new = self._gravitational_delay(x, y, kwargs_lens, i, z_lens)\n alpha_x, alpha_y = self._add_deflection(x, y, alpha_x, alpha_y, kwargs_lens, i)\n\n dt_grav += dt_grav_new\n z_lens_last = z_lens\n if T_ij_end is None:\n T_ij_end = self._cosmo_bkg.T_xy(z_lens_last, z_stop)\n T_ij = T_ij_end\n x_new, y_new = self._ray_step(x, y, alpha_x, alpha_y, T_ij)\n if T_z_stop is None:\n T_z_stop = self._cosmo_bkg.T_xy(0, z_stop)\n T_j = T_z_stop\n T_i = self._T_z_list[i]\n beta_i_x, beta_i_y = x / T_i, y / T_i\n beta_j_x, beta_j_y = x_new / T_j, y_new / T_j\n dt_geo_new = self._geometrical_delay(beta_i_x, beta_i_y, beta_j_x, beta_j_y, T_i, T_j, T_ij)\n dt_geo += dt_geo_new\n return dt_geo, dt_grav\n\n @staticmethod\n def _index_ordering(redshift_list):\n \"\"\"\n\n :param redshift_list: list of redshifts\n :return: indexes in ascending order to be evaluated (from z=0 to z=z_source)\n \"\"\"\n redshift_list = np.array(redshift_list)\n #sort_index = np.argsort(redshift_list[redshift_list < z_source])\n sort_index = np.argsort(redshift_list)\n #if len(sort_index) < 1:\n # Warning(\"There is no lens object between observer at z=0 and source at z=%s\" % z_source)\n return sort_index\n\n def _reduced2physical_deflection(self, alpha_reduced, index_lens):\n \"\"\"\n alpha_reduced = D_ds/Ds alpha_physical\n\n :param alpha_reduced: reduced deflection angle\n :param index_lens: integer, index of the deflector plane\n :return: physical deflection angle\n \"\"\"\n factor = self._reduced2physical_factor[index_lens]\n return alpha_reduced * factor\n\n def _gravitational_delay(self, x, y, kwargs_lens, index, z_lens):\n \"\"\"\n\n :param x: co-moving coordinate at the lens plane\n :param y: co-moving coordinate at the lens plane\n :param kwargs_lens: lens model keyword arguments\n :param z_lens: redshift of the deflector\n :param index: index of the lens model in sorted redshfit convention\n :return: gravitational delay in units of days as seen at z=0\n \"\"\"\n theta_x, theta_y = self._co_moving2angle(x, y, index)\n k = self._sorted_redshift_index[index]\n potential = self.func_list[k].function(theta_x, theta_y, **kwargs_lens[k])\n delay_days = self._lensing_potential2time_delay(potential, z_lens, z_source=self._z_source_convention)\n return -delay_days\n\n @staticmethod\n def _geometrical_delay(beta_i_x, beta_i_y, beta_j_x, beta_j_y, T_i, T_j, T_ij):\n \"\"\"\n\n :param beta_i_x: angle on the sky at plane i\n :param beta_i_y: angle on the sky at plane i\n :param beta_j_x: angle on the sky at plane j\n :param beta_j_y: angle on the sky at plane j\n :param T_i: transverse diameter distance to z_i\n :param T_j: transverse diameter distance to z_j\n :param T_ij: transverse diameter distance from z_i to z_j\n :return: excess delay relative to a straight line\n \"\"\"\n d_beta_x = beta_j_x - beta_i_x\n d_beta_y = beta_j_y - beta_i_y\n tau_ij = T_i * T_j / T_ij * const.Mpc / const.c / const.day_s * const.arcsec**2\n return tau_ij * (d_beta_x ** 2 + d_beta_y ** 2) / 2\n\n def _lensing_potential2time_delay(self, potential, z_lens, z_source):\n \"\"\"\n transforms the lensing potential (in units arcsec^2) to a gravitational time-delay as measured at z=0\n\n :param potential: lensing potential\n :param z_lens: redshift of the deflector\n :param z_source: redshift of source for the definition of the lensing quantities\n :return: gravitational time-delay in units of days\n \"\"\"\n D_dt = self._cosmo_bkg.ddt(z_lens, z_source)\n delay_days = const.delay_arcsec2days(potential, D_dt)\n return delay_days\n\n def _co_moving2angle(self, x, y, index):\n \"\"\"\n transforms co-moving distances Mpc into angles on the sky (radian)\n\n :param x: co-moving distance\n :param y: co-moving distance\n :param index: index of plane\n :return: angles on the sky\n \"\"\"\n T_z = self._T_z_list[index]\n theta_x = x / T_z\n theta_y = y / T_z\n return theta_x, theta_y\n\n @staticmethod\n def _ray_step(x, y, alpha_x, alpha_y, delta_T):\n \"\"\"\n ray propagation with small angle approximation\n\n :param x: co-moving x-position\n :param y: co-moving y-position\n :param alpha_x: deflection angle in x-direction at (x, y)\n :param alpha_y: deflection angle in y-direction at (x, y)\n :param delta_T: transverse angular diameter distance to the next step\n :return: co-moving position at the next step (backwards)\n \"\"\"\n x_ = x + alpha_x * delta_T\n y_ = y + alpha_y * delta_T\n return x_, y_\n\n @staticmethod\n def _ray_step_add(x, y, alpha_x, alpha_y, delta_T):\n \"\"\"\n ray propagation with small angle approximation\n\n :param x: co-moving x-position\n :param y: co-moving y-position\n :param alpha_x: deflection angle in x-direction at (x, y)\n :param alpha_y: deflection angle in y-direction at (x, y)\n :param delta_T: transverse angular diameter distance to the next step\n :return: co-moving position at the next step (backwards)\n \"\"\"\n x += alpha_x * delta_T\n y += alpha_y * delta_T\n return x, y\n\n def _add_deflection(self, x, y, alpha_x, alpha_y, kwargs_lens, index):\n \"\"\"\n adds the physical deflection angle of a single lens plane to the deflection field\n\n :param x: co-moving distance at the deflector plane\n :param y: co-moving distance at the deflector plane\n :param alpha_x: physical angle (radian) before the deflector plane\n :param alpha_y: physical angle (radian) before the deflector plane\n :param kwargs_lens: lens model parameter kwargs\n :param index: index of the lens model to be added in sorted redshift list convention\n :param idex_lens: redshift of the deflector plane\n :return: updated physical deflection after deflector plane (in a backwards ray-tracing perspective)\n \"\"\"\n theta_x, theta_y = self._co_moving2angle(x, y, index)\n k = self._sorted_redshift_index[index]\n alpha_x_red, alpha_y_red = self.func_list[k].derivatives(theta_x, theta_y, **kwargs_lens[k])\n alpha_x_phys = self._reduced2physical_deflection(alpha_x_red, index)\n alpha_y_phys = self._reduced2physical_deflection(alpha_y_red, index)\n return alpha_x - alpha_x_phys, alpha_y - alpha_y_phys\n\n @staticmethod\n def _start_condition(inclusive, z_lens, z_start):\n \"\"\"\n\n :param inclusive: boolean, if True selects z_lens including z_start, else only selects z_lens > z_start\n :param z_lens: deflector redshift\n :param z_start: starting redshift (lowest redshift)\n :return: boolean of condition\n \"\"\"\n\n if inclusive:\n return z_lens >= z_start\n else:\n return z_lens > z_start\n" ]
[ [ "numpy.ones", "numpy.max", "numpy.zeros_like", "numpy.argsort", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
benvcutilli/CountingPlusFriendly
[ "1947e2a765e20c87e080da22b4ecc4da1f272b02" ]
[ "Friendly/LaTeX/figures/cosinecomparison.py" ]
[ "# The Plotly^^^plotly^^^ package\nimport plotly\n\n# Importing ^^^numpy^^^\nimport numpy\n\n\n\n\ndef sigmoid(x):\n return (1 + numpy.exp(-x)) ** -1\n\n\n\n\n\n\n\n\n\nsamplesPerDimension = 500\n# Using numpy.linspace to create x and y values is from somewhere on ^^^plotly^^^'s website, most\n# likely. It is a convenient way to do this, so that's why.\nevaluationRange = numpy.linspace([-5, -5], [5, 5], samplesPerDimension, axis=1)\n\n\n# Using the technique that I used from networkcomponents.py (PairwiseDifference) where one dimension\n# is on the first axis and the other is on the second axis so that they can broadcast to create all\n# permutations between the array of x values and the array of y values. Before broadcasting, we need\n# to add a dimension to both the x vector and y vector, but at the beginning and end of them,\n# respectively, which is also what happens in PairwiseDifference. However, this code doesn't\n# actually broadcast, but it mimics broadcasting with the .repeat(...) calls.\n####################################################################################################\n# #\n\nx = numpy.expand_dims(evaluationRange[0], 0).repeat(samplesPerDimension, 0)\ny = numpy.expand_dims(evaluationRange[1], 1).repeat(samplesPerDimension, 1)\nevaluationPairs = numpy.stack([x, y], 2)\n\n# #\n####################################################################################################\n\nweights = numpy.array([1, 1])\nconstant = 1.0\n\n# Calculating every combination for the three functions\ndotProduct = numpy.dot(evaluationPairs, weights)\ncosine = dotProduct \\\n / \\\n ( numpy.linalg.norm(weights) * numpy.linalg.norm(evaluationPairs, axis=2) )\nsoftenedCosine = dotProduct \\\n / \\\n ( numpy.linalg.norm(weights) * numpy.linalg.norm(evaluationPairs, axis=2) + constant)\n\n\n\ndotProductSurface = plotly.graph_objects.Surface(\n x=evaluationRange[0],\n y=evaluationRange[1], z=sigmoid(dotProduct)\n )\n\ncosineSurface = plotly.graph_objects.Surface(\n x=evaluationRange[0],\n y=evaluationRange[1], z=cosine\n )\n\nsoftenedCosineSurface = plotly.graph_objects.Surface(\n x=evaluationRange[0],\n y=evaluationRange[1], z=softenedCosine\n )\n\n\nfigure = plotly.graph_objects.Figure(\n softenedCosineSurface,\n layout={ \"scene\": { \"aspectmode\": \"data\" } }\n )\n\n# \"validate\" left as True partially because I trust the default value listed in\n# ^^^plotlyfigureshow^^^\nfigure.show(renderer=\"firefox\")\n\n#figure.write_image(\"graph.png\", \"png\", 1200, 900, 1.0, True, \"kaleido\")" ]
[ [ "numpy.dot", "numpy.expand_dims", "numpy.linspace", "numpy.linalg.norm", "numpy.stack", "numpy.exp", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
530824679/YOLOv2
[ "eff9ddbab58da970e7fb449cd1974fb810fd6023" ]
[ "model/ops.py" ]
[ "# -*- coding: utf-8 -*-\n# --------------------------------------\n# @Time : 2020/11/01\n# @Author : Oscar Chen\n# @Email : [email protected]\n# @File : ops.py\n# Description :base operators.\n# --------------------------------------\n\nimport tensorflow as tf\n\ndef leaky_relu(x):\n return tf.nn.leaky_relu(x, alpha=0.1, name='leaky_relu')\n\ndef conv2d(inputs, filters_num, filters_size, pad_size=0, stride=1, batch_normalize=True, activation=leaky_relu, use_bias=False, is_train=True, name='conv2d'):\n if pad_size > 0:\n inputs = tf.pad(inputs, [[0,0], [pad_size, pad_size], [pad_size, pad_size],[0,0]])\n\n out = tf.layers.conv2d(inputs, filters=filters_num, kernel_size=filters_size, strides=stride, padding='VALID', activation=None, use_bias=use_bias, name=name)\n\n if batch_normalize:\n out = tf.layers.batch_normalization(out, axis=-1, momentum=0.9, training=is_train, name=name+'_bn')\n\n if activation:\n out = activation(out)\n\n return out\n\ndef maxpool(inputs, size=2, stride=2, name='maxpool'):\n with tf.name_scope(name):\n out = tf.layers.max_pooling2d(inputs, pool_size=size, strides=stride, padding='SAME')\n return out\n\ndef reorg(inputs, stride):\n return tf.space_to_depth(inputs, block_size=stride)" ]
[ [ "tensorflow.layers.conv2d", "tensorflow.layers.batch_normalization", "tensorflow.space_to_depth", "tensorflow.layers.max_pooling2d", "tensorflow.name_scope", "tensorflow.pad", "tensorflow.nn.leaky_relu" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
thaipduong/safe-control-gym
[ "69f8f627d232d50813a7fff6113dd6d5caccf930" ]
[ "safe_control_gym/controllers/mpc/gp_mpc_hexa.py" ]
[ "\"\"\"Model Predictive Control with a Gaussian Process model.\n\nBased on:\n * L. Hewing, J. Kabzan and M. N. Zeilinger, \"Cautious Model Predictive Control Using Gaussian Process Regression,\"\n in IEEE Transactions on Control Systems Technology, vol. 28, no. 6, pp. 2736-2743, Nov. 2020, doi: 10.1109/TCST.2019.2949757.\n\nImplementation details:\n 1. The previous time step MPC solution is used to compute the set constraints and GP dynamics rollout.\n Here, the dynamics are rolled out using the Mean Equivelence method, the fastest, but least accurate.\n 2. The GP is approximated using the Fully Independent Training Conditional (FITC) outlined in\n * J. Quinonero-Candela, C. E. Rasmussen, and R. Herbrich, “A unifying view of sparse approximate Gaussian process regression,”\n Journal of Machine Learning Research, vol. 6, pp. 1935–1959, 2005.\n https://www.jmlr.org/papers/volume6/quinonero-candela05a/quinonero-candela05a.pdf\n * E. Snelson and Z. Ghahramani, “Sparse gaussian processes using pseudo-inputs,” in Advances in Neural Information Processing\n Systems, Y. Weiss, B. Scholkopf, and J. C. Platt, Eds., 2006, pp. 1257–1264.\n and the inducing points are the previous MPC solution.\n 3. Each dimension of the learned error dynamics is an independent Zero Mean SE Kernel GP.\n\n\"\"\"\nimport scipy\nimport numpy as np\nimport casadi as cs\nimport time\nimport torch\nimport gpytorch\n\nfrom copy import deepcopy\nfrom skopt.sampler import Lhs\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\n\nfrom safe_control_gym.controllers.mpc.linear_mpc import LinearMPC, MPC\nfrom safe_control_gym.controllers.mpc.mpc_utils import discretize_linear_system\nfrom safe_control_gym.controllers.mpc.gp_utils import GaussianProcessCollection, ZeroMeanIndependentGPModel, covSEard\nfrom safe_control_gym.envs.benchmark_env import Task\n\n\nclass GPMPC(MPC):\n \"\"\"MPC with Gaussian Process as dynamics residual. \n\n \"\"\"\n\n def __init__(\n self,\n env_func,\n seed: int = 1337,\n horizon: int = 5,\n q_mpc: list = [1],\n r_mpc: list = [1],\n additional_constraints: list = None,\n use_prev_start: bool = True,\n train_iterations: int = 800,\n validation_iterations: int = 200,\n optimization_iterations: list = None,\n learning_rate: list = None,\n normalize_training_data: bool = False,\n use_gpu: bool = False,\n gp_model_path: str = None,\n prob: float = 0.955,\n initial_rollout_std: float = 0.005,\n input_mask: list = None,\n target_mask: list = None,\n gp_approx: str = 'mean_eq',\n sparse_gp: bool = False,\n online_learning: bool = False,\n inertial_prop: list = [1.0],\n prior_param_coeff: float = 1.0,\n output_dir: str = \"results/temp\",\n **kwargs\n ):\n \"\"\"Initialize GP-MPC.\n\n Args:\n env_func (gym.Env): functionalized initialization of the environment.\n seed (int): random seed.\n horizon (int): MPC planning horizon.\n Q, R (np.array): cost weight matrix.\n use_prev_start (bool): Warmstart mpc with the previous solution.\n train_iterations (int): the number of training examples to use for each dimension of the GP.\n validation_iterations (int): the number of points to use use for the test set during training.\n optimization_iterations (list): the number of optimization iterations for each dimension of the GP.\n learning_rate (list): the learning rate for training each dimension of the GP.\n normalize_training_data (bool): Normalize the training data.\n use_gpu (bool): use GPU while training the gp.\n gp_model_path (str): path to a pretrained GP model. If None, will train a new one.\n output_dir (str): directory to store model and results.\n prob (float): desired probabilistic safety level.\n initial_rollout_std (float): the initial std (across all states) for the mean_eq rollout.\n inertial_prop (list): to initialize the inertial properties of the prior model.\n prior_param_coeff (float): constant multiplying factor to adjust the prior model intertial properties.\n input_mask (list): list of which input dimensions to use in GP model. If None, all are used.\n target_mask (list): list of which output dimensions to use in the GP model. If None, all are used.\n gp_approx (str): 'mean_eq' used mean equivalence rollout for the GP dynamics. Only one that works currently.\n online_learning (bool): if true, GP kernel values will be updated using past trajectory values.\n additional_constraints (list): list of Constraint objects defining additional constraints to be used.\n\n \"\"\"\n print(\"############################################### GP-MPC hexa ###########################################\")\n self.prior_env_func = partial(env_func,\n inertial_prop=np.array(inertial_prop)*prior_param_coeff)\n self.prior_param_coeff = prior_param_coeff\n # Initialize the method using linear MPC.\n self.prior_ctrl = LinearMPC(\n self.prior_env_func,\n horizon=horizon,\n q_mpc=q_mpc,\n r_mpc=r_mpc,\n use_prev_start=use_prev_start,\n output_dir=output_dir,\n additional_constraints=additional_constraints,\n )\n self.prior_ctrl.reset()\n super().__init__(\n self.prior_env_func,\n horizon=horizon,\n q_mpc=q_mpc,\n r_mpc=r_mpc,\n use_prev_start=use_prev_start,\n output_dir=output_dir,\n additional_constraints=additional_constraints,\n **kwargs)\n # Setup environments.\n self.env_func = env_func\n self.env = env_func(randomized_init=False)\n self.env_training = env_func(randomized_init=True)\n # No training data accumulated yet so keep the dynamics function as linear prior.\n self.train_data = None\n self.prior_dynamics_func = self.prior_ctrl.linear_dynamics_func\n # GP and training parameters.\n self.gaussian_process = None\n self.train_iterations = train_iterations\n self.validation_iterations = validation_iterations\n self.optimization_iterations = optimization_iterations\n self.learning_rate = learning_rate\n self.gp_model_path = gp_model_path\n self.normalize_training_data = normalize_training_data\n self.use_gpu = use_gpu\n self.seed = seed\n self.prob = prob\n self.sparse_gp = sparse_gp\n if input_mask is None:\n self.input_mask = np.arange(self.model.nx + self.model.nu).tolist()\n else:\n self.input_mask = input_mask\n if target_mask is None:\n self.target_mask = np.arange(self.model.nx).tolist()\n else:\n self.target_mask = target_mask\n Bd = np.eye(self.model.nx)\n self.Bd = Bd[:, self.target_mask]\n self.gp_approx = gp_approx\n self.online_learning = online_learning\n self.last_obs = None\n self.last_action = None\n self.initial_rollout_std = initial_rollout_std\n\n def setup_prior_dynamics(self):\n \"\"\"Computes the LQR gain used for propograting GP uncertainty from the prior model dynamics.\n\n \"\"\"\n # Determine the LQR gain K to propogate the input uncertainty (doing this at each timestep will increase complexity).\n A, B = discretize_linear_system(self.prior_ctrl.dfdx, self.prior_ctrl.dfdu, self.dt)\n Q_lqr = self.Q\n R_lqr = self.R\n P = scipy.linalg.solve_discrete_are(A, B, Q_lqr, R_lqr)\n btp = np.dot(B.T, P)\n self.lqr_gain = -np.dot(np.linalg.inv(self.R + np.dot(btp, B)), np.dot(btp, A))\n self.discrete_dfdx = A\n self.discrete_dfdu = B\n\n def set_gp_dynamics_func(self):\n \"\"\"Updates symbolic dynamics.\n\n With actual control frequency, initialize GP model and add to the combined dynamics.\n\n \"\"\"\n self.setup_prior_dynamics()\n # Compute the probabilistic constraint inverse CDF according to section III.D.b in Hewing 2019.\n self.inverse_cdf = scipy.stats.norm.ppf(1 - (1/self.model.nx - (self.prob + 1)/(2*self.model.nx)))\n self.create_sparse_GP_machinery()\n\n def create_sparse_GP_machinery(self):\n \"\"\"This setups the gaussian process approximations for FITC formulation.\n\n \"\"\"\n lengthscales, signal_var, noise_var, gp_K_plus_noise = self.gaussian_process.get_hyperparameters(as_numpy=True)\n self.length_scales = lengthscales.squeeze()\n self.signal_var = signal_var.squeeze()\n self.noise_var = noise_var.squeeze()\n self.gp_K_plus_noise = gp_K_plus_noise\n Nx = len(self.input_mask)\n Ny = len(self.target_mask)\n N = self.gaussian_process.n_training_samples\n # Create CasADI function for computing the kernel K_z_zind with parameters for z, z_ind, length scales and signal variance.\n # We need the CasADI version of this so that it can by symbolically differentiated in in the MPC optimization.\n z1 = cs.SX.sym('z1', Nx)\n z2 = cs.SX.sym('z2', Nx)\n ell_s = cs.SX.sym('ell', Nx)\n sf2_s = cs.SX.sym('sf2')\n z_ind = cs.SX.sym('z_ind', self.T, Nx)\n covSE = cs.Function('covSE', [z1, z2, ell_s, sf2_s],\n [covSEard(z1, z2, ell_s, sf2_s)])\n ks = cs.SX.zeros(1, self.T)\n for i in range(self.T):\n ks[i] = covSE(z1, z_ind[i, :], ell_s, sf2_s)\n ks_func = cs.Function('K_s', [z1, z_ind, ell_s, sf2_s], [ks])\n K_z_zind = cs.SX.zeros(Ny, self.T)\n for i in range(Ny):\n K_z_zind[i,:] = ks_func(z1, z_ind, self.length_scales[i,:], self.signal_var[i])\n # This will be mulitplied by the mean_post_factor computed at every time step to compute the approximate mean.\n self.K_z_zind_func = cs.Function('K_z_zind', [z1, z_ind],[K_z_zind],['z1', 'z2'],['K'])\n\n def preprocess_training_data(self,\n x_seq,\n u_seq,\n x_next_seq\n ):\n \"\"\"Converts trajectory data for GP trianing.\n \n Args:\n x_seq (list): state sequence of np.array (nx,). \n u_seq (list): action sequence of np.array (nu,). \n x_next_seq (list): next state sequence of np.array (nx,). \n \n Returns:\n np.array: inputs for GP training, (N, nx+nu).\n np.array: targets for GP training, (N, nx).\n\n \"\"\"\n # Get the predicted dynamics. This is a linear prior, thus we need to account for the fact that\n # it is linearized about an eq using self.X_GOAL and self.U_GOAL.\n x_pred_seq = self.prior_dynamics_func(x0=x_seq.T - self.prior_ctrl.X_LIN[:, None],\n p=u_seq.T - self.prior_ctrl.U_LIN[:,None])['xf'].toarray()\n targets = (x_next_seq.T - (x_pred_seq+self.prior_ctrl.X_LIN[:,None])).transpose() # (N, nx).\n inputs = np.hstack([x_seq, u_seq]) # (N, nx+nu).\n return inputs, targets\n\n def precompute_probabilistic_limits(self,\n print_sets=True\n ):\n \"\"\"This updates the constraint value limits to account for the uncertainty in the dynamics rollout.\n\n Args:\n print_sets (bool): True to print out the sets for debugging purposes.\n\n \"\"\"\n nx, nu = self.model.nx, self.model.nu\n T = self.T\n state_covariances = np.zeros((self.T+1, nx, nx))\n input_covariances = np.zeros((self.T, nu, nu))\n # Initilize lists for the tightening of each constraint.\n state_constraint_set = []\n for state_constraint in self.constraints.state_constraints:\n state_constraint_set.append(np.zeros((state_constraint.num_constraints, T+1)))\n input_constraint_set = []\n for input_constraint in self.constraints.input_constraints:\n input_constraint_set.append(np.zeros((input_constraint.num_constraints, T)))\n if self.x_prev is not None and self.u_prev is not None:\n cov_x = np.diag([self.initial_rollout_std**2]*nx)\n for i in range(T):\n state_covariances[i] = cov_x\n cov_u = self.lqr_gain @ cov_x @ self.lqr_gain.T\n input_covariances[i] = cov_u\n cov_xu = cov_x @ self.lqr_gain.T\n z = np.hstack((self.x_prev[:,i], self.u_prev[:,i]))\n if self.gp_approx == 'taylor':\n raise NotImplementedError(\"Taylor GP approximation is currently not working.\")\n elif self.gp_approx == 'mean_eq':\n _, cov_d_tensor = self.gaussian_process.predict(z[None,:], return_pred=False)\n cov_d = cov_d_tensor.detach().numpy()\n else:\n raise NotImplementedError('gp_approx method is incorrect or not implemented')\n # Loop through input constraints and tighten by the required ammount.\n for ui, input_constraint in enumerate(self.constraints.input_constraints):\n input_constraint_set[ui][:, i] = -1*self.inverse_cdf * \\\n np.absolute(input_constraint.A) @ np.sqrt(np.diag(cov_u))\n for si, state_constraint in enumerate(self.constraints.state_constraints):\n state_constraint_set[si][:, i] = -1*self.inverse_cdf * \\\n np.absolute(state_constraint.A) @ np.sqrt(np.diag(cov_x))\n if self.gp_approx == 'taylor':\n raise NotImplementedError(\"Taylor GP rollout not implemented.\")\n elif self.gp_approx == 'mean_eq':\n # Compute the next step propogated state covariance using mean equivilence.\n cov_x = self.discrete_dfdx @ cov_x @ self.discrete_dfdx.T + \\\n self.discrete_dfdx @ cov_xu @ self.discrete_dfdu.T + \\\n self.discrete_dfdu @ cov_xu.T @ self.discrete_dfdx.T + \\\n self.discrete_dfdu @ cov_u @ self.discrete_dfdu.T + \\\n self.Bd @ cov_d @ self.Bd.T\n else:\n raise NotImplementedError('gp_approx method is incorrect or not implemented')\n # Udate Final covariance.\n for si, state_constraint in enumerate(self.constraints.state_constraints):\n state_constraint_set[si][:,-1] = -1 * self.inverse_cdf * \\\n np.absolute(state_constraint.A) @ np.sqrt(np.diag(cov_x))\n state_covariances[-1] = cov_x\n if print_sets:\n print(\"Probabilistic State Constraint values along Horizon:\")\n print(state_constraint_set)\n print(\"Probabilistic Input Constraint values along Horizon:\")\n print(input_constraint_set)\n self.results_dict['input_constraint_set'].append(input_constraint_set)\n self.results_dict['state_constraint_set'].append(state_constraint_set)\n self.results_dict['state_horizon_cov'].append(state_covariances)\n self.results_dict['input_horizon_cov'].append(input_covariances)\n return state_constraint_set, input_constraint_set\n\n def precompute_sparse_gp_values(self):\n \"\"\"Uses the last MPC solution to precomupte values associated with the FITC GP approximation.\n\n \"\"\"\n n_data_points = self.gaussian_process.n_training_samples\n dim_gp_inputs = len(self.input_mask)\n dim_gp_outputs = len(self.target_mask)\n inputs = self.train_data['train_inputs']\n targets = self.train_data['train_targets']\n # Get the inducing points.\n if self.x_prev is not None and self.u_prev is not None:\n # Use the previous MPC solution as in Hewing 2019.\n z_ind = np.hstack((self.x_prev[:,:-1].T, self.u_prev.T))\n z_ind = z_ind[:,self.input_mask]\n else:\n # If there is no previous solution. Choose T random training set points.\n inds = self.env.np_random.choice(range(n_data_points), size=self.T)\n #z_ind = self.data_inputs[inds][:, self.input_mask]\n z_ind = inputs[inds][:, self.input_mask]\n K_zind_zind = self.gaussian_process.kernel(torch.Tensor(z_ind).double())\n K_zind_zind_inv = self.gaussian_process.kernel_inv(torch.Tensor(z_ind).double())\n K_x_zind = self.gaussian_process.kernel(torch.from_numpy(inputs[:, self.input_mask]).double(),\n torch.Tensor(z_ind).double())\n Q_X_X = K_x_zind @ K_zind_zind_inv @ K_x_zind.transpose(1,2)\n Gamma = torch.diagonal(self.gaussian_process.K_plus_noise + Q_X_X, 0, 1, 2)\n Gamma_inv = torch.diag_embed(1/Gamma)\n Sigma = torch.pinverse(K_zind_zind + K_x_zind.transpose(1,2) @ Gamma_inv @ K_x_zind)\n mean_post_factor = torch.zeros((dim_gp_outputs, self.T))\n for i in range(dim_gp_outputs):\n mean_post_factor[i] = Sigma[i] @ K_x_zind[i].T @ Gamma_inv[i] @ \\\n torch.from_numpy(targets[:,self.target_mask[i]]).double()\n return mean_post_factor.detach().numpy(), Sigma.detach().numpy(), K_zind_zind_inv.detach().numpy(), z_ind\n\n def setup_gp_optimizer(self):\n \"\"\"Sets up nonlinear optimization problem including cost objective, variable bounds and dynamics constraints.\n\n \"\"\"\n nx, nu = self.model.nx, self.model.nu\n T = self.T\n # Define optimizer and variables.\n opti = cs.Opti()\n # States.\n x_var = opti.variable(nx, T + 1)\n # Inputs.\n u_var = opti.variable(nu, T)\n # Initial state.\n x_init = opti.parameter(nx, 1)\n # Reference (equilibrium point or trajectory, last step for terminal cost).\n x_ref = opti.parameter(nx, T + 1)\n # Chance constraint limits.\n state_constraint_set = []\n for state_constraint in self.constraints.state_constraints:\n state_constraint_set.append(opti.parameter(state_constraint.num_constraints, T+1))\n input_constraint_set = []\n for input_constraint in self.constraints.input_constraints:\n input_constraint_set.append(opti.parameter(input_constraint.num_constraints, T))\n # Sparse GP mean postfactor matrix.\n mean_post_factor = opti.parameter(len(self.target_mask), T)\n # Sparse GP inducing points.\n z_ind = opti.parameter(T, len(self.input_mask))\n # Cost (cumulative).\n cost = 0\n cost_func = self.model.loss\n for i in range(T):\n cost += cost_func(x=x_var[:, i],\n u=u_var[:, i],\n Xr=x_ref[:, i],\n Ur=np.zeros((nu, 1)),\n Q=self.Q,\n R=self.R)[\"l\"]\n # Terminal cost.\n cost += cost_func(x=x_var[:, -1],\n u=np.zeros((nu, 1)),\n Xr=x_ref[:, -1],\n Ur=np.zeros((nu, 1)),\n Q=self.Q,\n R=self.R)[\"l\"]\n opti.minimize(cost)\n z = cs.vertcat(x_var[:,:-1], u_var)\n z = z[self.input_mask,:]\n for i in range(self.T):\n # Dynamics constraints using the dynamics of the prior and the mean of the GP.\n # This follows the tractable dynamics formulation in Section III.B in Hewing 2019.\n # Note that for the GP approximation, we are purposely using elementwise multiplication *.\n if self.sparse_gp:\n next_state = self.prior_dynamics_func(x0=x_var[:, i]-self.prior_ctrl.X_LIN[:,None],\n p=u_var[:, i]-self.prior_ctrl.U_LIN[:,None])['xf'] + \\\n self.prior_ctrl.X_LIN[:,None]+ self.Bd @ cs.sum2(self.K_z_zind_func(z1=z[:,i].T, z2=z_ind)['K'] * mean_post_factor)\n else:\n # Sparse GP approximation doesn't always work well, thus, use Exact GP regression. This is much slower,\n # but for unstable systems, make performance much better.\n next_state = self.prior_dynamics_func(x0=x_var[:, i]-self.prior_ctrl.X_LIN[:,None],\n p=u_var[:, i]-self.prior_ctrl.U_LIN[:,None])['xf'] + \\\n self.prior_ctrl.X_LIN[:,None]+ self.Bd @ self.gaussian_process.casadi_predict(z=z[:,i])['mean']\n opti.subject_to(x_var[:, i + 1] == next_state)\n # Probabilistic state and input constraints according to Hewing 2019 constraint tightening.\n for s_i, state_constraint in enumerate(self.state_constraints_sym):\n opti.subject_to(state_constraint(x_var[:, i]) <= state_constraint_set[s_i][:,i])\n for u_i, input_constraint in enumerate(self.input_constraints_sym):\n opti.subject_to(input_constraint(u_var[:, i]) <= input_constraint_set[u_i][:,i])\n # Final state constraints.\n for s_i, state_constraint in enumerate(self.state_constraints_sym):\n opti.subject_to(state_constraint(x_var[:, -1]) <= state_constraint_set[s_i][:,-1])\n # Initial condition constraints.\n opti.subject_to(x_var[:, 0] == x_init)\n # Create solver (IPOPT solver in this version).\n opts = {\"ipopt.print_level\": 4,\n \"ipopt.sb\": \"yes\",\n \"ipopt.max_iter\": 100, #100,\n \"print_time\": 1}\n opti.solver('ipopt', opts)\n self.opti_dict = {\n \"opti\": opti,\n \"x_var\": x_var,\n \"u_var\": u_var,\n \"x_init\": x_init,\n \"x_ref\": x_ref,\n \"state_constraint_set\": state_constraint_set,\n \"input_constraint_set\": input_constraint_set,\n \"mean_post_factor\": mean_post_factor,\n \"z_ind\": z_ind,\n \"cost\": cost\n }\n\n def select_action_with_gp(self,\n obs\n ):\n \"\"\"Solves nonlinear MPC problem to get next action.\n\n Args:\n obs (np.array): current state/observation.\n\n Returns:\n np.array: input/action to the task/env.\n\n \"\"\"\n opti_dict = self.opti_dict\n opti = opti_dict[\"opti\"]\n x_var = opti_dict[\"x_var\"]\n u_var = opti_dict[\"u_var\"]\n x_init = opti_dict[\"x_init\"]\n x_ref = opti_dict[\"x_ref\"]\n state_constraint_set = opti_dict[\"state_constraint_set\"]\n input_constraint_set = opti_dict[\"input_constraint_set\"]\n mean_post_factor = opti_dict[\"mean_post_factor\"]\n z_ind = opti_dict[\"z_ind\"]\n cost = opti_dict[\"cost\"]\n # Assign the initial state.\n opti.set_value(x_init, obs)\n # Assign reference trajectory within horizon.\n goal_states = self.get_references()\n opti.set_value(x_ref, goal_states)\n if self.mode == \"tracking\":\n self.traj_step += 1\n # Set the probabilistic state and input constraint set limits.\n state_constraint_set_prev, input_constraint_set_prev = self.precompute_probabilistic_limits()\n for si in range(len(self.constraints.state_constraints)):\n opti.set_value(state_constraint_set[si], state_constraint_set_prev[si])\n for ui in range(len(self.constraints.input_constraints)):\n opti.set_value(input_constraint_set[ui], input_constraint_set_prev[ui])\n mean_post_factor_val, Sigma, K_zind_zind_inv, z_ind_val = self.precompute_sparse_gp_values()\n opti.set_value(mean_post_factor, mean_post_factor_val)\n opti.set_value(z_ind, z_ind_val)\n # Initial guess for the optimization problem.\n if self.warmstart and self.x_prev is not None and self.u_prev is not None:\n # shift previous solutions by 1 step\n x_guess = deepcopy(self.x_prev)\n u_guess = deepcopy(self.u_prev)\n x_guess[:, :-1] = x_guess[:, 1:]\n u_guess[:-1] = u_guess[1:]\n opti.set_initial(x_var, x_guess)\n opti.set_initial(u_var, u_guess)\n # Solve the optimization problem.\n try:\n sol = opti.solve()\n x_val, u_val = sol.value(x_var), sol.value(u_var)\n except RuntimeError:\n x_val, u_val = opti.debug.value(x_var), opti.debug.value(u_var)\n u_val = np.atleast_2d(u_val)\n self.x_prev = x_val\n self.u_prev = u_val\n self.results_dict['horizon_states'].append(deepcopy(self.x_prev))\n self.results_dict['horizon_inputs'].append(deepcopy(self.u_prev))\n zi = np.hstack((x_val[:,0], u_val[:,0]))\n zi = zi[self.input_mask]\n gp_contribution = np.sum(self.K_z_zind_func(z1=zi, z2=z_ind_val)['K'].toarray() * mean_post_factor_val,axis=1)\n print(\"GP Mean eq Contribution: %s\" % gp_contribution)\n zi = np.hstack((x_val[:,0], u_val[:,0]))\n pred, _, _ = self.gaussian_process.predict(zi[None,:])\n print(\"True GP value: %s\" % pred.numpy())\n lin_pred = self.prior_dynamics_func(x0=x_val[:,0]-self.prior_ctrl.X_LIN,\n p=u_val[:, 0]-self.prior_ctrl.U_LIN)['xf'].toarray() + \\\n self.prior_ctrl.X_LIN[:,None]\n self.results_dict['linear_pred'].append(lin_pred)\n self.results_dict['gp_mean_eq_pred'].append(gp_contribution)\n self.results_dict['gp_pred'].append(pred.numpy())\n # Take the first one from solved action sequence.\n if u_val.ndim > 1:\n action = u_val[:, 0]\n else:\n action = np.array([u_val[0]])\n self.prev_action = action,\n return action\n\n def learn(self,\n input_data=None,\n target_data=None,\n gp_model=None,\n plot=False\n ):\n \"\"\"Performs GP training.\n\n Args:\n input_data, target_data (optiona, np.array): data to use for training\n gp_model (str): if not None, this is the path to pretrained models to use instead of training new ones.\n plot (bool): to plot validation trajectories or not.\n\n Returns:\n training_results (dict): Dictionary of the training results.\n\n \"\"\"\n if gp_model is None:\n gp_model = self.gp_model_path\n self.prior_ctrl.remove_constraints(self.prior_ctrl.additional_constraints)\n self.reset()\n if self.online_learning:\n input_data = np.zeros((self.train_iterations, len(self.input_mask)))\n target_data = np.zeros((self.train_iterations, len(self.target_mask)))\n if input_data is None and target_data is None:\n train_inputs = []\n train_targets = []\n train_info = []\n\n ############\n # Use Latin Hypercube Sampling to generate states withing environment bounds.\n lhs_sampler = Lhs(lhs_type='classic', criterion='maximin')\n limits = [(self.env.INIT_STATE_RAND_INFO[key].low, self.env.INIT_STATE_RAND_INFO[key].high) for key in\n self.env.INIT_STATE_RAND_INFO]\n # todo: parameterize this if we actually want it.\n num_eq_samples = 0\n samples = lhs_sampler.generate(limits,\n self.train_iterations + self.validation_iterations - num_eq_samples,\n random_state=self.seed)\n # todo: choose if we want eq samples or not.\n delta = 0.01\n eq_limits = [(self.prior_ctrl.X_LIN[eq]-delta, self.prior_ctrl.X_LIN[eq]+delta) for eq in range(self.model.nx)]\n if num_eq_samples > 0:\n eq_samples = lhs_sampler.generate(eq_limits, num_eq_samples, random_state=self.seed)\n #samples = samples.append(eq_samples)\n init_state_samples = np.array(samples + eq_samples)\n else:\n init_state_samples = np.array(samples)\n input_limits = np.vstack((self.constraints.input_constraints[0].lower_bounds,\n self.constraints.input_constraints[0].upper_bounds)).T\n input_samples = lhs_sampler.generate(input_limits,\n self.train_iterations + self.validation_iterations,\n random_state=self.seed)\n input_samples = np.array(input_samples) # not being used currently\n seeds = self.env.np_random.randint(0,99999, size=self.train_iterations + self.validation_iterations)\n\n load_from_file = False\n if load_from_file:\n gpmpc_data = np.load(\"/home/erl/repos/journal_zhichao/safe-control-gym/experiments/annual_reviews/figure6/data/small_drone/statecontroldata_rand_good1.npz\")\n x_seq_all = gpmpc_data[\"x_seq_all\"]\n x_next_seq_all = gpmpc_data[\"x_next_seq_all\"]\n u_seq_all = gpmpc_data[\"u_seq_all\"]\n else:\n x_seq_all = []\n u_seq_all = []\n x_next_seq_all = []\n for i in range(self.train_iterations + self.validation_iterations):\n if load_from_file:\n x_seq = x_seq_all[i]\n x_next_seq = x_next_seq_all[i]\n u_seq = u_seq_all[i]\n else:\n # For random initial state training.\n init_state = init_state_samples[i,:]\n # Collect data with prior controller.\n run_env = self.env_func(init_state=init_state, randomized_init=False, seed=int(seeds[i]))\n episode_results = self.prior_ctrl.run(env=run_env, max_steps=1, gp_training = True)\n run_env.close()\n x_obs = episode_results['obs'][-3:,:]\n u_seq = episode_results['action'][-1:,:]\n run_env.close()\n x_seq = x_obs[:-1,:]\n x_next_seq = x_obs[1:,:]\n x_seq_all.append(x_seq)\n x_next_seq_all.append(x_next_seq)\n u_seq_all.append(u_seq)\n train_inputs_i, train_targets_i = self.preprocess_training_data(x_seq, u_seq, x_next_seq)\n train_inputs.append(train_inputs_i)\n train_targets.append(train_targets_i)\n np.savez(\"/home/erl/repos/journal_zhichao/safe-control-gym/experiments/annual_reviews/figure6/data/small_drone/statecontroldata_rand.npz\", x_seq_all = x_seq_all, x_next_seq_all = x_next_seq_all, u_seq_all = u_seq_all)\n ###########\n else:\n train_inputs = input_data\n train_targets = target_data\n # assign all data\n train_inputs = np.vstack(train_inputs)\n train_targets = np.vstack(train_targets)\n self.data_inputs = train_inputs\n self.data_targets = train_targets\n train_idx, test_idx = train_test_split(\n #list(range(self.train_iterations + self.validation_iterations)),\n list(range(train_inputs.shape[0])),\n test_size=self.validation_iterations/(self.train_iterations+self.validation_iterations),\n random_state=self.seed\n )\n train_inputs = self.data_inputs[train_idx, :]\n train_targets = self.data_targets[train_idx, :]\n self.train_data = {'train_inputs': train_inputs, 'train_targets': train_targets}\n test_inputs = self.data_inputs[test_idx, :]\n test_targets = self.data_targets[test_idx, :]\n self.test_data = {'test_inputs': test_inputs, 'test_targets': test_targets}\n\n\n train_inputs_tensor = torch.Tensor(train_inputs).double()\n train_targets_tensor = torch.Tensor(train_targets).double()\n test_inputs_tensor = torch.Tensor(test_inputs).double()\n test_targets_tensor = torch.Tensor(test_targets).double()\n\n if plot:\n init_state = np.array([-1.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n valid_env = self.env_func(init_state=init_state,\n randomized_init=False)\n validation_results = self.prior_ctrl.run(env=valid_env,\n max_steps=40)\n valid_env.close()\n x_obs = validation_results['obs']\n u_seq = validation_results['action']\n x_seq = x_obs[:-1, :]\n x_next_seq = x_obs[1:, :]\n # Define likelihood.\n likelihood = gpytorch.likelihoods.GaussianLikelihood(\n noise_constraint=gpytorch.constraints.GreaterThan(1e-6),\n ).double()\n self.gaussian_process = GaussianProcessCollection(ZeroMeanIndependentGPModel,\n likelihood,\n len(self.target_mask),\n input_mask=self.input_mask,\n target_mask=self.target_mask,\n normalize=self.normalize_training_data\n )\n if gp_model:\n self.gaussian_process.init_with_hyperparam(train_inputs_tensor,\n train_targets_tensor,\n gp_model)\n else:\n # Train the GP.\n self.gaussian_process.train(train_inputs_tensor,\n train_targets_tensor,\n test_inputs_tensor,\n test_targets_tensor,\n n_train=self.optimization_iterations,\n learning_rate=self.learning_rate,\n gpu=self.use_gpu,\n dir=self.output_dir)\n # Plot validation.\n if plot:\n validation_inputs, validation_targets = self.preprocess_training_data(x_seq, u_seq, x_next_seq)\n fig_count = 0\n fig_count = self.gaussian_process.plot_trained_gp(torch.Tensor(validation_inputs).double(),\n torch.Tensor(validation_targets).double(),\n fig_count=fig_count)\n self.set_gp_dynamics_func()\n self.setup_gp_optimizer()\n self.prior_ctrl.add_constraints(self.prior_ctrl.additional_constraints)\n self.prior_ctrl.reset()\n # Collect training results.\n training_results = {}\n training_results['train_targets'] = train_targets\n training_results['train_inputs'] = train_inputs\n try:\n training_results['info'] = train_info\n except UnboundLocalError:\n training_results['info'] = None\n return training_results\n\n def select_action(self,\n obs\n ):\n \"\"\"Select the action based on the given observation.\n\n Args:\n obs (np.array): current observed state.\n\n Returns:\n action (np.array): desired policy action.\n\n \"\"\"\n if self.gaussian_process is None:\n action = self.prior_ctrl.select_action(obs)\n else:\n if(self.last_obs is not None and self.last_action is not None and self.online_learning):\n print(\"[ERROR]: Not yet supported.\")\n exit()\n t1 = time.perf_counter()\n action = self.select_action_with_gp(obs)\n t2 = time.perf_counter()\n print(\"GP SELECT ACTION TIME: %s\" %(t2 - t1))\n self.last_obs = obs\n self.last_action = action\n return action\n\n def close(self):\n \"\"\"Clean up.\n\n \"\"\"\n self.env_training.close()\n self.env.close()\n\n def reset_results_dict(self):\n \"\"\"\n\n \"\"\"\n \"Result the results_dict before running.\"\n super().reset_results_dict()\n self.results_dict['input_constraint_set'] = []\n self.results_dict['state_constraint_set'] = []\n self.results_dict['state_horizon_cov'] = []\n self.results_dict['input_horizon_cov'] = []\n self.results_dict['gp_mean_eq_pred'] = []\n self.results_dict['gp_pred'] = []\n self.results_dict['linear_pred'] = []\n\n def reset(self):\n \"\"\"Reset the controller before running.\n\n \"\"\"\n # Setup reference input.\n if self.env.TASK == Task.STABILIZATION:\n self.mode = \"stabilization\"\n self.x_goal = self.env.X_GOAL\n elif self.env.TASK == Task.TRAJ_TRACKING:\n self.mode = \"tracking\"\n self.traj = self.env.X_GOAL.T\n self.traj_step = 0\n # Dynamics model.\n if self.gaussian_process is not None:\n self.set_gp_dynamics_func()\n # CasADi optimizer.\n self.setup_gp_optimizer()\n self.prior_ctrl.reset()\n # Previously solved states & inputs, useful for warm start.\n self.x_prev = None\n self.u_prev = None\n" ]
[ [ "numpy.diag", "numpy.dot", "scipy.stats.norm.ppf", "numpy.savez", "torch.zeros", "torch.diag_embed", "numpy.hstack", "numpy.arange", "numpy.eye", "torch.from_numpy", "numpy.load", "scipy.linalg.solve_discrete_are", "numpy.zeros", "numpy.atleast_2d", "numpy.array", "torch.diagonal", "numpy.absolute", "torch.Tensor", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
PouyaREZ/Wastewater_Energy_Optimization
[ "ead604b715337dc8c76871910d38965d1b8b1856" ]
[ "Plotters/Results/Plots_Paper_One.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 4 2020\n\n\n@Author: PouyaRZ\n\n____________________________________________________\nPlots to produce:\n1. LCC of equipment for each scenario for all the individuals\n2, SCC of equipment for each scenario for all the individuals\n\n3. SCC vs LCC scatter plot.\n\n4. SCC vs chiller type\n5. SCC vs CHP type,\n6. LCC vs chiller type\n7. SCC vs CHP type\n\n8. Traces of building types across all the runs\n____________________________________________________\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef DF_Filter(filename):\n \n file = np.loadtxt(filename, dtype='float')\n \n inputDF = pd.DataFrame(file)\n \n error_tol = 1.15\n \n# print('GFA stats:')\n# print(inputDF.iloc[:,38].describe())\n print('+++++ processing %s +++++\\n'%(filename))\n \n print('Count duplicates:')\n condition1 = inputDF.duplicated()==True\n print(inputDF[condition1][38].count())\n \n \n print('Count under the min GFA:') # Count non-trivial neighborhoods\n condition2 = inputDF[38] <= 1/error_tol#<=647497/10\n print(inputDF[condition2][38].count())\n \n \n print('Count over the max GFA:')\n condition3 = inputDF[38]>=647497*5*error_tol\n print(inputDF[condition3][38].count())\n \n \n print('Count over the max Site GFA:')\n condition4 = inputDF[38]/inputDF[36]>=647497*error_tol\n print(inputDF[condition4][38].count())\n \n \n print('Count valid answers:')\n print(len(inputDF) - inputDF[condition1 | condition2 | condition3 | condition4][38].count())\n \n# print('------------------')\n # Filtering the inadmissible results\n Filtered = ~(condition1 | condition2 | condition3 | condition4)\n inputDF = inputDF[Filtered]\n inputDF.reset_index(inplace=True, drop=True)\n \n# print('Annual energy demand stats (MWh):')\n inputDF[26] /= inputDF[38] # Normalizing LCC ($/m2)\n inputDF[27] /= inputDF[38] # Normalizing SCC ($/m2)\n inputDF[39] /= inputDF[38] # Normalizing CO2 (Tonnes/m2)\n inputDF[40] /= (10**3*inputDF[38]) # Normalizing total energy demand (MWh/m2)\n inputDF[41] /= inputDF[38] # Normalizing total wwater treatment demand (L/m2)\n for i in range(29,36): # Converting percent areas to integer %\n inputDF[i] = inputDF[i] * 100\n# print(inputDF[40].describe())\n \n return inputDF\n \n\n\n### MAIN FUNCTION\nprint('loading data')\nfilenames = ['../RQ1_W_CWWTP_ModConsts_Feb17/SDO_LHS_TestRuns288_Constraint_SF_Test.txt',\n '../RQ1_WO_CWWTP_ModConsts_Feb17/SDO_LHS_TestRuns288_Constraint_SF_Test.txt']\nDFNames = ['CCHP|CWWTP','CCHP+WWT']\nDFs = {}\nfor i in range(2):\n DFs[DFNames[i]] = DF_Filter(filenames[i])\n\n\n\n\nplt.style.use('ggplot')\ncolors_rb = {DFNames[0]:'r', DFNames[1]:'b'}\n\n\n\n\n\n\n\n\n# =============================================================================\n## CHP/Chiller/Solar Types used in the individual neighborhood\nCHP_Types = {}\nCHP_Types[1] = 'Gas_1'\nCHP_Types[2] = 'Gas_2'\nCHP_Types[3] = 'Gas_3'\nCHP_Types[4] = 'Gas_4'\nCHP_Types[5] = 'Gas_5'\nCHP_Types[6] = 'Micro_1'\nCHP_Types[7] = 'Micro_2'\nCHP_Types[8] = 'Micro_3'\nCHP_Types[9] = 'Recipro_1'\nCHP_Types[10] = 'Recipro_2'\nCHP_Types[11] = 'Recipro_3'\nCHP_Types[12] = 'Recipro_4'\nCHP_Types[13] = 'Recipro_5'\nCHP_Types[14] = 'Steam_1'\nCHP_Types[15] = 'Steam_2'\nCHP_Types[16] = 'Steam_3'\nCHP_Types[17] = 'Fuel_Cell_1'\nCHP_Types[18] = 'Fuel_Cell_2'\nCHP_Types[19] = 'Fuel_Cell_3'\nCHP_Types[20] = 'Fuel_Cell_4'\nCHP_Types[21] = 'Fuel_Cell_5'\nCHP_Types[22] = 'Fuel_Cell_6'\nCHP_Types[23] = 'Bio_1'\nCHP_Types[24] = 'Bio_2'\nCHP_Types[25] = 'Bio_3'\nCHP_Types[26] = 'Bio_4'\nCHP_Types[27] = 'Bio_5'\nCHP_Types[28] = 'Bio_6'\nCHP_Types[29] = 'Bio_7'\nCHP_Types[30] = 'Bio_8'\nCHP_Types[31] = 'Bio_9'\nCHP_Types[32] = 'Bio_10'\n\n\nChiller_Types = {}\nChiller_Types[1] = 'Electric_1'\nChiller_Types[2] = 'Electric_2'\nChiller_Types[3] = 'Electric_3'\nChiller_Types[4] = 'Electric_4'\nChiller_Types[5] = 'Electric_5'\nChiller_Types[6] = 'Electric_6'\nChiller_Types[7] = 'Electric_7'\nChiller_Types[8] = 'Electric_8'\nChiller_Types[9] = 'Electric_9'\nChiller_Types[10] = 'Absorp_1'\nChiller_Types[11] = 'Absorp_2'\nChiller_Types[12] = 'Absorp_3'\nChiller_Types[13] = 'Absorp_4'\nChiller_Types[14] = 'Absorp_5'\nChiller_Types[15] = 'Absorp_6'\nChiller_Types[16] = 'Absorp_7'\nChiller_Types[17] = 'Absorp_8'\n\n\nWWT_Types = {}\nWWT_Types[1] = \"FO_MD\"\nWWT_Types[2] = \"FO_RO\"\nWWT_Types[3] = \"CWWTP\"\n\n\n\n## CHP, Chiller and WWT name assignments\n# CHP = {}\n# Chiller = {}\n# WWT = {}\nfor DFName in DFNames:\n # CHP[DFName] = np.array([CHP_Types[int(i)] for i in DFs[DFName][21]]) # Making strings of CHP names instead of integers\n DFs[DFName][21] = np.array([CHP_Types[int(i)] for i in DFs[DFName][21]]) # Making strings of CHP names instead of integers\n # Chiller[DFName] = np.array([Chiller_Types[int(i)] for i in DFs[DFName][22]]) # Making strings of Chiller names instead of integers\n DFs[DFName][22] = np.array([Chiller_Types[int(i)] for i in DFs[DFName][22]]) # Making strings of Chiller names instead of integers\n # WWT[DFName] = np.array([WWT_Types[int(i)] for i in DFs[DFName][24]]) # Making strings of WWT module names instead of integers\n DFs[DFName][24] = np.array([WWT_Types[int(i)] for i in DFs[DFName][24]]) # Making strings of WWT module names instead of integers\n\n\n# =============================================================================\n\n\n\n\n\n######################## PLOTS ##########################\n\n#############################################\nprint('plotting overall LCC and SCC graphs')\n# LCC\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=26, ascending=True).reset_index(drop=True)\n plt.scatter(x=sortedDF.index,y=(sortedDF[26]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel('Rank')\nplt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.title('LCC')\nplt.legend()\nplt.savefig('LCC_Ascending.png', dpi=400, bbox_inches='tight')\n\n\n\n# SCC\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=27, ascending=True).reset_index(drop=True)\n plt.scatter(x=sortedDF.index,y=(sortedDF[27]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel('Rank')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\n# plt.title('SCC')\nplt.legend()\nplt.savefig('SCC_Ascending.png', dpi=400, bbox_inches='tight')\n\nplt.close('all')\n\n\n\n#############################################\nprint('plotting LCC and SCC box plots')\n\nprint('\\n#############################################')\nprint('Stats of LCC ($/m2) for Disintegrated Case:\\n',(DFs[DFNames[0]][26]).describe())\nprint('Stats of LCC ($/m2) for Integrated Case:\\n',(DFs[DFNames[1]][26]).describe())\nprint('Stats of SCC ($/m2) for Disintegrated Case:\\n',(DFs[DFNames[0]][27]).describe())\nprint('Stats of SCC ($/m2) for Integrated Case:\\n',(DFs[DFNames[1]][27]).describe())\nprint('#############################################\\n')\n\n# =============================================================================\n# # LCC\n# plt.figure(figsize=(10,5))\n# # for DFName in DFNames:\n# plt.boxplot(x=[(DFs[DFNames[0]][26]/10**3), (DFs[DFNames[1]][26]/10**3)])\n# # (DFs[DFName][0][26]/10**6).plot(label=DFName)\n# # plt.xlabel('Rank')\n# plt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.xticks([1,2],[DFNames[0],DFNames[1]])\n# # plt.title('LCC')\n# plt.savefig('LCC_Boxplot.png', dpi=400, bbox_inches='tight')\n# \n# \n# \n# # SCC\n# plt.figure(figsize=(10,5))\n# # for DFName in DFNames:\n# plt.boxplot(x=[(DFs[DFNames[0]][27]/10**3), (DFs[DFNames[1]][27]/10**3)])\n# # (DFs[DFName][0][26]/10**6).plot(label=DFName)\n# # plt.xlabel('Rank')\n# plt.ylabel(r'SCC (k\\$/$m^2$)')\n# plt.xticks([1,2],[DFNames[0],DFNames[1]])\n# # plt.title('LCC')\n# plt.savefig('SCC_Boxplot.png', dpi=400, bbox_inches='tight')\n# \n# plt.close('all')\n# =============================================================================\n\n\n'''\n#############################################\nprint('plotting LCC/SCC vs total neighborhood energy and ww graphs')\n\nprint('\\n#############################################')\nprint('Stats of Total Energy Demand (MWh/m2) for Disintegrated Case:\\n',(DFs[DFNames[0]][40]).describe())\nprint('Stats of Total Energy Demand (MWh/m2) for Integrated Case:\\n',(DFs[DFNames[1]][40]).describe())\nprint('Stats of Total Wastewater Treatment Demand (m3/m2) for Disintegrated Case:\\n',(DFs[DFNames[0]][41]/10**3).describe())\nprint('Stats of Total Wastewater Treatment Demand (m3/m2) for Integrated Case:\\n',(DFs[DFNames[1]][41]/10**3).describe())\nprint('#############################################\\n')\n\n# LCC vs Neighborhood's Total Energy Use\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\n plt.scatter(x=(sortedDF[40]),y=(sortedDF[26]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.title('LCC')\nplt.legend()\nplt.savefig('LCC_vs_Energy_Demand.png', dpi=400, bbox_inches='tight')\n\n\n# LCC vs Neighborhood's Total WWater Demand\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\n plt.scatter(x=(sortedDF[41]/10**3),y=(sortedDF[26]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.title('LCC')\nplt.legend()\nplt.savefig('LCC_vs_WWater_Demand.png', dpi=400, bbox_inches='tight')\n\n\n\n# SCC vs Neighborhood's Total Energy Use\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\n plt.scatter(x=(sortedDF[40]),y=(sortedDF[27]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\n# plt.title('LCC')\nplt.legend()\nplt.savefig('SCC_vs_Energy_Demand.png', dpi=400, bbox_inches='tight')\n\n\n# SCC vs Neighborhood's Total WWater Demand\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\n plt.scatter(x=(sortedDF[41]/10**3),y=(sortedDF[27]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\n# plt.title('LCC')\nplt.legend()\nplt.savefig('SCC_vs_WWater_Demand.png', dpi=400, bbox_inches='tight')\n\nplt.close('all')\n\n#############################################\n\nprint('plotting building mix vs neighborhood energy and ww graphs')\n\n# Building Mix vs Neighborhood's Total WWater Demand (integrated)\nDFName = 'CCHP+WWT'\nbldg_types = ['Res','Off','Com','Ind','Hos','Med','Edu']\ncolors = ['m','b','c','g','y','orange','r']\ncolumns = list(range(29,36))\nplt.figure(figsize=(10,5))\nsortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\nfor i in range(len(bldg_types)):\n plt.scatter(x=(sortedDF[41]/10**3),y=DFs[DFName].iloc[:,columns[i]],\n s=0.5, label=bldg_types[i], c=colors[i], alpha=0.5)\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.ylabel('Percent of Total GFA (%)')\nplt.ylim(0, 100)\nplt.xlim(0,11)\n# plt.title('LCC')\nplt.legend()\nplt.savefig('Bldg_Mix_vs_WWater_Demand_Integ.png', dpi=400, bbox_inches='tight')\n\n\n\n# Building Mix vs Neighborhood's Total WWater Demand (Disintegrated)\nDFName = 'CCHP|CWWTP'\nbldg_types = ['Res','Off','Com','Ind','Hos','Med','Edu']\ncolors = ['m','b','c','g','y','orange','r']\ncolumns = list(range(29,36))\nplt.figure(figsize=(10,5))\nsortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\nfor i in range(len(bldg_types)):\n plt.scatter(x=(sortedDF[41]/10**3),y=DFs[DFName].iloc[:,columns[i]],\n s=0.5, label=bldg_types[i], c=colors[i], alpha=0.5)\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.ylabel('Percent of Total GFA (%)')\n# plt.title('LCC')\nplt.ylim(0, 100)\nplt.xlim(0,11)\nplt.legend()\nplt.savefig('Bldg_Mix_vs_WWater_Demand_Disinteg.png', dpi=400, bbox_inches='tight')\n\n\n\n\n# Building Mix vs Neighborhood's Total Energy Demand (integrated)\nDFName = 'CCHP+WWT'\nbldg_types = ['Res','Off','Com','Ind','Hos','Med','Edu']\ncolors = ['m','b','c','g','y','orange','r']\ncolumns = list(range(29,36))\nplt.figure(figsize=(10,5))\nsortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\nfor i in range(len(bldg_types)):\n plt.scatter(x=(sortedDF[40]),y=DFs[DFName].iloc[:,columns[i]],\n s=0.5, label=bldg_types[i], c=colors[i], alpha=0.5)\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.ylabel('Percent of Total GFA (%)')\n# plt.title('LCC')\nplt.ylim(0, 100)\nplt.xlim(0,1)\nplt.legend()\nplt.savefig('Bldg_Mix_vs_Energy_Demand_Integ.png', dpi=400, bbox_inches='tight')\n\n\n\n# Building Mix vs Neighborhood's Total Energy Demand (Disintegrated)\nDFName = 'CCHP|CWWTP'\nbldg_types = ['Res','Off','Com','Ind','Hos','Med','Edu']\ncolors = ['m','b','c','g','y','orange','r']\ncolumns = list(range(29,36))\nplt.figure(figsize=(10,5))\nsortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\nfor i in range(len(bldg_types)):\n plt.scatter(x=(sortedDF[40]),y=DFs[DFName].iloc[:,columns[i]],\n s=0.5, label=bldg_types[i], c=colors[i], alpha=0.5)\n# (DFs[DFName][0][26]/10**6).plot(label=DFName)\nplt.xlabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.ylabel('Percent of Total GFA (%)')\n# plt.title('LCC')\nplt.ylim(0, 100)\nplt.xlim(0,1)\nplt.legend()\nplt.savefig('Bldg_Mix_vs_Energy_Demand_Disinteg.png', dpi=400, bbox_inches='tight')\n\nplt.close('all')\n\n#############################################\nprint('plotting Supply type vs total neighborhood energy and ww graphs')\n\n# Total Energy Demand vs CHP\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\n plt.scatter(x=DFs[DFName][21],y=(sortedDF[40]),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'CHP Type')\nplt.ylabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.legend()\nplt.savefig('Total_Energy_vs_CHP.png', dpi=400, bbox_inches='tight')\n\n\n# Total WWater Demand vs CHP\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\n plt.scatter(x=DFs[DFName][21],y=(sortedDF[41]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'CHP Type')\nplt.ylabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.legend()\nplt.savefig('Total_WWater_vs_CHP.png', dpi=400, bbox_inches='tight')\n\n\n# Total Energy Demand vs Chiller\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\n plt.scatter(x=DFs[DFName][22],y=(sortedDF[40]),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'Chiller Type')\nplt.ylabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.legend()\nplt.savefig('Total_Energy_vs_Chiller.png', dpi=400, bbox_inches='tight')\n\n\n# Total WWater Demand vs Chiller\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n sortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\n plt.scatter(x=DFs[DFName][22],y=(sortedDF[41]/10**3),label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'Chiller Type')\nplt.ylabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.legend()\nplt.savefig('Total_WWater_vs_Chiller.png', dpi=400, bbox_inches='tight')\n\n\n# Total Energy Demand vs WWT (integrated)\nplt.figure(figsize=(10,5))\nDFName = 'CCHP+WWT'\nsortedDF = DFs[DFName].sort_values(by=40, ascending=True).reset_index(drop=True)\nplt.scatter(x=DFs[DFName][24],y=(sortedDF[40]),s=2, c=colors_rb[DFName])\nplt.xlabel(r'WWT Type')\nplt.ylabel(r'Total Energy Demand (MWh/$m^2$)')\nplt.legend()\nplt.savefig('Total_Energy_vs_WWT_Integ.png', dpi=400, bbox_inches='tight')\n\n\n# Total WWater Demand vs WWT (integrated)\nplt.figure(figsize=(10,5))\nDFName = 'CCHP+WWT'\nsortedDF = DFs[DFName].sort_values(by=41, ascending=True).reset_index(drop=True)\nplt.scatter(x=DFs[DFName][24],y=(sortedDF[41]/10**3), s=2, c=colors_rb[DFName])\nplt.xlabel(r'WWT Type')\nplt.ylabel(r'Total Wastewater Treatment Demand ($m^3$/$m^2$)')\nplt.savefig('Total_Wwater_vs_WWT_Integ.png', dpi=400, bbox_inches='tight')\n'''\nplt.close('all')\n\n#############################################\nprint('plotting pareto fronts')\n\n# LCC vs CO2\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n plt.scatter(x=DFs[DFName][26]/10**3,y=DFs[DFName][39],label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'LCC (k\\$/$m^2$)')\nplt.ylabel(r'Lifecycle $CO_{2e}$ (T/$m^2$)')\nplt.legend()\nplt.savefig('CO2_vs_LCC.png', dpi=400, bbox_inches='tight')\n\n\n\n\n#############################################\n\n# LCC vs SCC\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n plt.scatter(x=DFs[DFName][26]/10**3,y=DFs[DFName][27]/10**3,label=DFName, s=2, alpha=0.5, c=colors_rb[DFName])\nplt.xlabel(r'LCC (k\\$/$m^2$)')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\nplt.legend()\nplt.savefig('SCC_vs_LCC.png', dpi=400, bbox_inches='tight')\n\n\n# LCC vs SCC w Generation-based transparency\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n alphas = np.linspace(0.1, 1, len(DFs[DFName]))\n rgba_colors = np.zeros((len(DFs[DFName]),4))\n if DFName == DFNames[0]:\n rgba_colors[:,0] = 1.0 # red\n else:\n rgba_colors[:,2] = 1.0 # blue\n rgba_colors[:,3] = alphas\n plt.scatter(x=DFs[DFName][26]/10**3,y=DFs[DFName][27]/10**3,label=DFName, s=1, c=rgba_colors)\nplt.xlabel(r'LCC (k\\$/$m^2$)')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\nplt.legend()\nplt.savefig('SCC_vs_LCC_Gen_Colorcoded.png', dpi=400, bbox_inches='tight')\n\n\n# LCC vs SCC w Generation-based transparency and elite-filtered\nplt.figure(figsize=(10,5))\nfor DFName in DFNames:\n DF = DFs[DFName][DFs[DFName][26]/10**3 <= 500]\n DF = DF[DFs[DFName][27]/10**3 <= 0.1]\n alphas = np.linspace(0.1, 1, len(DF))\n rgba_colors = np.zeros((len(DF),4))\n if DFName == DFNames[0]:\n rgba_colors[:,0] = 1.0 # red\n else:\n rgba_colors[:,2] = 1.0 # blue\n rgba_colors[:,3] = alphas\n plt.scatter(x=DF[26]/10**3,y=DF[27]/10**3,label=DFName, s=1, c=rgba_colors)\nplt.xlabel(r'LCC (k\\$/$m^2$)')\nplt.ylabel(r'SCC (k\\$/$m^2$)')\nplt.legend()\nplt.savefig('SCC_vs_LCC_Gen_Colorcoded_Filtered.png', dpi=400, bbox_inches='tight')\n\n\n# =============================================================================\n# # LCC vs SCC (integrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP+WWT'\n# plt.scatter(x=DFs[DFName][26]/10**3,y=DFs[DFName][27]/10**3, s=2)\n# plt.xlabel(r'LCC (k\\$/$m^2$)')\n# plt.ylabel(r'SCC (k\\$/$m^2$)')\n# plt.savefig('SCC_vs_LCC_Integ.png', dpi=400, bbox_inches='tight')\n# \n# \n# # LCC vs SCC (disintegrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP|CWWTP'\n# plt.scatter(x=DFs[DFName][26]/10**3,y=DFs[DFName][27]/10**3, s=2)\n# # (DFs[DFName][0][26]/10**6).plot(label=DFName)\n# plt.xlabel(r'LCC (k\\$/$m^2$)')\n# plt.ylabel(r'SCC (k\\$/$m^2$)')\n# # plt.title('LCC')\n# plt.savefig('SCC_vs_LCC_Disinteg.png', dpi=400, bbox_inches='tight')\n# \n# =============================================================================\n\n#############################################\nprint('plotting Supply type vs opt objectives')\n\n\nprint('\\n#############################################')\nDisinteg_Grpd_by_CHP_meanLCC = DFs[DFNames[0]].groupby(21)[26].mean()\nDisnteg_Grpd_by_CHP_medLCC = DFs[DFNames[0]].groupby(21)[26].median()\nDisnteg_Grpd_by_CHP_meanSCC = DFs[DFNames[0]].groupby(21)[27].mean()\nDisnteg_Grpd_by_CHP_medSCC = DFs[DFNames[0]].groupby(21)[27].median()\nInteg_Grpd_by_CHP_meanLCC = DFs[DFNames[1]].groupby(21)[26].mean()\nInteg_Grpd_by_CHP_medLCC = DFs[DFNames[1]].groupby(21)[26].median()\nInteg_Grpd_by_CHP_meanSCC = DFs[DFNames[1]].groupby(21)[27].mean()\nInteg_Grpd_by_CHP_medSCC = DFs[DFNames[1]].groupby(21)[27].median()\nitems = [Disinteg_Grpd_by_CHP_meanLCC, Disnteg_Grpd_by_CHP_medLCC, Disnteg_Grpd_by_CHP_meanSCC,\n Disnteg_Grpd_by_CHP_medSCC, Integ_Grpd_by_CHP_meanLCC, Integ_Grpd_by_CHP_medLCC,\n Integ_Grpd_by_CHP_meanSCC, Integ_Grpd_by_CHP_medSCC]\nitems_names = ['Disinteg_Grpd_by_CHP_meanLCC', 'Disnteg_Grpd_by_CHP_medLCC', 'Disnteg_Grpd_by_CHP_meanSCC',\n 'Disnteg_Grpd_by_CHP_medSCC', 'Integ_Grpd_by_CHP_meanLCC', 'Integ_Grpd_by_CHP_medLCC',\n 'Integ_Grpd_by_CHP_meanSCC', 'Integ_Grpd_by_CHP_medSCC']\nfor i in range(len(items)):\n print(items_names[i], items[i])\nprint('#############################################\\n')\n\n\n\n# shapes = {DFNames[0]: '+', DFNames[1]: 'x'}\n\n\n# LCC vs CHP\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=21)\n plt.scatter(x=DF[21], y=DF[26]/10**3,label=DFName, s=2, alpha=0.5)#, c=colors_rb[DFName])#, marker=shapes[DFName])\n plt.xlabel(r'CHP Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'LCC (k\\$/$m^2$)')\n plt.ylim(-5, 500)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('LCC_vs_CHP_disinteg.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('LCC_vs_CHP_integ.png', dpi=400, bbox_inches='tight')\n\n\n# SCC vs CHP\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=21)\n plt.scatter(x=DF[21], y=DF[27]/10**3,label=DFName, s=2, alpha=0.5)#, c=colors_rb[DFName])\n plt.xlabel(r'CHP Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'SCC (k\\$/$m^2$)')\n plt.ylim(-0.01, 0.1)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('SCC_vs_CHP_disinteg.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('SCC_vs_CHP_integ.png', dpi=400, bbox_inches='tight')\n\n\n# SCC vs CHP with LCC-oriented transparency\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=21)\n DF = DF[(DF[26]<=100) & (DF[27]<=100)]\n print('number of indivs plotted: ', len(DF))\n alphas = 1.2 - DF[26]/DF[26].max() # Normalized LCCs (lowest LCC: 1; highest LCC: 0)\n # alphas = np.linspace(0.1, 1, len(DFs[DFName]))\n rgba_colors = np.zeros((len(DF),4))\n rgba_colors[:,3] = alphas\n plt.scatter(x=DF[21],y=DF[27]/10**3,label=DFName, s=1, c=rgba_colors)\n plt.xlabel(r'CHP Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'SCC (k\\$/$m^2$)')\n plt.ylim(-0.01, 0.1)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('SCC_vs_CHP_disinteg_colorCoded.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('SCC_vs_CHP_integ_colorCoded.png', dpi=400, bbox_inches='tight')\n \n \n\n# =============================================================================\n# # LCC vs CHP (integrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP+WWT'\n# plt.scatter(x=DFs[DFName][21], y=DFs[DFName][26]/10**3, s=2)\n# plt.xlabel(r'CHP Type')\n# plt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.savefig('LCC_vs_CHP_Integ.png', dpi=400, bbox_inches='tight')\n# \n# \n# # LCC vs CHP (disintegrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP|CWWTP'\n# plt.scatter(x=DFs[DFName][21], y=DFs[DFName][26]/10**3, s=2)\n# plt.xlabel(r'CHP Type')\n# plt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.savefig('LCC_vs_CHP_Disinteg.png', dpi=400, bbox_inches='tight')\n# =============================================================================\n\n\n\n# LCC vs Chiller\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=22)\n plt.scatter(x=DF[22], y=DF[26]/10**3,label=DFName, s=2, alpha=0.5)#, c=colors_rb[DFName])\n plt.xlabel(r'Chiller Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'LCC (k\\$/$m^2$)')\n plt.ylim(-5, 500)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('LCC_vs_Chiller_disinteg.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('LCC_vs_Chiller_integ.png', dpi=400, bbox_inches='tight')\n\n\n# SCC vs Chiller\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=22)\n plt.scatter(x=DF[22], y=DF[27]/10**3,label=DFName, s=2, alpha=0.5)#, c=colors_rb[DFName])\n plt.xlabel(r'Chiller Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'SCC (k\\$/$m^2$)')\n plt.ylim(-0.01, 0.1)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('SCC_vs_Chiller_disinteg.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('SCC_vs_Chiller_integ.png', dpi=400, bbox_inches='tight')\n \n \n# SCC vs Chiller with LCC-oriented transparency\nfor DFName in DFNames:\n plt.figure(figsize=(10,5))\n DF = DFs[DFName].sort_values(by=22)\n DF = DF[(DF[26]<=100) & (DF[27]<=0.5)]\n print('number of indivs plotted: ', len(DF))\n alphas = 1 - DF[26]/DF[26].max() # Normalized LCCs (lowest LCC: 1; highest LCC: 0)\n # alphas = np.linspace(0.1, 1, len(DFs[DFName]))\n rgba_colors = np.zeros((len(DF),4))\n rgba_colors[:,3] = alphas\n plt.scatter(x=DF[22],y=DF[27]/10**3,label=DFName, s=1, c=rgba_colors)\n plt.xlabel(r'Chiller Type')\n plt.xticks(rotation=75)\n plt.ylabel(r'SCC (k\\$/$m^2$)')\n plt.ylim(-0.01, 0.1)\n # plt.legend()\n if DFName == 'CCHP|CWWTP':\n plt.savefig('SCC_vs_Chiller_disinteg_colorCoded.png', dpi=400, bbox_inches='tight')\n else:\n plt.savefig('SCC_vs_Chiller_integ_colorCoded.png', dpi=400, bbox_inches='tight')\n\n\n\n# =============================================================================\n# # LCC vs Chiller (integrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP+WWT'\n# plt.scatter(x=DFs[DFName][22], y=DFs[DFName][26]/10**3, s=2)\n# plt.xlabel(r'Chiller Type')\n# plt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.savefig('LCC_vs_Chiller_Integ.png', dpi=400, bbox_inches='tight')\n# \n# \n# # LCC vs Chiller (disintegrated)\n# plt.figure(figsize=(10,5))\n# DFName = 'CCHP|CWWTP'\n# plt.scatter(x=DFs[DFName][22], y=DFs[DFName][26]/10**3, s=2)\n# plt.xlabel(r'Chiller Type')\n# plt.ylabel(r'LCC (k\\$/$m^2$)')\n# plt.savefig('LCC_vs_Chiller_Disinteg.png', dpi=400, bbox_inches='tight')\n# =============================================================================\n\n\n\n# LCC vs WWT (integrated)\nplt.figure(figsize=(10,5))\nDFName = 'CCHP+WWT'\nDF = DFs[DFName].sort_values(by=24)\nplt.scatter(x=DF[24], y=DF[26]/10**3, s=2)#, c=colors_rb[DFName])\nplt.xlabel(r'WWT Type')\nplt.xticks(rotation=75)\nplt.ylabel(r'LCC (k\\$/$m^2$)')\nplt.ylim(-5, 500)\nplt.savefig('LCC_vs_WWT_Integ.png', dpi=400, bbox_inches='tight')\n\n\n\n# SCC vs WWT (integrated)\nplt.figure(figsize=(10,5))\nDFName = 'CCHP+WWT'\nDF = DFs[DFName].sort_values(by=24)\nplt.scatter(x=DF[24], y=DF[27]/10**3, s=2)#, c=colors_rb[DFName])\nplt.xlabel(r'WWT Type')\nplt.xticks(rotation=75)\nplt.ylabel(r'SCC (k\\$/$m^2$)')\nplt.ylim(-0.01, 0.1)\nplt.savefig('SCC_vs_WWT_Integ.png', dpi=400, bbox_inches='tight')\n\n\n\n# SCC vs WWT with LCC-oriented transparency (integrated)\nplt.figure(figsize=(10,5))\nDFName = 'CCHP+WWT'\nDF = DFs[DFName].sort_values(by=24)\nDF = DF[(DF[26]<=100) & (DF[27]<=0.5)]\nprint('number of indivs plotted: ', len(DF))\nalphas = 1 - DF[26]/DF[26].max() # Normalized LCCs (lowest LCC: 1; highest LCC: 0)\n# alphas = np.linspace(0.1, 1, len(DFs[DFName]))\nrgba_colors = np.zeros((len(DF),4))\nrgba_colors[:,3] = alphas\nplt.scatter(x=DF[24],y=DF[27]/10**3,s=1, c=rgba_colors)\nplt.xlabel(r'WWT Type')\nplt.xticks(rotation=75)\nplt.ylabel(r'SCC (k\\$/$m^2$)')\nplt.ylim(-0.01, 0.1)\nplt.savefig('SCC_vs_WWT_Integ_colorCoded.png', dpi=400, bbox_inches='tight')\n\nplt.close('all')\n\n#############################################\n'''\nprint('plotting building mix traces')\n\n# Building Mix trace plots\nDFName = 'CCHP+WWT'\nplt.figure(figsize=(10,5))\nfig = plt.figure(figsize=(10,5))\nax = fig.add_subplot(111)\nNum_Individuals = len(DFs[DFName])\ncm = plt.get_cmap('rainbow')\nax.set_prop_cycle(color=[cm(1.*i/Num_Individuals) for i in range(Num_Individuals)])#ax.set_color_cycle([cm(1.*i/Num_Individuals) for i in range(Num_Individuals)])\nfor i in range(Num_Individuals):\n ax.plot(['Res','Off','Com','Ind','Hos','Med','Edu'],\n DFs[DFName].iloc[i,29:36],linewidth=0.2, alpha=0.5)\nax.set_xlabel('Building-Use')\nax.set_ylabel('Percent of Total GFA (%)')\nplt.ylim(0, 100)\nfig.savefig('Uses_Integ.png', dpi=400, bbox_inches='tight')\n\n\n\n\nDFName = 'CCHP|CWWTP'\nfig = plt.figure(figsize=(10,5))\nax = fig.add_subplot(111)\nNum_Individuals = len(DFs[DFName])\ncm = plt.get_cmap('rainbow')\nax.set_prop_cycle(color=[cm(1.*i/Num_Individuals) for i in range(Num_Individuals)])#ax.set_color_cycle([cm(1.*i/Num_Individuals) for i in range(Num_Individuals)])\ny_array = np.array(DFs[DFName].iloc[:,29:36])\nfor i in range(Num_Individuals):\n ax.plot(['Res','Off','Com','Ind','Hos','Med','Edu'],\n DFs[DFName].iloc[i,29:36],linewidth=0.2, alpha=0.5)\nax.set_xlabel('Building-Use')\nax.set_ylabel('Percent of Total GFA (%)')\nplt.ylim(0, 100)\nfig.savefig('Uses_Disinteg.png', dpi=400, bbox_inches='tight')\nplt.close('all')\n'''\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.scatter", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "pandas.DataFrame", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.style.use", "numpy.loadtxt", "matplotlib.pyplot.ylabel" ] ]
[ { "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": [] } ]
Felihong/wikidata-sequence-analysis
[ "1d86ad9812c90864eb2c9ab72e5e61474d439f1e" ]
[ "src/sequence_generator.py" ]
[ "import pandas as pd\nfrom itertools import groupby\nfrom operator import itemgetter\n\nclass SequenceGenerator:\n\n def __init__(self, csvfile, jsThreshold):\n self.datafile = csvfile\n self.jsThreshold = jsThreshold\n\n \"\"\"\n Convert the input csv file into dataframe\n \"\"\"\n def _csv2df(self):\n return pd.read_csv(self.datafile, dtype={'item_id':int, 'user_id':str})\n\n \"\"\"\n Generate database by selecting the non-null sequences satisfying the js-distance threshold\n \"\"\"\n def generate_db(self):\n db = self._csv2df()[['item_id', 'user_id', 'edit_type', 'rev_timestamp', 'js_distance']].sort_values(by=['item_id','rev_timestamp'])\n filter = db.loc[db['js_distance'] >= self.jsThreshold][['item_id', 'user_id', 'edit_type']]\n return filter[filter.user_id.notnull()]\n\n def generate_dev_db(self, dev):\n db = self._csv2df()[['item_id', 'user_id', 'edit_type', 'rev_timestamp', 'prediction', 'js_distance']].sort_values(by=['item_id', 'rev_timestamp'])\n filter = db.loc[(db['js_distance']>=self.jsThreshold) & (db['prediction']==dev)][['item_id', 'user_id', 'edit_type']]\n return filter[filter.user_id.notnull()]\n\n \"\"\"\n Generate the sequence database by integrating all edits conducted upon one article in a list, where\n the serial edits from the same editor are collapsed into one sub-list\n Args: \n csv file of scheme: article_id : int\n editor_id : int \n edit_type : string \n Return:\n A list of list [[a], [b]], where a and b are collapsed edit types \n \"\"\"\n def generate_sequence(self):\n db = self.generate_db()\n df = db.groupby(['item_id', 'user_id']).agg({'edit_type': list})\n result = df.groupby(['item_id']).agg({'edit_type': list})\n tmp = []\n for ls in result.values.tolist():\n tmp.append(ls[0])\n return tmp\n\n def generate_dev_sequence(self, dev):\n db = self.generate_dev_db(dev=dev)\n df = db.groupby(['item_id', 'user_id']).agg({'edit_type': list})\n return df.values.tolist()" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
cvmxn1/OpenFermion
[ "cf53c063d0f124a02ff8776bb7f8afb110d4bde6" ]
[ "src/openfermion/resource_estimates/molecule/pyscf_utils.py" ]
[ "#coverage:ignore\n\"\"\" Drivers for various PySCF electronic structure routines \"\"\"\nfrom typing import Tuple, Optional\nimport sys\nimport h5py\nimport numpy as np\nfrom pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc\nfrom pyscf.mcscf import avas\n\n\ndef stability(pyscf_mf):\n \"\"\"\n Test wave function stability and re-optimize SCF.\n\n Args:\n pyscf_mf: PySCF mean field object (e.g. `scf.RHF()`)\n\n Returns:\n pyscf_mf: Updated PySCF mean field object\n \"\"\"\n new_orbitals = pyscf_mf.stability()[0]\n new_1rdm = pyscf_mf.make_rdm1(new_orbitals, pyscf_mf.mo_occ)\n pyscf_mf = pyscf_mf.run(new_1rdm)\n\n return pyscf_mf\n\n\ndef localize(pyscf_mf, loc_type='pm', verbose=0):\n \"\"\" Localize orbitals given a PySCF mean-field object\n\n Args:\n pyscf_mf: PySCF mean field object\n loc_type (str): localization type;\n Pipek-Mezey ('pm') or Edmiston-Rudenberg ('er')\n verbose (int): print level during localization\n\n Returns:\n pyscf_mf: Updated PySCF mean field object with localized orbitals\n \"\"\"\n # Note: After loading with `load_casfile_to_pyscf()` you can quiet message\n # by resetting mf.mol, i.e., mf.mol = gto.M(...)\n # but this assumes you have the *exact* molecular specification on hand.\n # I've gotten acceptable results by restoring mf.mol this way (usually\n # followed by calling mf.kernel()). But consistent localization is not a\n # given (not unique) despite restoring data this way, hence the message.\n if len(pyscf_mf.mol.atom) == 0:\n sys.exit(\"`localize()` requires atom loc. and atomic basis to be\" + \\\n \" defined.\\n \" + \\\n \"It also can be sensitive to the initial guess and MO\" + \\\n \" coefficients.\\n \" + \\\n \"Best to try re-creating the PySCF molecule and doing the\" + \\\n \" SCF, rather than\\n \" + \\\n \"try to load the mean-field object with\" + \\\n \" `load_casfile_to_pyscf()`. You can \\n \" + \\\n \"try to provide the missing information, but consistency\" + \\\n \" cannot be guaranteed!\")\n\n # Split-localize (localize DOCC, SOCC, and virtual separately)\n docc_idx = np.where(np.isclose(pyscf_mf.mo_occ, 2.))[0]\n socc_idx = np.where(np.isclose(pyscf_mf.mo_occ, 1.))[0]\n virt_idx = np.where(np.isclose(pyscf_mf.mo_occ, 0.))[0]\n\n # Pipek-Mezey\n if loc_type.lower() == 'pm':\n print(\"Localizing doubly occupied ... \", end=\"\")\n loc_docc_mo = lo.PM(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, docc_idx]).kernel(verbose=verbose)\n print(\"singly occupied ... \", end=\"\")\n loc_socc_mo = lo.PM(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, socc_idx]).kernel(verbose=verbose)\n print(\"virtual ... \", end=\"\")\n loc_virt_mo = lo.PM(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, virt_idx]).kernel(verbose=verbose)\n print(\"DONE\")\n\n # Edmiston-Rudenberg\n elif loc_type.lower() == 'er':\n print(\"Localizing doubly occupied ... \", end=\"\")\n loc_docc_mo = lo.ER(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, docc_idx]).kernel(verbose=verbose)\n print(\"singly occupied ... \", end=\"\")\n loc_socc_mo = lo.ER(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, socc_idx]).kernel(verbose=verbose)\n print(\"virtual ... \", end=\"\")\n loc_virt_mo = lo.ER(\n pyscf_mf.mol,\n pyscf_mf.mo_coeff[:, virt_idx]).kernel(verbose=verbose)\n print(\"DONE\")\n\n # overwrite orbitals with localized orbitals\n pyscf_mf.mo_coeff[:, docc_idx] = loc_docc_mo.copy()\n pyscf_mf.mo_coeff[:, socc_idx] = loc_socc_mo.copy()\n pyscf_mf.mo_coeff[:, virt_idx] = loc_virt_mo.copy()\n\n return pyscf_mf\n\n\ndef avas_active_space(pyscf_mf,\n ao_list=None,\n molden_fname='avas_localized_orbitals',\n **kwargs):\n \"\"\" Return AVAS active space as PySCF molecule and mean-field object\n\n Args:\n pyscf_mf: PySCF mean field object\n\n Kwargs:\n ao_list: list of strings of AOs (print mol.ao_labels() to see options)\n Example: ao_list = ['H 1s', 'O 2p', 'O 2s'] for water\n verbose (bool): do additional print\n molden_fname (str): MOLDEN filename to save AVAS active space orbitals.\n Default is to save\n to 'avas_localized_orbitals.molden'\n **kwargs: other keyworded arguments to pass into avas.avas()\n\n Returns:\n pyscf_active_space_mol: Updated PySCF molecule object from\n AVAS-selected active space\n pyscf_active_space_mf: Updated PySCF mean field object from\n AVAS-selected active space\n \"\"\"\n\n # Note: requires openshell_option = 3 for this to work, which keeps all\n # singly occupied in CAS\n # we also require canonicalize = False so that we don't destroy local orbs\n avas_output = avas.avas(pyscf_mf,\n ao_list,\n canonicalize=False,\n openshell_option=3,\n **kwargs)\n active_norb, active_ne, reordered_orbitals = avas_output\n\n active_alpha, _ = get_num_active_alpha_beta(pyscf_mf, active_ne)\n\n if molden_fname is not None:\n # save set of localized orbitals for active space\n if isinstance(pyscf_mf, scf.rohf.ROHF):\n frozen_alpha = pyscf_mf.nelec[0] - active_alpha\n assert frozen_alpha >= 0\n else:\n frozen_alpha = pyscf_mf.mol.nelectron // 2 - active_alpha\n assert frozen_alpha >= 0\n\n active_space_idx = slice(frozen_alpha, frozen_alpha + active_norb)\n active_mos = reordered_orbitals[:, active_space_idx]\n tools.molden.from_mo(pyscf_mf.mol,\n molden_fname + '.molden',\n mo_coeff=active_mos)\n\n # Choosing an active space changes the molecule (\"freezing\" electrons,\n # for example), so we\n # form the active space tensors first, then re-form the PySCF objects to\n # ensure consistency\n pyscf_active_space_mol, pyscf_active_space_mf = cas_to_pyscf(\n *pyscf_to_cas(pyscf_mf,\n cas_orbitals=active_norb,\n cas_electrons=active_ne,\n avas_orbs=reordered_orbitals))\n\n return pyscf_active_space_mol, pyscf_active_space_mf\n\n\ndef cas_to_pyscf(h1, eri, ecore, num_alpha, num_beta):\n \"\"\" Return a PySCF molecule and mean-field object from pre-computed CAS Ham\n\n Args:\n h1 (ndarray) - 2D matrix containing one-body terms (MO basis)\n eri (ndarray) - 4D tensor containing two-body terms (MO basis)\n ecore (float) - frozen core electronic energy + nuclear repulsion energy\n num_alpha (int) - number of spin up electrons in CAS space\n num_beta (int) - number of spin down electrons in CAS space\n\n Returns:\n pyscf_mol: PySCF molecule object\n pyscf_mf: PySCF mean field object\n \"\"\"\n\n n_orb = len(h1) # number orbitals\n assert [n_orb] * 4 == [*eri.shape] # check dims are consistent\n\n pyscf_mol = gto.M()\n pyscf_mol.nelectron = num_alpha + num_beta\n n_orb = h1.shape[0]\n alpha_diag = [1] * num_alpha + [0] * (n_orb - num_alpha)\n beta_diag = [1] * num_beta + [0] * (n_orb - num_beta)\n\n # Assumes Hamiltonian is either RHF or ROHF ... should be OK since UHF will\n # have two h1s, etc.\n if num_alpha == num_beta:\n pyscf_mf = scf.RHF(pyscf_mol)\n scf_energy = ecore + \\\n 2*np.einsum('ii', h1[:num_alpha,:num_alpha]) + \\\n 2*np.einsum('iijj',\n eri[:num_alpha,:num_alpha,:num_alpha,:num_alpha]) - \\\n np.einsum('ijji',\n eri[:num_alpha,:num_alpha,:num_alpha,:num_alpha])\n\n else:\n pyscf_mf = scf.ROHF(pyscf_mol)\n pyscf_mf.nelec = (num_alpha, num_beta)\n # grab singly and doubly occupied orbitals (assume high-spin open shell)\n docc = slice(None, min(num_alpha, num_beta))\n socc = slice(min(num_alpha, num_beta), max(num_alpha, num_beta))\n scf_energy = ecore + \\\n 2.0*np.einsum('ii',h1[docc, docc]) + \\\n np.einsum('ii',h1[socc, socc]) + \\\n 2.0*np.einsum('iijj',eri[docc, docc, docc, docc]) - \\\n np.einsum('ijji',eri[docc, docc, docc, docc]) + \\\n np.einsum('iijj',eri[socc, socc, docc, docc]) - \\\n 0.5*np.einsum('ijji',eri[socc, docc, docc, socc]) + \\\n np.einsum('iijj',eri[docc, docc, socc, socc]) - \\\n 0.5*np.einsum('ijji',eri[docc, socc, socc, docc]) + \\\n 0.5*np.einsum('iijj',eri[socc, socc, socc, socc]) - \\\n 0.5*np.einsum('ijji',eri[socc, socc, socc, socc])\n\n pyscf_mf.get_hcore = lambda *args: np.asarray(h1)\n pyscf_mf.get_ovlp = lambda *args: np.eye(h1.shape[0])\n pyscf_mf.energy_nuc = lambda *args: ecore\n pyscf_mf._eri = eri # ao2mo.restore('8', np.zeros((8, 8, 8, 8)), 8)\n pyscf_mf.e_tot = scf_energy\n\n pyscf_mf.init_guess = '1e'\n pyscf_mf.mo_coeff = np.eye(n_orb)\n pyscf_mf.mo_occ = np.array(alpha_diag) + np.array(beta_diag)\n pyscf_mf.mo_energy, _ = np.linalg.eigh(pyscf_mf.get_fock())\n\n return pyscf_mol, pyscf_mf\n\n\ndef pyscf_to_cas(pyscf_mf,\n cas_orbitals: Optional[int] = None,\n cas_electrons: Optional[int] = None,\n avas_orbs=None):\n \"\"\" Return CAS Hamiltonian tensors from a PySCF mean-field object\n\n Args:\n pyscf_mf: PySCF mean field object\n cas_orbitals (int, optional): number of orbitals in CAS space,\n default all orbitals\n cas_electrons (int, optional): number of electrons in CAS space,\n default all electrons\n avas_orbs (ndarray, optional): orbitals selected by AVAS in PySCF\n\n Returns:\n h1 (ndarray) - 2D matrix containing one-body terms (MO basis)\n eri (ndarray) - 4D tensor containing two-body terms (MO basis)\n ecore (float) - frozen core electronic energy + nuclear repulsion energy\n num_alpha (int) - number of spin up electrons in CAS space\n num_beta (int) - number of spin down electrons in CAS space\n \"\"\"\n\n # Only RHF or ROHF possible with mcscf.CASCI\n assert isinstance(pyscf_mf, scf.rhf.RHF) # ROHF is child of RHF class\n\n if cas_orbitals is None:\n cas_orbitals = len(pyscf_mf.mo_coeff)\n if cas_electrons is None:\n cas_electrons = pyscf_mf.mol.nelectron\n\n cas = mcscf.CASCI(pyscf_mf, ncas=cas_orbitals, nelecas=cas_electrons)\n h1, ecore = cas.get_h1eff(mo_coeff=avas_orbs)\n eri = cas.get_h2cas(mo_coeff=avas_orbs)\n eri = ao2mo.restore('s1', eri, h1.shape[0]) # chemist convention (11|22)\n ecore = float(ecore)\n\n num_alpha, num_beta = get_num_active_alpha_beta(pyscf_mf, cas_electrons)\n\n return h1, eri, ecore, num_alpha, num_beta\n\n\ndef get_num_active_alpha_beta(pyscf_mf, cas_electrons):\n \"\"\" Return number of alpha and beta electrons in the active space given\n number of CAS electrons\n This assumes that all the unpaired electrons are in the active space\n\n Args:\n pyscf_mf: PySCF mean field object\n cas_orbitals (int): number of electrons in CAS space,\n\n Returns:\n num_alpha (int): number of alpha (spin-up) electrons in active space\n num_beta (int): number of beta (spin-down) electrons in active space\n \"\"\"\n # Sanity checks and active space info\n total_electrons = pyscf_mf.mol.nelectron\n frozen_electrons = total_electrons - cas_electrons\n assert frozen_electrons % 2 == 0\n\n # ROHF == RHF but RHF != ROHF, and we only do either RHF or ROHF\n if isinstance(pyscf_mf, scf.rohf.ROHF):\n frozen_alpha = frozen_electrons // 2\n frozen_beta = frozen_electrons // 2\n num_alpha = pyscf_mf.nelec[0] - frozen_alpha\n num_beta = pyscf_mf.nelec[1] - frozen_beta\n assert np.isclose(num_beta + num_alpha, cas_electrons)\n\n else:\n assert cas_electrons % 2 == 0\n num_alpha = cas_electrons // 2\n num_beta = cas_electrons // 2\n\n return num_alpha, num_beta\n\n\ndef load_casfile_to_pyscf(fname,\n num_alpha: Optional[int] = None,\n num_beta: Optional[int] = None):\n \"\"\" Load CAS Hamiltonian from pre-computed HD5 file into a PySCF molecule\n and mean-field object\n\n Args:\n fname (str): path to hd5 file to be created containing CAS one and two\n body terms\n num_alpha (int, optional): number of spin up electrons in CAS space\n num_beta (int, optional): number of spin down electrons in CAS space\n\n Returns:\n pyscf_mol: PySCF molecule object\n pyscf_mf: PySCF mean field object\n \"\"\"\n\n with h5py.File(fname, \"r\") as f:\n eri = np.asarray(f['eri'][()])\n # h1 one body elements are sometimes called different things. Try a few.\n try:\n h1 = np.asarray(f['h0'][()])\n except KeyError:\n try:\n h1 = np.asarray(f['hcore'][()])\n except KeyError:\n try:\n h1 = np.asarray(f['h1'][()])\n except KeyError:\n raise KeyError(\"Could not find 1-electron Hamiltonian\")\n # ecore sometimes exists, and sometimes as enuc (no frozen electrons)\n try:\n ecore = float(f['ecore'][()])\n except KeyError:\n try:\n ecore = float(f['enuc'][()])\n except KeyError:\n ecore = 0.0\n # read the number of spin up and spin down electrons if not input\n if (num_alpha is None) or (num_beta is None):\n try:\n num_alpha = int(f['active_nalpha'][()])\n except KeyError:\n sys.exit(\"In `load_casfile_to_pyscf()`: \\n\" + \\\n \" No values found on file for num_alpha \" + \\\n \"(key: 'active_nalpha' in h5). \" + \\\n \" Try passing in a value for num_alpha, or\" + \\\n \" re-check integral file.\")\n try:\n num_beta = int(f['active_nbeta'][()])\n except KeyError:\n sys.exit(\"In `load_casfile_to_pyscf()`: \\n\" + \\\n \" No values found on file for num_beta \" + \\\n \"(key: 'active_nbeta' in h5). \" + \\\n \" Try passing in a value for num_beta, or\" + \\\n \" re-check integral file.\")\n\n pyscf_mol, pyscf_mf = cas_to_pyscf(h1, eri, ecore, num_alpha, num_beta)\n\n return pyscf_mol, pyscf_mf\n\n\ndef save_pyscf_to_casfile(fname,\n pyscf_mf,\n cas_orbitals: Optional[int] = None,\n cas_electrons: Optional[int] = None,\n avas_orbs=None):\n \"\"\" Save CAS Hamiltonian from a PySCF mean-field object to an HD5 file\n\n Args:\n fname (str): path to hd5 file to be created containing CAS terms\n pyscf_mf: PySCF mean field object\n cas_orbitals (int, optional): number of orb in CAS space, default all\n cas_electrons (int, optional): number of elec in CAS, default all elec\n avas_orbs (ndarray, optional): orbitals selected by AVAS in PySCF\n \"\"\"\n h1, eri, ecore, num_alpha, num_beta = \\\n pyscf_to_cas(pyscf_mf, cas_orbitals, cas_electrons, avas_orbs)\n\n with h5py.File(fname, 'w') as fid:\n fid.create_dataset('ecore', data=float(ecore), dtype=float)\n fid.create_dataset(\n 'h0',\n data=h1) # note the name change to be consistent with THC paper\n fid.create_dataset('eri', data=eri)\n fid.create_dataset('active_nalpha', data=int(num_alpha), dtype=int)\n fid.create_dataset('active_nbeta', data=int(num_beta), dtype=int)\n\n\ndef factorized_ccsd_t(pyscf_mf, eri_rr = None, use_kernel = True,\\\n no_triples=False) -> Tuple[float, float, float]:\n \"\"\" Compute CCSD(T) energy using rank-reduced ERIs\n\n Args:\n pyscf_mf - PySCF mean field object\n eri_rr (ndarray) - rank-reduced ERIs, or use full ERIs from pyscf_mf\n use_kernel (bool) - re-do SCF, using canonical orbitals for one-body?\n no_triples (bool) - skip the perturbative triples correction? (CCSD)\n\n Returns:\n e_scf (float) - SCF energy\n e_cor (float) - Correlation energy from CCSD(T)\n e_tot (float) - Total energy; i.e. SCF + Corr energy from CCSD(T)\n \"\"\"\n h1, eri_full, ecore, num_alpha, num_beta = pyscf_to_cas(pyscf_mf)\n\n # If no rank-reduced ERIs, use the full (possibly local) ERIs from pyscf_mf\n if eri_rr is None:\n eri_rr = eri_full\n\n e_scf, e_cor, e_tot = ccsd_t(h1, eri_rr, ecore, num_alpha, num_beta,\\\n eri_full, use_kernel, no_triples)\n\n return e_scf, e_cor, e_tot\n\n\ndef ccsd_t(h1, eri, ecore, num_alpha: int, num_beta: int, eri_full = None,\\\n use_kernel=True, no_triples=False) -> Tuple[float, float, float]:\n \"\"\" Helper function to do CCSD(T) on set of one- and two-body Hamil elems\n\n Args:\n h1 (ndarray) - 2D matrix containing one-body terms (MO basis)\n eri (ndarray) - 4D tensor containing two-body terms (MO basis)\n may be from integral factorization (e.g. SF/DF/THC)\n ecore (float) - frozen core electronic energy + nuclear repulsion energy\n num_alpha (int) - number of spin alpha electrons in Hamiltonian\n num_beta (int) - number of spin beta electrons in Hamiltonian\n eri_full (ndarray) - optional 4D tensor containing full two-body\n terms (MO basis) for the SCF procedure only\n use_kernel (bool) - re-run SCF prior to doing CCSD(T)?\n no_triples (bool) - skip the perturbative triples correction? (CCSD)\n\n Returns:\n e_scf (float) - SCF energy\n e_cor (float) - Correlation energy from CCSD(T)\n e_tot (float) - Total energy; i.e. SCF + Corr energy from CCSD(T)\n \"\"\"\n\n mol = gto.M()\n mol.nelectron = num_alpha + num_beta\n n_orb = h1.shape[0]\n alpha_diag = [1] * num_alpha + [0] * (n_orb - num_alpha)\n beta_diag = [1] * num_beta + [0] * (n_orb - num_beta)\n\n # If eri_full not provided, use (possibly rank-reduced) ERIs for check\n if eri_full is None:\n eri_full = eri\n\n # either RHF or ROHF ... should be OK since UHF will have two h1s, etc.\n if num_alpha == num_beta:\n mf = scf.RHF(mol)\n scf_energy = ecore + \\\n 2*np.einsum('ii',h1[:num_alpha,:num_alpha]) + \\\n 2*np.einsum('iijj',eri_full[:num_alpha,\\\n :num_alpha,\\\n :num_alpha,\\\n :num_alpha]) - \\\n np.einsum('ijji',eri_full[:num_alpha,\\\n :num_alpha,\\\n :num_alpha,\\\n :num_alpha])\n\n else:\n mf = scf.ROHF(mol)\n mf.nelec = (num_alpha, num_beta)\n # grab singly and doubly occupied orbitals (assume high-spin open shell)\n docc = slice(None, min(num_alpha, num_beta))\n socc = slice(min(num_alpha, num_beta), max(num_alpha, num_beta))\n scf_energy = ecore + \\\n 2.0*np.einsum('ii',h1[docc, docc]) + \\\n np.einsum('ii',h1[socc, socc]) + \\\n 2.0*np.einsum('iijj',eri_full[docc, docc, docc, docc]) - \\\n np.einsum('ijji',eri_full[docc, docc, docc, docc]) + \\\n np.einsum('iijj',eri_full[socc, socc, docc, docc]) - \\\n 0.5*np.einsum('ijji',eri_full[socc, docc, docc, socc]) + \\\n np.einsum('iijj',eri_full[docc, docc, socc, socc]) - \\\n 0.5*np.einsum('ijji',eri_full[docc, socc, socc, docc]) + \\\n 0.5*np.einsum('iijj',eri_full[socc, socc, socc, socc]) - \\\n 0.5*np.einsum('ijji',eri_full[socc, socc, socc, socc])\n\n mf.get_hcore = lambda *args: np.asarray(h1)\n mf.get_ovlp = lambda *args: np.eye(h1.shape[0])\n mf.energy_nuc = lambda *args: ecore\n mf._eri = eri_full # ao2mo.restore('8', np.zeros((8, 8, 8, 8)), 8)\n\n mf.init_guess = '1e'\n mf.mo_coeff = np.eye(n_orb)\n mf.mo_occ = np.array(alpha_diag) + np.array(beta_diag)\n w, _ = np.linalg.eigh(mf.get_fock())\n mf.mo_energy = w\n\n # Rotate the interaction tensors into the canonical basis.\n # Reiher and Li tensors, for example, are read-in in the local MO basis,\n # which is not optimal for the CCSD(T) calculation (canonical gives better\n # energy estimate whereas QPE is invariant to choice of basis)\n if use_kernel:\n mf.conv_tol = 1e-7\n mf.init_guess = '1e'\n mf.verbose = 4\n mf.diis_space = 24\n mf.level_shift = 0.5\n mf.conv_check = False\n mf.max_cycle = 800\n mf.kernel(mf.make_rdm1(mf.mo_coeff,\n mf.mo_occ)) # use MO info to generate guess\n mf = stability(mf)\n mf = stability(mf)\n mf = stability(mf)\n\n # Check if SCF has changed by doing restart, and print warning if so\n try:\n assert np.isclose(scf_energy, mf.e_tot, rtol=1e-14)\n except AssertionError:\n print(\n \"WARNING: E(SCF) from input integrals does not match E(SCF)\" + \\\n \" from mf.kernel()\")\n print(\" Will use E(SCF) = {:12.6f} from mf.kernel going forward.\".\n format(mf.e_tot))\n print(\"E(SCF, ints) = {:12.6f} whereas E(SCF) = {:12.6f}\".format(\n scf_energy, mf.e_tot))\n\n # New SCF energy and orbitals for CCSD(T)\n scf_energy = mf.e_tot\n\n # Now re-set the eri's to the (possibly rank-reduced) ERIs\n mf._eri = eri\n mf.mol.incore_anyway = True\n\n mycc = cc.CCSD(mf)\n mycc.max_cycle = 800\n mycc.conv_tol = 1E-8\n mycc.conv_tol_normt = 1E-4\n mycc.diis_space = 24\n mycc.verbose = 4\n mycc.kernel()\n\n if no_triples:\n et = 0.0\n else:\n et = mycc.ccsd_t()\n\n e_scf = scf_energy # may be read-in value or 'fresh' SCF value\n e_cor = mycc.e_corr + et\n e_tot = e_scf + e_cor\n\n print(\"E(SCF): \", e_scf)\n print(\"E(cor): \", e_cor)\n print(\"Total energy: \", e_tot)\n return e_scf, e_cor, e_tot\n\n\ndef open_shell_t1_d1(t1a, t1b, mo_occ, nalpha, nbeta):\n \"\"\"\n T1-diagnostic for open-shell is defined w.r.t Sx eigenfunction of T1\n where reference is ROHF.\n\n given i double occ, c unoccupied, x is single occuplied The T1 amps\n (high spin) in Sz basis are:\n T1 = t_{ia}^{ca}(ca^ ia) + t_{ib}^{cb}(cb^ ib)\n + t_{xa}^{ca}(ca^ xa) + t_{ib}^{xb}(xb^ ib)\n T1 in the Sx basis are\n T1 = f_{i}^{c}E_{ci} + v_{i}^{c}A_{ci}\n + sqrt(2)f_{x}^{c}(ca^ xa) + sqrt(2)f_{i}^{x}(xb^ ib)\n\n where E_{ci} = ca^ ia + cb^ ib and A_{ci} = ca^ ia - cb^ ib.\n\n See: The Journal of Chemical Physics 98, 9734 (1993);\n doi: 10.1063/1.464352\n Chemical Physics Letters 372 (2003) 362–367;\n doi:10.1016/S0009-2614(03)00435-4\n\n based on these and two papers from Lee the T1-openshell diagnostic is\n\n sqrt(sum_{ia}(f_{ia})^2 + 2sum_{xa}(t_{xa}^{ca})^2\n + 2 sum_{ix}(t_{ib}^{xb})^2) / 2 sqrt{N}\n\n To get this relate eqs 3-7 from Chemical Physics Letters 372 (2003) 362–367\n to Eqs. 45, 46, and 51 from Journal of Chemical Physics 98, 9734 (1993);\n doi: 10.1063/1.464352.\n \"\"\"\n # compute t1-diagnostic\n docc_idx = np.where(np.isclose(mo_occ, 2.))[0]\n socc_idx = np.where(np.isclose(mo_occ, 1.))[0]\n virt_idx = np.where(np.isclose(mo_occ, 0.))[0]\n t1a_docc = t1a[docc_idx, :] # double occ-> virtual\n t1b_docc = t1b[docc_idx, :][:, -len(virt_idx):] # double occ-> virtual\n if len(socc_idx) > 0:\n t1_xa = t1a[socc_idx, :] # single occ -> virtual\n t1_ix = t1b[docc_idx, :][:, :len(socc_idx)] # double occ -> single occ\n else:\n t1_xa = np.array(())\n t1_ix = np.array(())\n\n if nalpha - nbeta + len(virt_idx) != t1b.shape[1]:\n raise ValueError(\n \"Inconsistent shapes na {}, nb {}, t1b.shape {},{}\".format(\n nalpha, nbeta, t1b.shape[0], t1b.shape[1]))\n\n if t1a_docc.shape != (len(docc_idx), len(virt_idx)):\n raise ValueError(\"T1a_ia does not have the right shape\")\n if t1b_docc.shape != (len(docc_idx), len(virt_idx)):\n raise ValueError(\"T1b_ia does not have the right shape\")\n if len(socc_idx) > 0:\n if t1_ix.shape != (len(docc_idx), len(socc_idx)):\n raise ValueError(\"T1_ix does not have the right shape\")\n if t1_xa.shape != (len(socc_idx), len(virt_idx)):\n raise ValueError(\"T1_xa does not have the right shape\")\n\n t1_diagnostic = np.sqrt(\n np.sum((t1a_docc + t1b_docc)**2) + 2 * np.sum(t1_xa**2) +\n 2 * np.sum(t1_ix**2)) / (2 * np.sqrt(nalpha + nbeta))\n # compute D1-diagnostic\n f_ia = 0.5 * (t1a_docc + t1b_docc)\n s_f_ia_2, _ = np.linalg.eigh(f_ia @ f_ia.T)\n s_f_ia_2_norm = np.sqrt(np.max(s_f_ia_2, initial=0))\n\n if len(socc_idx) > 0:\n f_xa = np.sqrt(1 / 2) * t1_xa\n f_ix = np.sqrt(1 / 2) * t1_ix\n s_f_xa_2, _ = np.linalg.eigh(f_xa @ f_xa.T)\n s_f_ix_2, _ = np.linalg.eigh(f_ix @ f_ix.T)\n else:\n s_f_xa_2 = np.array(())\n s_f_ix_2 = np.array(())\n s_f_xa_2_norm = np.sqrt(np.max(s_f_xa_2, initial=0))\n s_f_ix_2_norm = np.sqrt(np.max(s_f_ix_2, initial=0))\n\n d1_diagnostic = np.max(\n np.array([s_f_ia_2_norm, s_f_xa_2_norm, s_f_ix_2_norm]))\n\n return t1_diagnostic, d1_diagnostic\n" ]
[ [ "numpy.sqrt", "numpy.einsum", "numpy.asarray", "numpy.eye", "numpy.max", "numpy.linalg.eigh", "numpy.array", "numpy.sum", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wenhaopeter/read_pytorch_code
[ "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f", "491f989cd918cf08874dd4f671fb7f0142a0bc4f" ]
[ "torch/testing/_internal/common_utils.py", "test/distributed/test_ddp_under_dist_autograd.py", "caffe2/python/data_parallel_model_test.py", "test/test_show_pickle.py", "caffe2/python/operator_test/bbox_transform_test.py", "test/type_hint_tests/tensor_copy.py", "caffe2/python/optimizer_test_util.py", "caffe2/python/operator_test/cast_op_test.py", "caffe2/python/operator_test/elementwise_ops_test.py", "torch/distributions/geometric.py", "test/distributed/rpc/faulty_agent/test_dist_autograd_spawn.py", "caffe2/python/operator_test/segment_ops_test.py", "torch/__init__.py", "torch/nn/modules/activation.py", "benchmarks/operator_benchmark/pt/remainder_test.py", "python_torch_test/test_short.py", "benchmarks/operator_benchmark/common/tests/jit_forward_test.py", "caffe2/python/operator_test/mpi_test.py", "caffe2/python/predictor/mobile_exporter_test.py", "caffe2/quantization/server/elementwise_add_dnnlowp_op_test.py" ]
[ "r\"\"\"Importing this file must **not** initialize CUDA context. test_distributed\nrelies on this assumption to properly run. This means that when this is imported\nno CUDA calls shall be made, including torch.cuda.device_count(), etc.\n\ntorch.testing._internal.common_cuda.py can freely initialize CUDA context when imported.\n\"\"\"\n\nimport sys\nimport os\nimport platform\nimport re\nimport gc\nimport types\nfrom functools import partial\nimport inspect\nimport io\nimport argparse\nimport unittest\nimport warnings\nimport random\nimport contextlib\nimport socket\nimport subprocess\nimport time\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nfrom functools import wraps\nfrom itertools import product\nfrom copy import deepcopy\nfrom numbers import Number\nimport tempfile\nimport json\nfrom urllib.request import urlopen\nimport __main__\nimport errno\nfrom typing import cast, Any, Iterable, Optional\n\nfrom torch.testing._internal import expecttest\nfrom torch.testing import _compare_tensors_internal, _compare_scalars_internal, _compare_return_type\n\nimport torch\nimport torch.cuda\nfrom torch._utils_internal import get_writable_path\nfrom torch._six import string_classes\nimport torch.backends.cudnn\nimport torch.backends.mkl\nfrom enum import Enum\nfrom torch.autograd import gradcheck\nfrom torch.autograd.gradcheck import gradgradcheck\n\ntorch.backends.disable_global_flags()\n\nIS_SANDCASTLE = os.getenv('SANDCASTLE') == '1' or os.getenv('TW_JOB_USER') == 'sandcastle'\n\nclass ProfilingMode(Enum):\n LEGACY = 1\n SIMPLE = 2\n PROFILING = 3\n\ndef cppProfilingFlagsToProfilingMode():\n old_prof_exec_state = torch._C._jit_set_profiling_executor(True)\n old_prof_mode_state = torch._C._jit_set_profiling_mode(True)\n torch._C._jit_set_profiling_executor(old_prof_exec_state)\n torch._C._jit_set_profiling_mode(old_prof_mode_state)\n\n if old_prof_exec_state:\n if old_prof_mode_state:\n return ProfilingMode.PROFILING\n else:\n return ProfilingMode.SIMPLE\n else:\n return ProfilingMode.LEGACY\n\n@contextmanager\ndef enable_profiling_mode_for_profiling_tests():\n if GRAPH_EXECUTOR == ProfilingMode.PROFILING:\n old_prof_exec_state = torch._C._jit_set_profiling_executor(True)\n old_prof_mode_state = torch._C._jit_set_profiling_mode(True)\n try:\n yield\n finally:\n if GRAPH_EXECUTOR == ProfilingMode.PROFILING:\n torch._C._jit_set_profiling_executor(old_prof_exec_state)\n torch._C._jit_set_profiling_mode(old_prof_mode_state)\n\n@contextmanager\ndef enable_profiling_mode():\n old_prof_exec_state = torch._C._jit_set_profiling_executor(True)\n old_prof_mode_state = torch._C._jit_set_profiling_mode(True)\n try:\n yield\n finally:\n torch._C._jit_set_profiling_executor(old_prof_exec_state)\n torch._C._jit_set_profiling_mode(old_prof_mode_state)\n\n@contextmanager\ndef num_profiled_runs(num_runs):\n old_num_runs = torch._C._jit_set_num_profiled_runs(num_runs)\n try:\n yield\n finally:\n torch._C._jit_set_num_profiled_runs(old_num_runs)\n\nfunc_call = torch._C.ScriptFunction.__call__\nmeth_call = torch._C.ScriptMethod.__call__\n\ndef prof_callable(callable, *args, **kwargs):\n if 'profile_and_replay' in kwargs:\n del kwargs['profile_and_replay']\n if GRAPH_EXECUTOR == ProfilingMode.PROFILING:\n with enable_profiling_mode_for_profiling_tests():\n callable(*args, **kwargs)\n return callable(*args, **kwargs)\n\n return callable(*args, **kwargs)\n\ndef prof_func_call(*args, **kwargs):\n return prof_callable(func_call, *args, **kwargs)\n\ndef prof_meth_call(*args, **kwargs):\n return prof_callable(meth_call, *args, **kwargs)\n\ntorch._C.ScriptFunction.__call__ = prof_func_call\ntorch._C.ScriptMethod.__call__ = prof_meth_call\n\ndef _get_test_report_path():\n # allow users to override the test file location. We need this\n # because the distributed tests run the same test file multiple\n # times with different configurations.\n override = os.environ.get('TEST_REPORT_SOURCE_OVERRIDE')\n test_source = override if override is not None else 'python-unittest'\n return os.path.join('test-reports', test_source)\n\n\nparser = argparse.ArgumentParser(add_help=False)\nparser.add_argument('--subprocess', action='store_true',\n help='whether to run each test in a subprocess')\nparser.add_argument('--seed', type=int, default=1234)\nparser.add_argument('--accept', action='store_true')\nparser.add_argument('--ge_config', type=str)\nparser.add_argument('--repeat', type=int, default=1)\nparser.add_argument('--test_bailouts', action='store_true')\nparser.add_argument('--save-xml', nargs='?', type=str,\n const=_get_test_report_path(),\n default=_get_test_report_path() if bool(os.environ.get('IN_CIRCLECI')) else None)\nparser.add_argument('--discover-tests', action='store_true')\nparser.add_argument('--log-suffix', type=str, default=\"\")\nparser.add_argument('--run-parallel', type=int, default=1)\n\nargs, remaining = parser.parse_known_args()\nif args.ge_config == 'legacy':\n GRAPH_EXECUTOR = ProfilingMode.LEGACY\nelif args.ge_config == 'profiling':\n GRAPH_EXECUTOR = ProfilingMode.PROFILING\nelif args.ge_config == 'simple':\n GRAPH_EXECUTOR = ProfilingMode.SIMPLE\nelse:\n # infer flags based on the default settings\n GRAPH_EXECUTOR = cppProfilingFlagsToProfilingMode()\n\n\nLOG_SUFFIX = args.log_suffix\nRUN_PARALLEL = args.run_parallel\nTEST_BAILOUTS = args.test_bailouts\nTEST_DISCOVER = args.discover_tests\nTEST_IN_SUBPROCESS = args.subprocess\nTEST_SAVE_XML = args.save_xml\nREPEAT_COUNT = args.repeat\nSEED = args.seed\nif not expecttest.ACCEPT:\n expecttest.ACCEPT = args.accept\nUNITTEST_ARGS = [sys.argv[0]] + remaining\ntorch.manual_seed(SEED)\n\ndef wait_for_process(p):\n try:\n return p.wait()\n except KeyboardInterrupt:\n # Give `p` a chance to handle KeyboardInterrupt. Without this,\n # `pytest` can't print errors it collected so far upon KeyboardInterrupt.\n exit_status = p.wait(timeout=5)\n if exit_status is not None:\n return exit_status\n else:\n p.kill()\n raise\n except: # noqa E722, copied from python core library\n p.kill()\n raise\n finally:\n # Always call p.wait() to ensure exit\n p.wait()\n\ndef shell(command, cwd=None, env=None):\n sys.stdout.flush()\n sys.stderr.flush()\n # The following cool snippet is copied from Py3 core library subprocess.call\n # only the with\n # 1. `except KeyboardInterrupt` block added for SIGINT handling.\n # 2. In Py2, subprocess.Popen doesn't return a context manager, so we do\n # `p.wait()` in a `final` block for the code to be portable.\n #\n # https://github.com/python/cpython/blob/71b6c1af727fbe13525fb734568057d78cea33f3/Lib/subprocess.py#L309-L323\n assert not isinstance(command, torch._six.string_classes), \"Command to shell should be a list or tuple of tokens\"\n p = subprocess.Popen(command, universal_newlines=True, cwd=cwd, env=env)\n return wait_for_process(p)\n\n\n# Used to run the same test with different tensor types\ndef repeat_test_for_types(dtypes):\n def repeat_helper(f):\n @wraps(f)\n def call_helper(self, *args):\n for dtype in dtypes:\n with TestCase.subTest(self, dtype=dtype):\n f(self, *args, dtype=dtype)\n\n return call_helper\n return repeat_helper\n\n# Environment variable `IS_PYTORCH_CI` is set in `.jenkins/common.sh`.\nIS_PYTORCH_CI = bool(os.environ.get('IS_PYTORCH_CI'))\n\n\ndef discover_test_cases_recursively(suite_or_case):\n if isinstance(suite_or_case, unittest.TestCase):\n return [suite_or_case]\n rc = []\n for element in suite_or_case:\n rc.extend(discover_test_cases_recursively(element))\n return rc\n\ndef get_test_names(test_cases):\n return ['.'.join(case.id().split('.')[-2:]) for case in test_cases]\n\ndef chunk_list(lst, nchunks):\n return [lst[i::nchunks] for i in range(nchunks)]\n\n\ndef run_tests(argv=UNITTEST_ARGS):\n if TEST_DISCOVER:\n suite = unittest.TestLoader().loadTestsFromModule(__main__)\n test_cases = discover_test_cases_recursively(suite)\n for name in get_test_names(test_cases):\n print(name)\n elif TEST_IN_SUBPROCESS:\n suite = unittest.TestLoader().loadTestsFromModule(__main__)\n test_cases = discover_test_cases_recursively(suite)\n failed_tests = []\n for case in test_cases:\n test_case_full_name = case.id().split('.', 1)[1]\n exitcode = shell([sys.executable] + argv + [test_case_full_name])\n if exitcode != 0:\n failed_tests.append(test_case_full_name)\n\n assert len(failed_tests) == 0, \"{} unit test(s) failed:\\n\\t{}\".format(\n len(failed_tests), '\\n\\t'.join(failed_tests))\n elif RUN_PARALLEL > 1:\n suite = unittest.TestLoader().loadTestsFromModule(__main__)\n test_cases = discover_test_cases_recursively(suite)\n test_batches = chunk_list(get_test_names(test_cases), RUN_PARALLEL)\n processes = []\n for i in range(RUN_PARALLEL):\n command = [sys.executable] + argv + ['--log-suffix=-shard-{}'.format(i + 1)] + test_batches[i]\n processes.append(subprocess.Popen(command, universal_newlines=True))\n failed = False\n for p in processes:\n failed |= wait_for_process(p) != 0\n assert not failed, \"Some test shards have failed\"\n elif TEST_SAVE_XML is not None:\n # import here so that non-CI doesn't need xmlrunner installed\n import xmlrunner\n test_report_path = TEST_SAVE_XML + LOG_SUFFIX\n os.makedirs(test_report_path, exist_ok=True)\n verbose = '--verbose' in argv or '-v' in argv\n if verbose:\n print('Test results will be stored in {}'.format(test_report_path))\n unittest.main(argv=argv, testRunner=xmlrunner.XMLTestRunner(output=test_report_path, verbosity=2 if verbose else 1))\n elif REPEAT_COUNT > 1:\n for _ in range(REPEAT_COUNT):\n if not unittest.main(exit=False, argv=argv).result.wasSuccessful():\n sys.exit(-1)\n else:\n unittest.main(argv=argv)\n\nIS_WINDOWS = sys.platform == \"win32\"\nIS_MACOS = sys.platform == \"darwin\"\nIS_PPC = platform.machine() == \"ppc64le\"\n\nif IS_WINDOWS:\n @contextmanager\n def TemporaryFileName():\n # Ideally we would like to not have to manually delete the file, but NamedTemporaryFile\n # opens the file, and it cannot be opened multiple times in Windows. To support Windows,\n # close the file after creation and try to remove it manually\n f = tempfile.NamedTemporaryFile(delete=False)\n try:\n f.close()\n yield f.name\n finally:\n os.unlink(f.name)\nelse:\n @contextmanager # noqa: T484\n def TemporaryFileName():\n with tempfile.NamedTemporaryFile() as f:\n yield f.name\n\n\ndef _check_module_exists(name):\n r\"\"\"Returns if a top-level module with :attr:`name` exists *without**\n importing it. This is generally safer than try-catch block around a\n `import X`. It avoids third party libraries breaking assumptions of some of\n our tests, e.g., setting multiprocessing start method when imported\n (see librosa/#747, torchvision/#544).\n \"\"\"\n import importlib\n import importlib.util\n spec = importlib.util.find_spec(name)\n return spec is not None\n\nTEST_NUMPY = _check_module_exists('numpy')\nTEST_SCIPY = _check_module_exists('scipy')\nTEST_MKL = torch.backends.mkl.is_available()\nTEST_NUMBA = _check_module_exists('numba')\n\nTEST_DILL = _check_module_exists('dill')\n\nTEST_LIBROSA = _check_module_exists('librosa')\n\n# Python 2.7 doesn't have spawn\nNO_MULTIPROCESSING_SPAWN = os.environ.get('NO_MULTIPROCESSING_SPAWN', '0') == '1'\nTEST_WITH_ASAN = os.getenv('PYTORCH_TEST_WITH_ASAN', '0') == '1'\nTEST_WITH_TSAN = os.getenv('PYTORCH_TEST_WITH_TSAN', '0') == '1'\nTEST_WITH_UBSAN = os.getenv('PYTORCH_TEST_WITH_UBSAN', '0') == '1'\nTEST_WITH_ROCM = os.getenv('PYTORCH_TEST_WITH_ROCM', '0') == '1'\n# Enables tests that are slow to run (disabled by default)\nTEST_WITH_SLOW = os.getenv('PYTORCH_TEST_WITH_SLOW', '0') == '1'\n\n# Disables non-slow tests (these tests enabled by default)\n# This is usually used in conjunction with TEST_WITH_SLOW to\n# run *only* slow tests. (I could have done an enum, but\n# it felt a little awkward.\nTEST_SKIP_FAST = os.getenv('PYTORCH_TEST_SKIP_FAST', '0') == '1'\n\nif TEST_NUMPY:\n import numpy as np\n\n # Dict of NumPy dtype -> torch dtype (when the correspondence exists)\n numpy_to_torch_dtype_dict = {\n np.bool : torch.bool,\n np.uint8 : torch.uint8,\n np.int8 : torch.int8,\n np.int16 : torch.int16,\n np.int32 : torch.int32,\n np.int64 : torch.int64,\n np.float16 : torch.float16,\n np.float32 : torch.float32,\n np.float64 : torch.float64,\n np.complex64 : torch.complex64,\n np.complex128 : torch.complex128\n }\n\n # Dict of torch dtype -> NumPy dtype\n torch_to_numpy_dtype_dict = {value : key for (key, value) in numpy_to_torch_dtype_dict.items()}\n\nALL_TENSORTYPES = [torch.float,\n torch.double,\n torch.half]\n\n# bfloat16 bringup is currently only available on ROCm\n# ALL_TENSORTYPES2 will eventually be unified with ALL_TENSORTYPES\n# when bfloat16 bringup is complete on all platforms\nif TEST_WITH_ROCM:\n ALL_TENSORTYPES2 = [torch.float,\n torch.double,\n torch.half,\n torch.bfloat16]\nelse:\n ALL_TENSORTYPES2 = ALL_TENSORTYPES\n\ndef skipIfRocm(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if TEST_WITH_ROCM:\n raise unittest.SkipTest(\"test doesn't currently work on the ROCm stack\")\n else:\n fn(*args, **kwargs)\n return wrapper\n\n\ndef skipIfCompiledWithoutNumpy(fn):\n # Even if the numpy module is present, if `USE_NUMPY=0` is used during the\n # build, numpy tests will fail\n numpy_support = TEST_NUMPY\n if numpy_support:\n try:\n # The numpy module is present, verify that PyTorch is compiled with\n # numpy support\n torch.from_numpy(np.array([2, 2]))\n except RuntimeError:\n numpy_support = False\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if not numpy_support:\n raise unittest.SkipTest(\"PyTorch was compiled without numpy support\")\n else:\n fn(*args, **kwargs)\n return wrapper\n\ndef _test_function(fn, device):\n def run_test_function(self):\n return fn(self, device)\n return run_test_function\n\n\ndef skipIfNoLapack(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if not torch._C.has_lapack:\n raise unittest.SkipTest('PyTorch compiled without Lapack')\n else:\n fn(*args, **kwargs)\n return wrapper\n\n\ndef skipIfNotRegistered(op_name, message):\n \"\"\"Wraps the decorator to hide the import of the `core`.\n\n Args:\n op_name: Check if this op is registered in `core._REGISTERED_OPERATORS`.\n message: message to fail with.\n\n Usage:\n @skipIfNotRegistered('MyOp', 'MyOp is not linked!')\n This will check if 'MyOp' is in the caffe2.python.core\n \"\"\"\n try:\n from caffe2.python import core\n skipper = unittest.skipIf(op_name not in core._REGISTERED_OPERATORS,\n message)\n except ImportError:\n skipper = unittest.skip(\"Cannot import `caffe2.python.core`\")\n return skipper\n\n\ndef skipIfNoSciPy(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if not TEST_SCIPY:\n raise unittest.SkipTest(\"test require SciPy, but SciPy not found\")\n else:\n fn(*args, **kwargs)\n return wrapper\n\n\ndef slowTest(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if not TEST_WITH_SLOW:\n raise unittest.SkipTest(\"test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test\")\n else:\n fn(*args, **kwargs)\n wrapper.__dict__['slow_test'] = True\n return wrapper\n\n\ndef skipCUDAMemoryLeakCheckIf(condition):\n def dec(fn):\n if getattr(fn, '_do_cuda_memory_leak_check', True): # if current True\n fn._do_cuda_memory_leak_check = not condition\n return fn\n return dec\n\ndef skipCUDANonDefaultStreamIf(condition):\n def dec(fn):\n if getattr(fn, '_do_cuda_non_default_stream', True): # if current True\n fn._do_cuda_non_default_stream = not condition\n return fn\n return dec\n\ndef suppress_warnings(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n fn(*args, **kwargs)\n return wrapper\n\n\ndef get_cpu_type(type_name):\n module, name = type_name.rsplit('.', 1)\n assert module == 'torch.cuda'\n return getattr(torch, name)\n\n\ndef get_gpu_type(type_name):\n if isinstance(type_name, type):\n type_name = '{}.{}'.format(type_name.__module__, type_name.__name__)\n module, name = type_name.rsplit('.', 1)\n assert module == 'torch'\n return getattr(torch.cuda, name)\n\n\ndef to_gpu(obj, type_map=None):\n if type_map is None:\n type_map = {}\n if isinstance(obj, torch.Tensor):\n assert obj.is_leaf\n t = type_map.get(obj.type(), get_gpu_type(obj.type()))\n with torch.no_grad():\n res = obj.clone().type(t)\n res.requires_grad = obj.requires_grad\n return res\n elif torch.is_storage(obj):\n return obj.new().resize_(obj.size()).copy_(obj)\n elif isinstance(obj, list):\n return [to_gpu(o, type_map) for o in obj]\n elif isinstance(obj, tuple):\n return tuple(to_gpu(o, type_map) for o in obj)\n else:\n return deepcopy(obj)\n\n\ndef get_function_arglist(func):\n return inspect.getfullargspec(func).args\n\n\ndef set_rng_seed(seed):\n torch.manual_seed(seed)\n random.seed(seed)\n if TEST_NUMPY:\n np.random.seed(seed)\n\n\[email protected]\ndef freeze_rng_state():\n rng_state = torch.get_rng_state()\n if torch.cuda.is_available():\n cuda_rng_state = torch.cuda.get_rng_state()\n yield\n if torch.cuda.is_available():\n torch.cuda.set_rng_state(cuda_rng_state)\n torch.set_rng_state(rng_state)\n\[email protected]\ndef set_default_dtype(dtype):\n saved_dtype = torch.get_default_dtype()\n torch.set_default_dtype(dtype)\n yield\n torch.set_default_dtype(saved_dtype)\n\ndef iter_indices(tensor):\n if tensor.dim() == 0:\n return range(0)\n if tensor.dim() == 1:\n return range(tensor.size(0))\n return product(*(range(s) for s in tensor.size()))\n\n\ndef is_iterable(obj):\n try:\n iter(obj)\n return True\n except TypeError:\n return False\n\nclass CudaNonDefaultStream():\n def __enter__(self):\n # Before starting CUDA test save currently active streams on all\n # CUDA devices and set new non default streams to all CUDA devices\n # to ensure CUDA tests do not use default stream by mistake.\n beforeDevice = torch.cuda.current_device()\n self.beforeStreams = []\n for d in range(torch.cuda.device_count()):\n self.beforeStreams.append(torch.cuda.current_stream(d))\n deviceStream = torch.cuda.Stream(device=d)\n torch._C._cuda_setStream(deviceStream._cdata)\n torch._C._cuda_setDevice(beforeDevice)\n\n def __exit__(self, exec_type, exec_value, traceback):\n # After completing CUDA test load previously active streams on all\n # CUDA devices.\n beforeDevice = torch.cuda.current_device()\n for d in range(torch.cuda.device_count()):\n torch._C._cuda_setStream(self.beforeStreams[d]._cdata)\n torch._C._cuda_setDevice(beforeDevice)\n\nclass CudaMemoryLeakCheck():\n def __init__(self, testcase, name=None):\n self.name = testcase.id() if name is None else name\n self.testcase = testcase\n\n # initialize context & RNG to prevent false positive detections\n # when the test is the first to initialize those\n from torch.testing._internal.common_cuda import initialize_cuda_context_rng\n initialize_cuda_context_rng()\n\n @staticmethod\n def get_cuda_memory_usage():\n # we don't need CUDA synchronize because the statistics are not tracked at\n # actual freeing, but at when marking the block as free.\n num_devices = torch.cuda.device_count()\n gc.collect()\n return tuple(torch.cuda.memory_allocated(i) for i in range(num_devices))\n\n def __enter__(self):\n self.befores = self.get_cuda_memory_usage()\n\n def __exit__(self, exec_type, exec_value, traceback):\n # Don't check for leaks if an exception was thrown\n if exec_type is not None:\n return\n\n afters = self.get_cuda_memory_usage()\n\n for i, (before, after) in enumerate(zip(self.befores, afters)):\n self.testcase.assertEqual(\n before, after, msg='{} leaked {} bytes CUDA memory on device {}'.format(\n self.name, after - before, i))\n\n# \"min_satisfying_examples\" setting has been deprecated in hypythesis\n# 3.56.0 and removed in hypothesis 4.x\ntry:\n import hypothesis\n\n def settings(*args, **kwargs):\n if 'min_satisfying_examples' in kwargs and hypothesis.version.__version_info__ >= (3, 56, 0):\n kwargs.pop('min_satisfying_examples')\n return hypothesis.settings(*args, **kwargs)\n\n\n hypothesis.settings.register_profile(\n \"pytorch_ci\",\n settings(\n derandomize=True,\n suppress_health_check=[hypothesis.HealthCheck.too_slow],\n database=None,\n max_examples=100,\n verbosity=hypothesis.Verbosity.normal))\n hypothesis.settings.register_profile(\n \"dev\",\n settings(\n suppress_health_check=[hypothesis.HealthCheck.too_slow],\n database=None,\n max_examples=10,\n verbosity=hypothesis.Verbosity.normal))\n hypothesis.settings.register_profile(\n \"debug\",\n settings(\n suppress_health_check=[hypothesis.HealthCheck.too_slow],\n database=None,\n max_examples=1000,\n verbosity=hypothesis.Verbosity.verbose))\n\n hypothesis.settings.load_profile(\n \"pytorch_ci\" if IS_PYTORCH_CI else os.getenv('PYTORCH_HYPOTHESIS_PROFILE',\n 'dev')\n )\nexcept ImportError:\n print('Fail to import hypothesis in common_utils, tests are not derandomized')\n\ndisabled_test_from_issues = None\ndef check_disabled(test_name):\n global disabled_test_from_issues\n if disabled_test_from_issues is None:\n disabled_test_from_issues = {}\n\n def read_and_process():\n url = 'https://raw.githubusercontent.com/zdevito/pytorch_disabled_tests/master/result.json'\n contents = urlopen(url, timeout=1).read().decode('utf-8')\n the_response = json.loads(contents)\n for item in the_response['items']:\n title = item['title']\n key = 'DISABLED '\n if title.startswith(key):\n test_name = title[len(key):].strip()\n disabled_test_from_issues[test_name] = item['html_url']\n\n if not IS_SANDCASTLE and os.getenv(\"PYTORCH_RUN_DISABLED_TESTS\", \"0\") != \"1\":\n try:\n read_and_process()\n except Exception:\n print(\"Couldn't download test skip set, leaving all tests enabled...\")\n\n if test_name in disabled_test_from_issues:\n raise unittest.SkipTest(\n \"Test is disabled because an issue exists disabling it: {}\".format(disabled_test_from_issues[test_name]) +\n \" To enable set the environment variable PYTORCH_RUN_DISABLED_TESTS=1\")\n\n# Acquires the comparison dtype, required since isclose\n# requires both inputs have the same dtype, and isclose is not supported\n# for some device x dtype combinations.\n# NOTE: Remaps bfloat16 to float32 since neither the CPU or CUDA device types\n# support needed bfloat16 comparison methods.\n# NOTE: Remaps float16 to float32 on CPU since the CPU device type doesn't\n# support needed float16 comparison methods.\n# TODO: Update this once bfloat16 and float16 are better supported.\ndef get_comparison_dtype(a, b):\n # TODO: update this when promote_types supports bfloat16 and/or\n # isclose supports bfloat16.\n a_dtype = torch.float32 if a.dtype is torch.bfloat16 else a.dtype\n b_dtype = torch.float32 if b.dtype is torch.bfloat16 else b.dtype\n\n compare_dtype = torch.promote_types(a_dtype, b_dtype)\n\n # non-CUDA (CPU, for example) float16 -> float32\n # TODO: update this when isclose is implemented for CPU float16\n if (compare_dtype is torch.float16 and\n (a.device != b.device or a.device.type != 'cuda' or\n b.device.type != 'cuda')):\n compare_dtype = torch.float32\n\n return compare_dtype\n\nclass TestCase(expecttest.TestCase):\n # NOTE: \"precision\" lets classes and generated tests set minimum\n # atol values when comparing tensors. Used by @precisionOverride, for\n # example.\n # TODO: provide a better mechanism for generated tests to set rtol/atol.\n _precision: float = 0\n\n @property\n def precision(self) -> float:\n return self._precision\n\n @precision.setter\n def precision(self, prec: float) -> None:\n self._precision = prec\n\n _do_cuda_memory_leak_check = False\n _do_cuda_non_default_stream = False\n\n def __init__(self, method_name='runTest'):\n super().__init__(method_name)\n\n test_method = getattr(self, method_name, None)\n if test_method is not None:\n # Wraps the tested method if we should do CUDA memory check.\n self._do_cuda_memory_leak_check &= getattr(test_method, '_do_cuda_memory_leak_check', True)\n # FIXME: figure out the flaky -1024 anti-leaks on windows. See #8044\n if self._do_cuda_memory_leak_check and not IS_WINDOWS:\n self.wrap_with_cuda_policy(method_name, self.assertLeaksNoCudaTensors)\n\n # Wraps the tested method if we should enforce non default CUDA stream.\n self._do_cuda_non_default_stream &= getattr(test_method, '_do_cuda_non_default_stream', True)\n if self._do_cuda_non_default_stream and not IS_WINDOWS and not TEST_WITH_ROCM:\n self.wrap_with_cuda_policy(method_name, self.enforceNonDefaultStream)\n\n def assertLeaksNoCudaTensors(self, name=None):\n name = self.id() if name is None else name\n return CudaMemoryLeakCheck(self, name)\n\n def enforceNonDefaultStream(self):\n return CudaNonDefaultStream()\n\n def wrap_with_cuda_policy(self, method_name, policy):\n test_method = getattr(self, method_name)\n # the import below may initialize CUDA context, so we do it only if\n # self._do_cuda_memory_leak_check or self._do_cuda_non_default_stream\n # is True.\n from torch.testing._internal.common_cuda import TEST_CUDA\n fullname = self.id().lower() # class_name.method_name\n if TEST_CUDA and ('gpu' in fullname or 'cuda' in fullname):\n setattr(self, method_name, self.wrap_method_with_cuda_policy(test_method, policy))\n\n def wrap_method_with_cuda_policy(self, method, policy):\n # Assumes that `method` is the tested function in `self`.\n # NOTE: Python Exceptions (e.g., unittest.Skip) keeps objects in scope\n # alive, so this cannot be done in setUp and tearDown because\n # tearDown is run unconditionally no matter whether the test\n # passes or not. For the same reason, we can't wrap the `method`\n # call in try-finally and always do the check.\n @wraps(method)\n def wrapper(self, *args, **kwargs):\n with policy():\n method(*args, **kwargs)\n return types.MethodType(wrapper, self)\n\n def wrap_with_cuda_memory_check(self, method):\n return self.wrap_method_with_cuda_policy(method, self.assertLeaksNoCudaTensors)\n\n\n def setUp(self):\n\n\n if TEST_SKIP_FAST:\n if not getattr(self, self._testMethodName).__dict__.get('slow_test', False):\n raise unittest.SkipTest(\"test is fast; we disabled it with PYTORCH_TEST_SKIP_FAST\")\n check_disabled(str(self))\n\n set_rng_seed(SEED)\n\n def genSparseTensor(self, size, sparse_dim, nnz, is_uncoalesced, device='cpu'):\n # Assert not given impossible combination, where the sparse dims have\n # empty numel, but nnz > 0 makes the indices containing values.\n assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments'\n\n v_size = [nnz] + list(size[sparse_dim:])\n v = torch.randn(*v_size, device=device)\n i = torch.rand(sparse_dim, nnz, device=device)\n i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i))\n i = i.to(torch.long)\n if is_uncoalesced:\n v = torch.cat([v, torch.randn_like(v)], 0)\n i = torch.cat([i, i], 1)\n\n x = torch.sparse_coo_tensor(i, v, torch.Size(size))\n\n if not is_uncoalesced:\n x = x.coalesce()\n else:\n # FIXME: `x` is a sparse view of `v`. Currently rebase_history for\n # sparse views is not implemented, so this workaround is\n # needed for inplace operations done on `x`, e.g., copy_().\n # Remove after implementing something equivalent to CopySlice\n # for sparse views.\n # NOTE: We do clone() after detach() here because we need to be able to change size/storage of x afterwards\n x = x.detach().clone()\n return x, x._indices().clone(), x._values().clone()\n\n def safeToDense(self, t):\n r = self.safeCoalesce(t)\n return r.to_dense()\n\n def safeCoalesce(self, t):\n tc = t.coalesce()\n self.assertEqual(tc.to_dense(), t.to_dense())\n self.assertTrue(tc.is_coalesced())\n\n # Our code below doesn't work when nnz is 0, because\n # then it's a 0D tensor, not a 2D tensor.\n if t._nnz() == 0:\n self.assertEqual(t._indices(), tc._indices())\n self.assertEqual(t._values(), tc._values())\n return tc\n\n value_map = {}\n for idx, val in zip(t._indices().t(), t._values()):\n idx_tup = tuple(idx.tolist())\n if idx_tup in value_map:\n value_map[idx_tup] += val\n else:\n value_map[idx_tup] = val.clone() if isinstance(val, torch.Tensor) else val\n\n new_indices = sorted(list(value_map.keys()))\n new_values = [value_map[idx] for idx in new_indices]\n if t._values().ndimension() < 2:\n new_values = t._values().new(new_values)\n else:\n new_values = torch.stack(new_values)\n\n new_indices = t._indices().new(new_indices).t()\n tg = t.new(new_indices, new_values, t.size())\n\n self.assertEqual(tc._indices(), tg._indices())\n self.assertEqual(tc._values(), tg._values())\n\n if t.is_coalesced():\n self.assertEqual(tc._indices(), t._indices())\n self.assertEqual(tc._values(), t._values())\n\n return tg\n\n # Compares the given Torch and NumPy functions on the given tensor-like object.\n # NOTE: both torch_fn and np_fn should be functions that take a single\n # tensor (array). If the torch and/or NumPy function require additional\n # arguments then wrap the function in a lambda or pass a partial function.\n # TODO: support bfloat16 comparisons\n # TODO: add args/kwargs for passing to assertEqual (e.g. rtol, atol)\n def compare_with_numpy(self, torch_fn, np_fn, tensor_like, device=None, dtype=None):\n assert TEST_NUMPY\n assert dtype is not torch.bfloat16\n\n if isinstance(tensor_like, torch.Tensor):\n assert device is None\n assert dtype is None\n a = tensor_like.detach().cpu().numpy()\n t = tensor_like\n else:\n a = np.array(tensor_like, dtype=torch_to_numpy_dtype_dict[dtype])\n t = torch.tensor(tensor_like, device=device, dtype=dtype)\n\n np_result = np_fn(a)\n torch_result = torch_fn(t).cpu()\n\n # Converts arrays to tensors\n if isinstance(np_result, np.ndarray):\n try:\n np_result = torch.from_numpy(np_result)\n except Exception:\n # NOTE: copying an array before conversion is necessary when,\n # for example, the array has negative strides.\n np_result = torch.from_numpy(np_result.copy())\n\n self.assertEqual(np_result, torch_result)\n\n # Some analysis of tolerance by logging tests from test_torch.py can be found\n # in https://github.com/pytorch/pytorch/pull/32538.\n # dtype name : (rtol, atol)\n dtype_precisions = {\n torch.float16 : (0.001, 1e-5),\n torch.bfloat16 : (0.016, 1e-5),\n torch.float32 : (1.3e-6, 1e-5),\n torch.float64 : (1e-7, 1e-7),\n torch.complex32 : (0.001, 1e-5),\n torch.complex64 : (1.3e-6, 1e-5),\n torch.complex128 : (1e-7, 1e-7),\n }\n\n # Returns the \"default\" rtol and atol for comparing scalars or\n # tensors of the given dtypes.\n def _getDefaultRtolAndAtol(self, dtype0, dtype1):\n rtol = max(self.dtype_precisions.get(dtype0, (0, 0))[0],\n self.dtype_precisions.get(dtype1, (0, 0))[0])\n atol = max(self.dtype_precisions.get(dtype0, (0, 0))[1],\n self.dtype_precisions.get(dtype1, (0, 0))[1])\n\n return rtol, atol\n\n # Checks if two dense tensors are equal(-ish), returning (True, None)\n # when they are and (False, debug_msg) when they are not.\n # If exact_dtype is true both tensors must have the same dtype.\n # If exact_device is true both tensors must be on the same device.\n # See the \"Test Framework Tensor 'Equality'\" note for more details.\n # NOTE: tensors on different devices are moved to the CPU to be compared when\n # exact_device is False.\n # NOTE: this function checks the tensors' devices, sizes, and dtypes\n # and acquires the appropriate device, dtype, rtol and atol to compare\n # them with. It then calls _compare_tensors_internal.\n def _compareTensors(self, a, b, *, rtol: Optional[float] = None, atol=None, equal_nan=True,\n exact_dtype=True, exact_device=False) -> _compare_return_type:\n assert (atol is None) == (rtol is None)\n if not isinstance(a, torch.Tensor):\n return (False, \"argument a, {0}, to _compareTensors is not a tensor!\".format(a))\n if not isinstance(b, torch.Tensor):\n return (False, \"argument b, {0}, to _compareTensors is not a tensor!\".format(b))\n\n # Validates tensors are on the same device\n if exact_device and a.device != b.device:\n return (False, (\"Attempted to compare equality of tensors on \"\n \"different devices! Got devices {0} and \"\n \"{1}.\".format(a.device, b.device)))\n\n # Compares tensors of different devices on the CPU\n if a.device != b.device:\n a = a.cpu()\n b = b.cpu()\n\n # Checks size matches\n if a.size() != b.size():\n return (False, (\"Attempted to compare equality of tensors with \"\n \"different sizes. Got sizes {0} and {1}.\").format(a.size(), b.size()))\n\n # Checks dtype (if exact_dtype)\n if exact_dtype and a.dtype is not b.dtype:\n return (False, (\"Attempted to compare equality of tensors with \"\n \"different dtypes. Got dtypes {0} and {1}.\").format(a.dtype, b.dtype))\n\n # Acquires rtol and atol\n if rtol is None:\n rtol, atol = self._getDefaultRtolAndAtol(a.dtype, b.dtype)\n\n atol = max(atol, self.precision)\n\n # Converts to comparison dtype\n dtype = get_comparison_dtype(a, b)\n a = a.to(dtype)\n b = b.to(dtype)\n\n return _compare_tensors_internal(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)\n\n # Checks if two scalars are equal(-ish), returning (True, None)\n # when they are and (False, debug_msg) when they are not.\n # NOTE: this function just acquires rtol and atol\n # before calling _compare_scalars_internal.\n def _compareScalars(self, a, b, *,\n rtol: Optional[float] = None, atol: Optional[float] = None, equal_nan=True) -> _compare_return_type:\n # Acquires rtol and atol\n assert (atol is None) == (rtol is None)\n if rtol is None:\n if isinstance(a, complex) or isinstance(b, complex):\n rtol, atol = self._getDefaultRtolAndAtol(torch.complex64, torch.complex64)\n elif isinstance(a, float) or isinstance(b, float):\n rtol, atol = self._getDefaultRtolAndAtol(torch.float32, torch.float32)\n else:\n rtol, atol = 0, 0\n atol = max(atol, self.precision)\n\n return _compare_scalars_internal(a, b, rtol=cast(float, rtol), atol=cast(float, atol), equal_nan=equal_nan)\n\n def assertEqualIgnoreType(self, *args, **kwargs) -> None:\n # If you are seeing this function used, that means test is written wrongly\n # and deserves detailed investigation\n return self.assertEqual(*args, exact_dtype=False, **kwargs)\n\n # Compares x and y\n # TODO: default exact_device to True\n def assertEqual(self, x, y, msg: Optional[str] = None, *,\n atol: Optional[float] = None, rtol: Optional[float] = None,\n equal_nan=True, exact_dtype=True, exact_device=False) -> None:\n assert (atol is None) == (rtol is None), \"If one of atol or rtol is specified the other must be, too\"\n\n # Tensor x Number and Number x Tensor comparisons\n if isinstance(x, torch.Tensor) and isinstance(y, Number):\n self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n elif isinstance(y, torch.Tensor) and isinstance(x, Number):\n self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n # Tensor x np.bool\n elif isinstance(x, torch.Tensor) and isinstance(y, np.bool_):\n self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n elif isinstance(y, torch.Tensor) and isinstance(x, np.bool_):\n self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n # Tensor x Tensor\n elif isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor):\n super().assertEqual(x.is_sparse, y.is_sparse, msg=msg)\n super().assertEqual(x.is_quantized, y.is_quantized, msg=msg)\n if x.is_sparse:\n x = self.safeCoalesce(x)\n y = self.safeCoalesce(y)\n indices_result, debug_msg = self._compareTensors(x._indices(), y._indices(),\n rtol=rtol, atol=atol,\n equal_nan=equal_nan, exact_dtype=exact_dtype,\n exact_device=exact_device)\n\n if not indices_result and msg is None:\n assert debug_msg is not None\n msg = \"Sparse tensor indices failed to compare as equal! \" + debug_msg\n self.assertTrue(indices_result, msg=msg)\n\n values_result, debug_msg = self._compareTensors(x._values(), y._values(),\n rtol=rtol, atol=atol,\n equal_nan=equal_nan, exact_dtype=exact_dtype,\n exact_device=exact_device)\n\n if not values_result and msg is None:\n assert debug_msg is not None\n msg = \"Sparse tensor values failed to compare as equal! \" + debug_msg\n self.assertTrue(values_result, msg=msg)\n elif x.is_quantized and y.is_quantized:\n self.assertEqual(x.qscheme(), y.qscheme(), atol=atol, rtol=rtol,\n msg=msg, exact_dtype=exact_dtype,\n exact_device=exact_device)\n\n if x.qscheme() == torch.per_tensor_affine:\n self.assertEqual(x.q_scale(), y.q_scale(), atol=atol, rtol=rtol,\n msg=msg, exact_dtype=exact_dtype,\n exact_device=exact_device)\n self.assertEqual(x.q_zero_point(), y.q_zero_point(),\n atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n elif x.qscheme() == torch.per_channel_affine:\n self.assertEqual(x.q_per_channel_scales(), y.q_per_channel_scales(), atol=atol, rtol=rtol,\n msg=msg, exact_dtype=exact_dtype,\n exact_device=exact_device)\n self.assertEqual(x.q_per_channel_zero_points(), y.q_per_channel_zero_points(),\n atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n self.assertEqual(x.q_per_channel_axis(), y.q_per_channel_axis(),\n atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n\n result, debug_msg = self._compareTensors(x.int_repr().to(torch.int32),\n y.int_repr().to(torch.int32),\n atol=atol, rtol=rtol,\n exact_dtype=exact_dtype,\n exact_device=exact_device)\n\n if not result and msg is None:\n assert debug_msg is not None\n msg = \"Quantized representations failed to compare as equal! \" + debug_msg\n self.assertTrue(result, msg=msg)\n else:\n result, debug_msg = self._compareTensors(x, y, rtol=rtol, atol=atol,\n equal_nan=equal_nan, exact_dtype=exact_dtype,\n exact_device=exact_device)\n\n if not result and msg is None:\n assert debug_msg is not None\n msg = \"Tensors failed to compare as equal! \" + debug_msg\n self.assertTrue(result, msg=msg)\n elif isinstance(x, string_classes) and isinstance(y, string_classes):\n super().assertEqual(x, y, msg=msg)\n elif type(x) == set and type(y) == set:\n super().assertEqual(x, y, msg=msg)\n elif isinstance(x, dict) and isinstance(y, dict):\n if isinstance(x, OrderedDict) and isinstance(y, OrderedDict):\n self.assertEqual(x.items(), y.items(), atol=atol, rtol=rtol,\n msg=msg, exact_dtype=exact_dtype,\n exact_device=exact_device)\n else:\n self.assertEqual(set(x.keys()), set(y.keys()), atol=atol, rtol=rtol,\n msg=msg, exact_dtype=exact_dtype,\n exact_device=exact_device)\n key_list = list(x.keys())\n self.assertEqual([x[k] for k in key_list],\n [y[k] for k in key_list],\n atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n elif isinstance(x, type) and isinstance(y, type):\n # See TestTorch.test_assert_equal_generic_meta\n super().assertEqual(x, y, msg=msg)\n elif is_iterable(x) and is_iterable(y):\n super().assertEqual(len(x), len(y), msg=msg)\n for x_, y_ in zip(x, y):\n self.assertEqual(x_, y_, atol=atol, rtol=rtol, msg=msg,\n exact_dtype=exact_dtype, exact_device=exact_device)\n elif isinstance(x, bool) and isinstance(y, bool):\n self.assertTrue(x == y, msg=msg)\n\n # Scalar x Scalar\n elif isinstance(x, Number) and isinstance(y, Number):\n result, debug_msg = self._compareScalars(x, y, rtol=rtol, atol=atol,\n equal_nan=equal_nan)\n if not result and msg is None:\n assert debug_msg is not None\n msg = \"Scalars failed to compare as equal! \" + debug_msg\n self.assertTrue(result, msg=msg)\n else:\n super().assertEqual(x, y, msg=msg)\n\n def assertAlmostEqual(self, x, y, *, places=None, msg=None, delta=None):\n prec = delta\n if places:\n prec = 10**(-places)\n rtol = None if prec is None else 0\n self.assertEqual(x, y, msg=msg, atol=prec, rtol=rtol)\n\n def assertNotEqual(self, x, y, msg: Optional[str] = None, *,\n atol: Optional[float] = None, rtol: Optional[float] = None, **kwargs) -> None:\n with self.assertRaises(AssertionError, msg=msg):\n self.assertEqual(x, y, msg, atol=atol, rtol=rtol, **kwargs)\n\n def assertEqualTypeString(self, x, y) -> None:\n # This API is used simulate deprecated x.type() == y.type()\n self.assertEqual(x.device, y.device)\n self.assertEqual(x.dtype, y.dtype)\n self.assertEqual(x.is_sparse, y.is_sparse)\n\n def assertObjectIn(self, obj: Any, iterable: Iterable[Any]) -> None:\n for elem in iterable:\n if id(obj) == id(elem):\n return\n raise AssertionError(\"object not found in iterable\")\n\n # TODO: Support context manager interface\n # NB: The kwargs forwarding to callable robs the 'subname' parameter.\n # If you need it, manually apply your callable in a lambda instead.\n def assertExpectedRaises(self, exc_type, callable, *args, **kwargs):\n subname = None\n if 'subname' in kwargs:\n subname = kwargs['subname']\n del kwargs['subname']\n try:\n callable(*args, **kwargs)\n except exc_type as e:\n self.assertExpected(str(e), subname)\n return\n # Don't put this in the try block; the AssertionError will catch it\n self.fail(msg=\"Did not raise when expected to\")\n\n def assertNotWarn(self, callable, msg=''):\n r\"\"\"\n Test if :attr:`callable` does not raise a warning.\n \"\"\"\n with warnings.catch_warnings(record=True) as ws:\n warnings.simplefilter(\"always\") # allow any warning to be raised\n callable()\n self.assertTrue(len(ws) == 0, msg)\n\n @contextmanager\n def maybeWarnsRegex(self, category, regex=''):\n \"\"\"Context manager for code that *may* warn, e.g. ``TORCH_WARN_ONCE``.\n\n This filters expected warnings from the test log and fails the test if\n any unexpected warnings are caught.\n \"\"\"\n with warnings.catch_warnings(record=True) as ws:\n warnings.simplefilter(\"always\") # allow any warning to be raised\n # Ignore expected warnings\n warnings.filterwarnings(\"ignore\", message=regex, category=category)\n try:\n yield\n finally:\n if len(ws) != 0:\n msg = 'Caught unexpected warnings:\\n'\n for w in ws:\n msg += warnings.formatwarning(\n w.message, w.category, w.filename, w.lineno, w.line)\n msg += '\\n'\n self.fail(msg)\n\n def assertExpected(self, s, subname=None):\n r\"\"\"\n Test that a string matches the recorded contents of a file\n derived from the name of this test and subname. This file\n is placed in the 'expect' directory in the same directory\n as the test script. You can automatically update the recorded test\n output using --accept.\n\n If you call this multiple times in a single function, you must\n give a unique subname each time.\n \"\"\"\n if not isinstance(s, str):\n raise TypeError(\"assertExpected is strings only\")\n\n def remove_prefix(text, prefix):\n if text.startswith(prefix):\n return text[len(prefix):]\n return text\n # NB: we take __file__ from the module that defined the test\n # class, so we place the expect directory where the test script\n # lives, NOT where test/common_utils.py lives. This doesn't matter in\n # PyTorch where all test scripts are in the same directory as\n # test/common_utils.py, but it matters in onnx-pytorch\n module_id = self.__class__.__module__\n munged_id = remove_prefix(self.id(), module_id + \".\")\n test_file = os.path.realpath(sys.modules[module_id].__file__)\n expected_file = os.path.join(os.path.dirname(test_file),\n \"expect\",\n munged_id)\n\n subname_output = \"\"\n if subname:\n expected_file += \"-\" + subname\n subname_output = \" ({})\".format(subname)\n expected_file += \".expect\"\n expected = None\n\n def accept_output(update_type):\n print(\"Accepting {} for {}{}:\\n\\n{}\".format(update_type, munged_id, subname_output, s))\n with open(expected_file, 'w') as f:\n f.write(s)\n\n try:\n with open(expected_file) as f:\n expected = f.read()\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise\n elif expecttest.ACCEPT:\n return accept_output(\"output\")\n else:\n raise RuntimeError(\n (\"I got this output for {}{}:\\n\\n{}\\n\\n\"\n \"No expect file exists; to accept the current output, run:\\n\"\n \"python {} {} --accept\").format(munged_id, subname_output, s, __main__.__file__, munged_id))\n\n # a hack for JIT tests\n if IS_WINDOWS:\n expected = re.sub(r'CppOp\\[(.+?)\\]', 'CppOp[]', expected)\n s = re.sub(r'CppOp\\[(.+?)\\]', 'CppOp[]', s)\n\n # Adjust for producer_version\n expected = expected.replace(\n 'producer_version: \"XXX\"',\n 'producer_version: \"{}\"'.format(torch.onnx.producer_version)\n )\n if expecttest.ACCEPT:\n if expected != s:\n return accept_output(\"updated output\")\n else:\n if hasattr(self, \"assertMultiLineEqual\"):\n # Python 2.7 only\n # NB: Python considers lhs \"old\" and rhs \"new\".\n self.assertMultiLineEqual(expected, s)\n else:\n self.assertEqual(s, expected)\n\n def assertExpectedStripMangled(self, s, subname=None):\n s = re.sub(r'__torch__[^ ]+', '', s)\n self.assertExpected(s, subname)\n\n # returns captured stderr\n @staticmethod\n def runWithPytorchAPIUsageStderr(code):\n import subprocess\n\n env = os.environ.copy()\n env[\"PYTORCH_API_USAGE_STDERR\"] = \"1\"\n pipes = subprocess.Popen(\n [sys.executable, '-c', code],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n env=env)\n return pipes.communicate()[1].decode('ascii')\n\n if sys.version_info < (3, 2):\n # assertRegexpMatches renamed to assertRegex in 3.2\n assertRegex = unittest.TestCase.assertRegexpMatches\n # assertRaisesRegexp renamed to assertRaisesRegex in 3.2\n assertRaisesRegex = unittest.TestCase.assertRaisesRegexp\n\n if sys.version_info < (3, 5):\n # assertNotRegexpMatches renamed to assertNotRegex in 3.5\n assertNotRegex = unittest.TestCase.assertNotRegexpMatches\n\n\ndef download_file(url, binary=True):\n from urllib.parse import urlsplit\n from urllib import request, error\n\n filename = os.path.basename(urlsplit(url)[2])\n data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data'))\n path = os.path.join(data_dir, filename)\n\n if os.path.exists(path):\n return path\n try:\n data = request.urlopen(url, timeout=15).read()\n with open(path, 'wb' if binary else 'w') as f:\n f.write(data)\n return path\n except error.URLError:\n msg = \"could not download test file '{}'\".format(url)\n warnings.warn(msg, RuntimeWarning)\n raise unittest.SkipTest(msg)\n\n\ndef find_free_port():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('localhost', 0))\n sockname = sock.getsockname()\n sock.close()\n return sockname[1]\n\n# Errors that we can get in c10d initialization for which we should retry tests for.\nADDRESS_IN_USE = \"Address already in use\"\nCONNECT_TIMEOUT = \"connect() timed out.\"\n\ndef retry_on_connect_failures(func=None, connect_errors=(ADDRESS_IN_USE)):\n \"\"\"Reruns a test if the test returns a RuntimeError and the exception\n matches exactly with one of the strings in connect_errors.\"\"\"\n # This if block is executed when using this function as a decorator with arguments.\n if func is None:\n return partial(retry_on_connect_failures, connect_errors=connect_errors)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n tries_remaining = 10\n while True:\n try:\n return func(*args, **kwargs)\n except RuntimeError as error:\n if str(error) in connect_errors:\n tries_remaining -= 1\n if tries_remaining == 0:\n raise\n time.sleep(random.random())\n continue\n raise\n return wrapper\n\n\n# Decorator to retry upon certain Exceptions.\ndef retry(ExceptionToCheck, tries=3, delay=3, skip_after_retries=False):\n def deco_retry(f):\n @wraps(f)\n def f_retry(*args, **kwargs):\n mtries, mdelay = tries, delay\n while mtries > 1:\n try:\n return f(*args, **kwargs)\n except ExceptionToCheck as e:\n msg = \"%s, Retrying in %d seconds...\" % (str(e), mdelay)\n print(msg)\n time.sleep(mdelay)\n mtries -= 1\n try:\n return f(*args, **kwargs)\n except ExceptionToCheck as e:\n raise unittest.SkipTest(f\"Skipping after {tries} consecutive {str(e)}\") from e if skip_after_retries else e\n return f_retry # true decorator\n return deco_retry\n\n\n# Methods for matrix generation\n# Used in test_autograd.py and test_torch.py\ndef prod_single_zero(dim_size):\n result = torch.randn(dim_size, dim_size)\n result[0, 1] = 0\n return result\n\n\ndef random_square_matrix_of_rank(l, rank, dtype=torch.double, device='cpu'):\n assert rank <= l\n A = torch.randn(l, l, dtype=dtype, device=device)\n u, s, v = A.svd()\n for i in range(l):\n if i >= rank:\n s[i] = 0\n elif s[i] == 0:\n s[i] = 1\n return u.mm(torch.diag(s)).mm(v.transpose(0, 1))\n\n\ndef random_symmetric_matrix(l, *batches, **kwargs):\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)\n A = (A + A.transpose(-2, -1)).div_(2)\n return A\n\n\ndef random_symmetric_psd_matrix(l, *batches, **kwargs):\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)\n return torch.matmul(A, A.transpose(-2, -1))\n\n\ndef random_symmetric_pd_matrix(matrix_size, *batch_dims, **kwargs):\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n A = torch.randn(*(batch_dims + (matrix_size, matrix_size)),\n dtype=dtype, device=device)\n return torch.matmul(A, A.transpose(-2, -1)) \\\n + torch.eye(matrix_size, dtype=dtype, device=device) * 1e-5\n\n\ndef make_nonzero_det(A, sign=None, min_singular_value=0.1):\n u, s, v = A.svd()\n s.clamp_(min=min_singular_value)\n A = torch.matmul(u, torch.matmul(torch.diag_embed(s), v.transpose(-2, -1)))\n det = A.det()\n if sign is not None:\n if A.dim() == 2:\n det = det.item()\n if (det < 0) ^ (sign < 0):\n A[0, :].neg_()\n else:\n cond = ((det < 0) ^ (sign < 0)).nonzero()\n if cond.size(0) > 0:\n for i in range(cond.size(0)):\n A[list(cond[i])][0, :].neg_()\n return A\n\n\ndef random_fullrank_matrix_distinct_singular_value(matrix_size, *batch_dims,\n **kwargs):\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n silent = kwargs.get(\"silent\", False)\n if silent and not torch._C.has_lapack:\n return torch.ones(matrix_size, matrix_size, dtype=dtype, device=device)\n\n A = torch.randn(batch_dims + (matrix_size, matrix_size), dtype=dtype, device=device)\n u, _, v = A.svd()\n s = torch.arange(1., matrix_size + 1, dtype=dtype, device=device).mul_(1.0 / (matrix_size + 1)).diag()\n return u.matmul(s.expand(batch_dims + (matrix_size, matrix_size)).matmul(v.transpose(-2, -1)))\n\n\ndef random_matrix(rows, columns, *batch_dims, **kwargs):\n \"\"\"Return rectangular matrix or batches of rectangular matrices.\n\n Parameters:\n dtype - the data type\n device - the device kind\n singular - when True, the output will be singular\n \"\"\"\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n silent = kwargs.get(\"silent\", False)\n singular = kwargs.get(\"singular\", False)\n if silent and not torch._C.has_lapack:\n return torch.ones(rows, columns, dtype=dtype, device=device)\n\n A = torch.randn(batch_dims + (rows, columns), dtype=dtype, device=device)\n u, _, v = A.svd(some=False)\n s = torch.zeros(rows, columns, dtype=dtype, device=device)\n k = min(rows, columns)\n for i in range(k):\n s[i, i] = float(i + 1) / (k + 1)\n if singular:\n # make matrix singular\n s[k - 1, k - 1] = 0\n if k > 2:\n # increase the order of singularity so that the pivoting\n # in LU factorization will be non-trivial\n s[0, 0] = 0\n return u.matmul(s.expand(batch_dims + (rows, columns)).matmul(v.transpose(-2, -1)))\n\n\ndef random_lowrank_matrix(rank, rows, columns, *batch_dims, **kwargs):\n \"\"\"Return rectangular matrix or batches of rectangular matrices with\n given rank.\n \"\"\"\n B = random_matrix(rows, rank, *batch_dims, **kwargs)\n C = random_matrix(rank, columns, *batch_dims, **kwargs)\n return B.matmul(C)\n\n\ndef random_sparse_matrix(rows, columns, density=0.01, **kwargs):\n \"\"\"Return rectangular random sparse matrix within given density.\n\n The density of the result approaches to given density as the size\n of the matrix is increased and a relatively small value of density\n is specified but higher than min(rows, columns)/(rows * columns)\n for non-singular matrices.\n \"\"\"\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n singular = kwargs.get(\"singular\", False)\n\n k = min(rows, columns)\n nonzero_elements = max(min(rows, columns), int(rows * columns * density))\n\n row_indices = [i % rows for i in range(nonzero_elements)]\n column_indices = [i % columns for i in range(nonzero_elements)]\n random.shuffle(column_indices)\n indices = [row_indices, column_indices]\n values = torch.randn(nonzero_elements, dtype=dtype, device=device)\n # ensure that the diagonal dominates\n values *= torch.tensor([-float(i - j)**2 for i, j in zip(*indices)], dtype=dtype, device=device).exp()\n A = torch.sparse_coo_tensor(indices, values, (rows, columns), device=device)\n return A.coalesce()\n\n\ndef random_sparse_pd_matrix(matrix_size, density=0.01, **kwargs):\n \"\"\"Return random sparse positive-definite matrix with given density.\n\n The eigenvalues of the matrix are defined as::\n arange(1, matrix_size+1)/matrix_size\n\n Algorithm:\n A = diag(arange(1, matrix_size+1)/matrix_size)\n while <A density is smaller than required>:\n <choose random i, j in range(matrix_size), theta in [0, 2*pi]>\n R = <rotation matrix (i,j,theta)>\n A = R^T A R\n \"\"\"\n import math\n torch = kwargs.get('torch', globals()['torch'])\n dtype = kwargs.get('dtype', torch.double)\n device = kwargs.get('device', 'cpu')\n data = dict([((i, i), float(i + 1) / matrix_size)\n for i in range(matrix_size)])\n\n\n def multiply(data, N, i, j, cs, sn, left=True):\n for k in range(N):\n if left:\n ik, jk = (k, i), (k, j)\n else:\n ik, jk = (i, k), (j, k)\n aik, ajk = data.get(ik, 0), data.get(jk, 0)\n aik, ajk = cs * aik + sn * ajk, -sn * aik + cs * ajk\n if aik:\n data[ik] = aik\n else:\n data.pop(ik, None)\n if ajk:\n data[jk] = ajk\n else:\n data.pop(jk, None)\n\n target_nnz = density * matrix_size * matrix_size\n while len(data) < target_nnz:\n i = random.randint(0, matrix_size - 1)\n j = random.randint(0, matrix_size - 1)\n if i != j:\n theta = random.uniform(0, 2 * math.pi)\n cs = math.cos(theta)\n sn = math.sin(theta)\n multiply(data, matrix_size, i, j, cs, sn, left=True)\n multiply(data, matrix_size, i, j, cs, sn, left=False)\n icoords, jcoords, values = [], [], []\n for (i, j), v in sorted(data.items()):\n icoords.append(i)\n jcoords.append(j)\n values.append(v)\n indices = [icoords, jcoords]\n return torch.sparse_coo_tensor(indices, values, (matrix_size, matrix_size), dtype=dtype, device=device)\n\n\ndef do_test_dtypes(self, dtypes, layout, device):\n for dtype in dtypes:\n if dtype != torch.float16:\n out = torch.zeros((2, 3), dtype=dtype, layout=layout, device=device)\n self.assertIs(dtype, out.dtype)\n self.assertIs(layout, out.layout)\n self.assertEqual(device, out.device)\n\n\ndef do_test_empty_full(self, dtypes, layout, device):\n shape = torch.Size([2, 3])\n\n def check_value(tensor, dtype, layout, device, value, requires_grad):\n self.assertEqual(shape, tensor.shape)\n self.assertIs(dtype, tensor.dtype)\n self.assertIs(layout, tensor.layout)\n self.assertEqual(tensor.requires_grad, requires_grad)\n if tensor.is_cuda and device is not None:\n self.assertEqual(device, tensor.device)\n if value is not None:\n fill = tensor.new(shape).fill_(value)\n self.assertEqual(tensor, fill)\n\n def get_int64_dtype(dtype):\n module = '.'.join(str(dtype).split('.')[1:-1])\n if not module:\n return torch.int64\n return operator.attrgetter(module)(torch).int64\n\n default_dtype = torch.get_default_dtype()\n check_value(torch.empty(shape), default_dtype, torch.strided, -1, None, False)\n check_value(torch.full(shape, -5.), default_dtype, torch.strided, -1, None, False)\n for dtype in dtypes:\n for rg in {dtype.is_floating_point, False}:\n int64_dtype = get_int64_dtype(dtype)\n v = torch.empty(shape, dtype=dtype, device=device, layout=layout, requires_grad=rg)\n check_value(v, dtype, layout, device, None, rg)\n out = v.new()\n check_value(torch.empty(shape, out=out, device=device, layout=layout, requires_grad=rg),\n dtype, layout, device, None, rg)\n check_value(v.new_empty(shape), dtype, layout, device, None, False)\n check_value(v.new_empty(shape, dtype=int64_dtype, device=device, requires_grad=False),\n int64_dtype, layout, device, None, False)\n check_value(torch.empty_like(v), dtype, layout, device, None, False)\n check_value(torch.empty_like(v, dtype=int64_dtype, layout=layout, device=device, requires_grad=False),\n int64_dtype, layout, device, None, False)\n\n if dtype is not torch.float16 and layout != torch.sparse_coo:\n fv = 3\n v = torch.full(shape, fv, dtype=dtype, layout=layout, device=device, requires_grad=rg)\n check_value(v, dtype, layout, device, fv, rg)\n check_value(v.new_full(shape, fv + 1), dtype, layout, device, fv + 1, False)\n out = v.new()\n check_value(torch.full(shape, fv + 2, out=out, device=device, layout=layout, requires_grad=rg),\n dtype, layout, device, fv + 2, rg)\n check_value(v.new_full(shape, fv + 3, dtype=int64_dtype, device=device, requires_grad=False),\n int64_dtype, layout, device, fv + 3, False)\n check_value(torch.full_like(v, fv + 4), dtype, layout, device, fv + 4, False)\n check_value(torch.full_like(v, fv + 5,\n dtype=int64_dtype, layout=layout, device=device, requires_grad=False),\n int64_dtype, layout, device, fv + 5, False)\n\n\n\n\nTHESE_TAKE_WAY_TOO_LONG = {\n 'test_Conv3d_groups',\n 'test_conv_double_backward',\n 'test_conv_double_backward_groups',\n 'test_Conv3d_dilated',\n 'test_Conv3d_stride_padding',\n 'test_Conv3d_dilated_strided',\n 'test_Conv3d',\n 'test_Conv2d_dilated',\n 'test_ConvTranspose3d_dilated',\n 'test_ConvTranspose2d_dilated',\n 'test_snli',\n 'test_Conv2d',\n 'test_Conv2d_padding',\n 'test_ConvTranspose2d_no_bias',\n 'test_ConvTranspose2d',\n 'test_ConvTranspose3d',\n 'test_Conv2d_no_bias',\n 'test_matmul_4d_4d',\n 'test_multinomial_invalid_probs',\n}\n\n\nrunning_script_path = None\n\n\ndef set_running_script_path():\n global running_script_path\n try:\n running_file = os.path.abspath(os.path.realpath(sys.argv[0]))\n if running_file.endswith('.py'): # skip if the running file is not a script\n running_script_path = running_file\n except Exception:\n pass\n\n\ndef check_test_defined_in_running_script(test_case):\n if running_script_path is None:\n return\n test_case_class_file = os.path.abspath(os.path.realpath(inspect.getfile(test_case.__class__)))\n assert test_case_class_file == running_script_path, \"Class of loaded TestCase \\\"{}\\\" \" \\\n \"is not defined in the running script \\\"{}\\\", but in \\\"{}\\\". Did you \" \\\n \"accidentally import a unittest.TestCase from another file?\".format(\n test_case.id(), running_script_path, test_case_class_file)\n\n\ndef load_tests(loader, tests, pattern):\n set_running_script_path()\n test_suite = unittest.TestSuite()\n for test_group in tests:\n for test in test_group:\n check_test_defined_in_running_script(test)\n test_suite.addTest(test)\n return test_suite\n\n\nclass BytesIOContext(io.BytesIO):\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n pass\n\ndef _assertGradAndGradgradChecks(test_case, apply_fn, inputs):\n # call assert function rather than returning a bool since it's nicer\n # if we get whether this failed on the gradcheck or the gradgradcheck.\n test_case.assertTrue(gradcheck(apply_fn, inputs))\n test_case.assertTrue(gradgradcheck(apply_fn, inputs))\n\n\n# Using @precisionOverride specific to your test is the recommended way\n# of doing this. These are just some values that worked for test_nn.\ndtype2prec_DONTUSE = {torch.float: 1e-5,\n torch.double: 1e-5,\n torch.half: 1e-2,\n torch.bfloat16: 1e-1}\n", "#!/usr/bin/env python3\n\nfrom torch.testing._internal.distributed import ddp_under_dist_autograd_test\nfrom torch.testing._internal.common_utils import (\n run_tests,\n)\n\nclass TestDdpUnderDistAutogradWrapper(ddp_under_dist_autograd_test.TestDdpUnderDistAutograd):\n pass\n\nclass TestDdpComparison(ddp_under_dist_autograd_test.TestDdpComparison):\n pass\n\nif __name__ == \"__main__\":\n run_tests()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom future.utils import viewkeys\nfrom multiprocessing import Process, Queue\nimport numpy as np\nimport os\nimport shutil\nimport tempfile\nimport unittest\nimport time\nfrom mock import Mock\nfrom hypothesis import assume, given\nimport hypothesis.strategies as st\n\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import brew, core, cnn, data_parallel_model, dyndep, \\\n model_helper, optimizer, rnn_cell, workspace\nfrom caffe2.python.test_util import TestCase\n\n\ndyndep.InitOpsLibrary(\"@/caffe2/caffe2/distributed:file_store_handler_ops\")\n\n\nclass TemporaryDirectory:\n def __enter__(self):\n self.tmpdir = tempfile.mkdtemp()\n return self.tmpdir\n\n def __exit__(self, type, value, traceback):\n shutil.rmtree(self.tmpdir)\n\n# Note(jiayq): we are yet to find out why Travis gives out an error in gloo\n# like:\n# RuntimeError: [enforce fail at /home/travis/build/caffe2/caffe2/third_party/gloo/gloo/transport/tcp/device.cc:113] ifa != nullptr. Unable to find interface for: [127.0.1.1]\n# See for example https://travis-ci.org/caffe2/caffe2/jobs/262433866\n# As a result, we will check if this is travis, and if yes, disable it.\[email protected](os.environ.get(\"TRAVIS\"), \"DPMTest has a known issue with Travis.\")\nclass DataParallelModelTest(TestCase):\n\n def run_model(self, devices, gpu):\n '''\n Helper function for test_equiv\n '''\n def input_builder_fun(model):\n return None\n\n def model_build_fun(model, loss_scale):\n fc = model.FC(\"data\", \"fc\", 16, 1,\n (\"ConstantFill\", {}), (\"ConstantFill\", {}))\n fc_fl = model.FlattenToVec(fc, \"fc_fl\")\n sigm = model.Sigmoid(fc_fl, \"sigm\")\n sq = model.SquaredL2Distance([sigm, \"label\"], \"sq\")\n loss = model.AveragedLoss(sq, \"loss\")\n loss = model.Scale(loss, scale=loss_scale)\n\n # For testing explicit sync\n model.param_init_net.UniformFill([], [\"sync_num\"], shape=[1])\n return [loss]\n\n def add_optimizer(model):\n return optimizer.build_sgd(\n model,\n 0.1,\n policy=\"fixed\",\n max_gradient_norm=5.0,\n allow_lr_injection=True,\n )\n\n workspace.ResetWorkspace()\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"test{}\".format(devices),\n )\n data_parallel_model.Parallelize(\n model,\n input_builder_fun=input_builder_fun,\n forward_pass_builder_fun=model_build_fun,\n optimizer_builder_fun=add_optimizer,\n devices=devices,\n cpu_device=not gpu,\n shared_model=not gpu,\n combine_spatial_bn=not gpu,\n )\n data_parallel_model.AddBlobSync(model, [\"sync_num\"])\n\n # Light test for LR names\n lr_names = data_parallel_model.GetLearningRateBlobNames(model)\n self.assertGreater(len(lr_names), 0)\n\n np.random.seed(2603)\n\n # Each run has same input, independent of number of gpus\n batch_size = 64\n for i in range(0, 10):\n full_data = np.random.rand(batch_size, 16)\n full_labels = np.round(full_data[:, 0])\n batch_per_device = batch_size // len(devices)\n\n for (j, g) in enumerate(devices):\n st = j * batch_per_device\n en = st + batch_per_device\n data = full_data[st:en, :].astype(np.float32)\n labels = full_labels[st:en].astype(np.float32)\n with core.DeviceScope(core.DeviceOption(model._device_type, g)):\n workspace.FeedBlob(\n \"{}_{}/data\".format(model._device_prefix, g), data\n )\n workspace.FeedBlob(\n \"{}_{}/label\".format(model._device_prefix, g), labels\n )\n\n if i == 0:\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net)\n\n workspace.FeedBlob(\n model._device_prefix + \"_0/sync_num\",\n np.array([i * 2]).astype(np.float32),\n device_option=core.DeviceOption(model._device_type, 0))\n workspace.RunNet(model.net.Proto().name)\n\n # Test AddBlobSync\n for j in model._devices:\n sync = workspace.FetchBlob(\n model._device_prefix + \"_{}/sync_num\".format(j))[0]\n self.assertTrue(abs(sync - i * 2) < 0.01)\n\n return workspace.FetchBlob(\"{}_0/fc_w\".format(model._device_prefix))\n\n def run_test_locally(self, fn, device_option=None, **kwargs):\n # Queue for assertion errors on subprocesses\n queue = Queue()\n\n # Capture any exception thrown by the subprocess\n def run_fn(*args, **kwargs):\n try:\n if device_option is None:\n fn(*args, **kwargs)\n workspace.ResetWorkspace()\n else:\n with core.DeviceScope(device_option):\n fn(*args, **kwargs)\n workspace.ResetWorkspace()\n except Exception as ex:\n queue.put(ex)\n\n # Start N processes in the background\n procs = []\n for i in range(kwargs['comm_size']):\n kwargs['comm_rank'] = i\n proc = Process(\n target=run_fn,\n kwargs=kwargs)\n proc.start()\n procs.append(proc)\n\n # Test complete, join background processes\n while len(procs) > 0:\n proc = procs.pop(0)\n while proc.is_alive():\n proc.join(1)\n\n # Raise exception if we find any.\n # Note that the following is executed ALSO after\n # the last process was joined, so if ANY exception\n # was raised, it will be re-raised here.\n if not queue.empty():\n raise queue.get()\n\n def test_equiv(self):\n '''\n Test that the model produces exactly same results given\n total batchsize, independent of number of GPUs.\n '''\n for gpu in [True, False]:\n if gpu and (not workspace.has_gpu_support or\n workspace.NumCudaDevices() < 2):\n continue\n result_2gpus = self.run_model([0, 1], gpu=gpu)\n result_1gpus = self.run_model([0], gpu=gpu)\n\n self.assertTrue(np.allclose(result_1gpus, result_2gpus))\n\n if not gpu or workspace.NumCudaDevices() >= 4:\n result_4gpus = self.run_model(list(range(4)), gpu=gpu)\n self.assertTrue(np.allclose(result_1gpus, result_4gpus))\n\n if not gpu or workspace.NumCudaDevices() >= 8:\n result_8gpus = self.run_model(list(range(8)), gpu=gpu)\n self.assertTrue(np.allclose(result_1gpus, result_8gpus))\n\n if not gpu or workspace.NumCudaDevices() >= 16:\n result_16gpus = self.run_model(list(range(16)), gpu=gpu)\n self.assertTrue(np.allclose(result_1gpus, result_16gpus))\n\n def test_checkpoint_params(self):\n def add_input_ops(model):\n pass\n\n def add_model_ops(model, loss_scale):\n model.NHWC2NCHW(\"data\", \"data_nchw\")\n model.Conv(\"data_nchw\", 'conv1', 3, 64,\n weight_init=(\"MSRAFill\", {}), kernel=7,\n stride=2, pad=3, no_bias=0)\n model.SpatialBN('conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, is_test=False)\n model.Relu('conv1_spatbn_relu', 'conv1_spatbn_relu')\n model.MaxPool('conv1_spatbn_relu', 'pool1', kernel=3, stride=2)\n model.FC('pool1', 'fc', dim_in=(64 * 56 * 56), dim_out=100)\n model.Sigmoid('fc', 'fc_sigm')\n model.Softmax('fc_sigm', 'softmax')\n model.LabelCrossEntropy(['softmax', 'label'], 'xent')\n loss = model.AveragedLoss('xent', 'loss')\n\n # Add a duplicate param init to ensure it does not cause issues\n model.param_init_net.ConstantFill(\n [], [\"fc_w\"], shape=((64 * 56 * 56), 1000)\n )\n return [loss]\n\n def add_optimizer(model):\n optimizer.build_sgd(model, 0.1, policy=\"fixed\", momentum=0.9)\n\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"test\",\n )\n data_parallel_model.Parallelize_CPU(\n model,\n input_builder_fun=add_input_ops,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=[1, 2, 3],\n )\n\n # Only gpu_1 params should be returned (gpu_1 is the first gpu)\n checkpoint_params = data_parallel_model.GetCheckpointParams(model)\n for p in model.GetParams(\"cpu_1/\"):\n self.assertTrue(p in checkpoint_params)\n self.assertTrue(p + \"_momentum\" in checkpoint_params)\n for p in model.GetParams(\"cpu_2/\"):\n self.assertFalse(p in checkpoint_params)\n self.assertTrue(\n core.BlobReference(\"cpu_1/fc_w_momentum\") in checkpoint_params)\n for c in model.GetComputedParams(\"cpu_1/\"):\n self.assertTrue(c in checkpoint_params)\n for c in model.GetComputedParams(\"cpu_2/\"):\n self.assertFalse(c in checkpoint_params)\n self.assertFalse(core.BlobReference(\"cpu_1/data\") in checkpoint_params)\n self.assertTrue(core.BlobReference(\"optimizer_iteration\") in checkpoint_params)\n\n def test_net_conversion_and_append_net(self):\n other = model_helper.ModelHelper()\n fc1 = brew.fc(other, \"data\", \"other_fc1\", dim_in=3*227*227, dim_out=10)\n fc2 = brew.fc(other, fc1, \"other_fc2\", dim_in=10, dim_out=10)\n brew.fc(other, fc2, \"other_fc3\", dim_in=10, dim_out=10)\n\n def add_input_ops(model):\n model.net.UniformFill([], [\"data\"], shape=[4, 227, 227, 3])\n model.net.UniformFill([], [\"label\"], shape=[4])\n\n def add_model_ops(model, loss_scale):\n model.NHWC2NCHW(\"data\", \"data_nchw\")\n model.Conv(\"data_nchw\", 'conv1', 3, 64,\n weight_init=(\"MSRAFill\", {}), kernel=7,\n stride=2, pad=3, no_bias=0)\n model.SpatialBN('conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, is_test=False)\n model.Relu('conv1_spatbn_relu', 'conv1_spatbn_relu')\n model.MaxPool('conv1_spatbn_relu', 'pool1', kernel=3, stride=2)\n model.FC('pool1', 'fc', dim_in=(64 * 56 * 56), dim_out=10)\n\n # Append the net and param_init_net of the other model\n appendnet = data_parallel_model.ConvertNetForDevice(other.net)\n model.net.AppendNet(appendnet)\n\n model.param_init_net.AppendNet(\n data_parallel_model.ConvertNetForDevice(other.param_init_net))\n\n model.Sigmoid('fc', 'fc_sigm')\n model.Softmax('fc_sigm', 'softmax')\n loss = model.AveragedLoss('softmax', 'loss')\n return [loss]\n\n def add_optimizer(model):\n optimizer.build_sgd(model, 0.1, policy=\"fixed\", momentum=0.9)\n\n model = cnn.CNNModelHelper(\n order=\"NCHW\",\n name=\"test\",\n )\n data_parallel_model.Parallelize_CPU(\n model,\n input_builder_fun=add_input_ops,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=range(4)\n )\n\n # Just create and run net and confirm no exception is thrown\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net)\n workspace.RunNet(model.net)\n\n def test_synchronization_barrier(self):\n def run(comm_rank, comm_size, tmpdir):\n def add_input_ops(model):\n pass\n\n def add_model_ops(model, loss_scale):\n return []\n\n def add_optimizer(model):\n pass\n\n store_handler = \"store_handler\"\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"FileStoreHandlerCreate\",\n [],\n [store_handler],\n path=tmpdir))\n rendezvous = dict(\n kv_handler=store_handler,\n shard_id=comm_rank,\n num_shards=comm_size,\n engine='GLOO',\n )\n\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"test\",\n )\n data_parallel_model.Parallelize_CPU(\n model,\n input_builder_fun=add_input_ops,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=[1, 2, 3],\n rendezvous=rendezvous\n )\n data_parallel_model.RunInitNet(model)\n\n for _ in range(2):\n data_parallel_model.Synchronize(model)\n\n with TemporaryDirectory() as tmpdir:\n self.run_test_locally(\n run,\n comm_size=2,\n device_option=None,\n tmpdir=tmpdir)\n\n def test_pre_train_synchronization_barrier(self):\n def run(comm_rank, comm_size, tmpdir):\n def add_input_ops(model):\n pass\n\n def add_model_ops(model, loss_scale):\n return []\n\n def add_optimizer(model):\n pass\n\n workspace.ResetWorkspace()\n store_handler = \"store_handler\"\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"FileStoreHandlerCreate\",\n [],\n [store_handler],\n path=tmpdir))\n rendezvous = dict(\n kv_handler=store_handler,\n shard_id=comm_rank,\n num_shards=comm_size,\n engine='GLOO',\n )\n\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"test\",\n )\n # Set network timeout to 2 seconds, and add a 3 seconds\n # sleep for 1 host. Make sure there is no timeout on the\n # second RunNet.\n data_parallel_model._DEFAULT_TIMEOUT_SEC = 2\n data_parallel_model.Parallelize_CPU(\n model,\n input_builder_fun=add_input_ops,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=[1, 2, 3],\n rendezvous=rendezvous,\n barrier_net_timeout_sec=5\n )\n data_parallel_model.RunInitNet(model)\n data_parallel_model.RunNet(model, 2)\n if comm_rank == 0:\n time.sleep(data_parallel_model._DEFAULT_TIMEOUT_SEC)\n data_parallel_model.RunNet(model, 2)\n\n with TemporaryDirectory() as tmpdir:\n self.run_test_locally(\n run,\n comm_size=2,\n device_option=None,\n tmpdir=tmpdir)\n\n def test_device_scope_check(self):\n with self.assertRaises(AssertionError):\n with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, 0)):\n data_parallel_model.Parallelize_GPU(None, None, None)\n\n def test_net_transformer_function(self):\n devices = [1, 2, 3]\n\n def add_input_ops(model):\n model.param_init_net.UniformFill([], [\"data\"], shape=[32, 8])\n\n def add_optimizer(model):\n optimizer.build_sgd(model, 0.1)\n\n def add_model_ops(model, loss_scale):\n fc1 = brew.fc(model, \"data\", \"fc1\", dim_in=8, dim_out=8)\n return [fc1]\n\n kwargs = {\n 'input_builder_fun': add_input_ops,\n 'forward_pass_builder_fun': add_model_ops,\n 'devices': devices,\n }\n\n # assert that the transformer is called for both train and test cases\n transform = Mock()\n kwargs['net_transformer_fun'] = transform\n model = model_helper.ModelHelper(name=\"r\", init_params=False)\n data_parallel_model.Parallelize_CPU(model, **kwargs)\n self.assertTrue(transform.called)\n self.assertEqual(transform.call_count, 1)\n\n transform = Mock()\n kwargs['net_transformer_fun'] = transform\n kwargs['optimizer_builder_fun'] = add_optimizer\n model = model_helper.ModelHelper(name=\"r\", init_params=True)\n data_parallel_model.Parallelize_CPU(model, **kwargs)\n self.assertTrue(transform.called)\n self.assertEqual(transform.call_count, 1)\n\n @given(seed=st.integers(0, 65535), batch_size=st.integers(1, 20))\n def test_multi_device_bn_op_level_cpu(self, seed, batch_size):\n self._bn_check_op_level(\"cpu\", seed, batch_size)\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support.\")\n @unittest.skipIf(workspace.NumCudaDevices() < 2, \"Need at least 2 GPUs.\")\n @given(seed=st.integers(0, 65535), batch_size=st.integers(1, 20))\n def test_multi_device_bn_op_level_gpu(self, seed, batch_size):\n self._bn_check_op_level(\"gpu\", seed, batch_size)\n\n def _bn_check_op_level(self, device_type, seed, batch_size):\n '''\n Test multi device batch normalization at the operation level. This is\n done by checking the outputs of batch normalization and its gradient\n operator. We compare values produced with our manually calculated\n batch normalization values and gradients.\n '''\n devices = [0, 1]\n epsilon = 1e-3\n tolerance = 1e-3\n\n def _test_forward_pass(x, devices, device_type, scale, bias, epsilon):\n x_concat = np.concatenate(x)\n mean = np.mean(x_concat, axis=0)\n var = np.var(x_concat, axis=0)\n for device in devices:\n x_i = x[device]\n x_hat = (x_i - mean) / (np.sqrt(var + epsilon))\n expected_out = scale * x_hat + bias\n spatial_out = workspace.FetchBlob(\n \"{}_{}/bn_out\".format(device_type, device))\n rel_error = np.linalg.norm(spatial_out - expected_out) \\\n / np.linalg.norm(expected_out)\n self.assertTrue(rel_error < 0.005)\n\n def _test_backward_pass(x, devices, device_type, scale, tolerance):\n dBias_arr = []\n dY_arr = []\n dGamma_arr = []\n num_devices = len(devices)\n mean = np.array(workspace.FetchBlob(\n \"{}_0/bn_out_sm\".format(device_type)), dtype=np.float32)\n inv_var = np.array(workspace.FetchBlob(\n \"{}_0/bn_out_siv\".format(device_type)), dtype=np.float32)\n\n # dBias\n # Sum dBias values over all devices to find the average gradient\n for device in devices:\n dY_blob = workspace.FetchBlob(\n \"{}_{}/bn_out_grad\".format(device_type, device))\n dY = np.array(dY_blob, dtype=np.float32)\n dY_arr.append(dY)\n dBias_arr.append(np.array(np.sum(dY, axis=0), dtype=np.float32))\n dBias = np.sum(dBias_arr, dtype=np.float32)\n dBias_avg = dBias / num_devices\n for device in devices:\n dBiasActual = np.sum(workspace.FetchBlob(\"{}_{}/bn_out_b_grad\"\n .format(device_type, device)), dtype=np.float32)\n self.assertTrue(np.isclose([dBiasActual], [dBias], atol=tolerance))\n\n # dGamma\n # Sum dGamma values over all devices to find the average gradient\n for device in devices:\n dGamma = np.sum((x[device] - mean) * inv_var * dY_arr[device],\n axis=0, dtype=np.float32)\n dGamma_arr.append(dGamma)\n dGamma = np.sum(dGamma_arr, axis=0, dtype=np.float32)\n dGamma_avg = dGamma / num_devices\n for device in devices:\n dGammaActual = workspace.FetchBlob(\n \"{}_{}/bn_out_s_grad\".format(device_type, device))\n self.assertTrue(np.isclose([dGamma], [dGammaActual], atol=tolerance))\n\n # dX\n scale_inv_var = scale * inv_var / batch_size\n for device in devices:\n dX = scale_inv_var * (dY_arr[device] * batch_size - dBias_avg\n - (x[device] - mean) * dGamma_avg * inv_var)\n dX_actual = workspace.FetchBlob(\n \"{}_{}/tanh_grad\".format(device_type, device))\n self.assertTrue(np.isclose([dX], [dX_actual], atol=tolerance).all())\n\n def add_input_ops(model):\n for device in devices:\n data = np.random.rand(batch_size, 1, 1, 1).astype(np.float32)\n workspace.FeedBlob(\"{}_{}/data\".format(device_type, device), data)\n\n def add_model_ops(model, loss_scale):\n if device_type == \"gpu\":\n model.CopyCPUToGPU(\"data\", \"device_data\")\n model.Tanh(\"device_data\", \"tanh\")\n else:\n model.Tanh(\"data\", \"tanh\")\n model.SpatialBN(\"tanh\", \"bn_out\", 1, epsilon=epsilon, is_test=False)\n model.Sqr(\"bn_out\", \"sqr\")\n loss = model.SumElements(\"sqr\", \"loss\")\n return [loss]\n\n def add_optimizer(model):\n return optimizer.build_sgd(model, 0.1)\n\n np.random.seed(seed)\n workspace.ResetWorkspace()\n model = cnn.CNNModelHelper(\n order=\"NCHW\",\n name=\"test\"\n )\n data_parallel_model.Parallelize(\n model,\n input_builder_fun=add_input_ops,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=devices,\n cpu_device=device_type == \"cpu\",\n shared_model=False,\n combine_spatial_bn=True,\n )\n\n workspace.RunNetOnce(model.param_init_net)\n scale = workspace.FetchBlob(\"{}_0/bn_out_s\".format(device_type))\n bias = workspace.FetchBlob(\"{}_0/bn_out_b\".format(device_type))\n workspace.RunNetOnce(model.net)\n\n x = []\n for device in devices:\n x_blob = workspace.FetchBlob(\"{}_{}/tanh\".format(device_type, device))\n x_i = np.array(x_blob, dtype=np.float32)\n x.append(x_i)\n\n _test_forward_pass(x, devices, device_type, scale, bias, epsilon)\n _test_backward_pass(x, devices, device_type, scale, tolerance)\n\n @given(seed=st.integers(0, 65535), batch_size=st.integers(1, 20))\n def test_multi_device_bn_net_lvl_cpu(self, seed, batch_size):\n if batch_size % 2 == 1:\n batch_size += 1\n self._test_multi_device_bn_net_lvl(\"cpu\", seed, batch_size)\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support.\")\n @unittest.skipIf(workspace.NumCudaDevices() < 2, \"Need at least 2 GPUs.\")\n @given(seed=st.integers(0, 65535), batch_size=st.integers(1, 20))\n def test_multi_device_bn_net_lvl_gpu(self, seed, batch_size):\n if batch_size % 2 == 1:\n batch_size += 1\n self._test_multi_device_bn_net_lvl(\"gpu\", seed, batch_size)\n\n def _test_multi_device_bn_net_lvl(self, device_type, seed, batch_size):\n '''\n Test multi device batch normalization at the net level. This is done\n by verifying that the final batch normalization outputs and the\n gradient outputs from multiple devices are the same as those produced\n from a single device\n '''\n\n # Verify that the gradients calculated over multiple devices are the\n # same as the gradients calculated over one device. These values should\n # be equivalent because combine_spatial_bn sums values over all devices\n def _verify_bn_outputs(\n devices,\n device_type,\n tolerance,\n single_device_bn_out,\n two_device_bn_out_vals,\n single_device_grads,\n two_device_grads,\n ):\n two_device_bn_out = np.concatenate(two_device_bn_out_vals)\n self.assertTrue(np.isclose(\n [single_device_bn_out], [two_device_bn_out], atol=tolerance).all())\n\n # Scalar and Bias gradients should be the same across devices\n gradient_names = [\"bn_out_s_grad\", \"bn_out_b_grad\"]\n for name in gradient_names:\n expected_grad = single_device_grads[name]\n for device in devices:\n actual_grad = two_device_grads[device][name]\n self.assertTrue(\n np.isclose([actual_grad], [expected_grad], atol=tolerance))\n\n # Expected tanh_grad should be the combined tanh_grad vectors\n # across the devices\n first_grad = two_device_grads[0][\"tanh_grad\"]\n second_grad = two_device_grads[1][\"tanh_grad\"]\n actual_grad = np.concatenate([first_grad, second_grad])\n expected_grad = single_device_grads[\"tanh_grad\"]\n rel_error = np.linalg.norm(actual_grad - expected_grad) \\\n / np.linalg.norm(expected_grad)\n self.assertTrue(rel_error < 1e-3)\n\n def _create_model(multiple_devices):\n def add_input_ops_no_combine(model):\n workspace.FeedBlob(\"{}_0/data\".format(device_type), data)\n\n def add_input_ops_combine(model):\n half = int(batch_size / 2)\n workspace.FeedBlob(\"{}_0/data\".format(device_type), data[:half])\n workspace.FeedBlob(\"{}_1/data\".format(device_type), data[half:])\n\n def add_model_ops(model, loss_scale):\n if device_type == \"gpu\":\n model.CopyCPUToGPU(\"data\", \"device_data\")\n model.Tanh(\"device_data\", \"tanh\")\n else:\n model.Tanh(\"data\", \"tanh\")\n model.SpatialBN(\"tanh\", \"bn_out\", 1, epsilon=epsilon, is_test=False)\n model.Sqr(\"bn_out\", \"sqr\")\n loss = model.SumElements(\"sqr\", \"loss\")\n return [loss]\n\n def add_optimizer(model):\n return optimizer.build_sgd(model, 0.1)\n\n if multiple_devices:\n input_fun = add_input_ops_combine\n devices = [0, 1]\n combine_spatial_bn = True\n else:\n input_fun = add_input_ops_no_combine\n devices = [0]\n combine_spatial_bn = False\n model = cnn.CNNModelHelper(\n order=\"NCHW\",\n name=\"test\"\n )\n data_parallel_model.Parallelize(\n model,\n input_builder_fun=input_fun,\n forward_pass_builder_fun=add_model_ops,\n optimizer_builder_fun=add_optimizer,\n devices=devices,\n cpu_device=device_type == \"cpu\",\n shared_model=False,\n combine_spatial_bn=combine_spatial_bn,\n )\n return model\n\n devices = [0, 1]\n epsilon = 1e-3\n tolerance = 1e-3\n # We are generating random data\n np.random.seed(seed)\n data = np.random.rand(batch_size, 1, 1, 1).astype(np.float32)\n data = np.reshape(data, (batch_size, 1, 1, 1))\n\n # Get values calculated without combine_spatial_bn\n workspace.ResetWorkspace()\n model_no_combine = _create_model(multiple_devices=False)\n workspace.RunNetOnce(model_no_combine.param_init_net)\n workspace.RunNetOnce(model_no_combine.net)\n single_device_bn_out = workspace.FetchBlob(\"{}_0/bn_out\".format(device_type))\n single_device_grads = {}\n single_device_grads[\"bn_out_s_grad\"] = workspace.FetchBlob(\n \"{}_0/bn_out_s_grad\".format(device_type))\n single_device_grads[\"bn_out_b_grad\"] = workspace.FetchBlob(\n \"{}_0/bn_out_b_grad\".format(device_type))\n single_device_grads[\"tanh_grad\"] = workspace.FetchBlob(\n \"{}_0/tanh_grad\".format(device_type))\n\n # Get values calculated over multiple devices with combine_spatial_bn true\n workspace.ResetWorkspace()\n model_combine = _create_model(multiple_devices=True)\n workspace.RunNetOnce(model_combine.param_init_net)\n workspace.RunNetOnce(model_combine.net)\n two_device_bn_out_vals = []\n two_device_grads = {}\n for device in devices:\n bn_out_blob = \"{}_{}/bn_out\".format(device_type, device)\n two_device_bn_out_vals.append(workspace.FetchBlob(bn_out_blob))\n two_device_grads[device] = {}\n two_device_grads[device][\"bn_out_s_grad\"] = workspace.FetchBlob(\n \"{}_{}/bn_out_s_grad\".format(device_type, device))\n two_device_grads[device][\"bn_out_b_grad\"] = workspace.FetchBlob(\n \"{}_{}/bn_out_b_grad\".format(device_type, device))\n two_device_grads[device][\"tanh_grad\"] = workspace.FetchBlob(\n \"{}_{}/tanh_grad\".format(device_type, device))\n\n # Check to see if the combined values are equivalent\n _verify_bn_outputs(\n devices,\n device_type,\n tolerance,\n single_device_bn_out,\n two_device_bn_out_vals,\n single_device_grads,\n two_device_grads\n )\n\nclass RecurrentNetworkParallelTest(TestCase):\n\n def run_model(self, devices, gpu):\n\n '''\n Helper function for test_equiv\n '''\n def input_builder_fun(model):\n return None\n\n def model_build_fun(model, loss_scale):\n workspace.FeedBlob(\n core.ScopedBlobReference(\"seq_lengths\"),\n np.array([self.T] * self.batch_per_device, dtype=np.int32)\n )\n model.param_init_net.ConstantFill(\n [],\n \"hidden_init\",\n value=0.0,\n shape=[1, self.batch_per_device, self.hidden_dim]\n )\n model.param_init_net.ConstantFill(\n [],\n \"cell_init\",\n value=0.0,\n shape=[1, self.batch_per_device, self.hidden_dim]\n )\n\n output, _last_hidden, _, _last_state, = rnn_cell.LSTM(\n model=model,\n input_blob=\"data\",\n seq_lengths=\"seq_lengths\",\n initial_states=(\"hidden_init\", \"cell_init\"),\n dim_in=self.input_dim,\n dim_out=self.hidden_dim,\n scope=\"partest\",\n )\n\n # A silly loss function\n loss = model.AveragedLoss(\n model.Sub([output, \"target\"], \"dist\"),\n \"loss\",\n )\n loss = model.Scale(loss, \"loss_scaled\", scale=loss_scale)\n return [loss]\n\n def param_update_fun(model):\n ITER = model.Iter(\"ITER\")\n LR = model.net.LearningRate(\n [ITER],\n \"LR\",\n base_lr=(-0.1),\n policy=\"fixed\",\n )\n ONE = model.param_init_net.ConstantFill(\n [], \"ONE\", shape=[1], value=1.0,\n )\n for param in model.GetParams():\n param_grad = model.param_to_grad[param]\n model.WeightedSum([param, ONE, param_grad, LR], param)\n\n assert len(model.GetParams()) == len(model.params) // len(model._devices)\n\n workspace.ResetWorkspace()\n model = cnn.CNNModelHelper(\n name=\"recurrent_test{}\".format(devices),\n )\n\n self.T = 8\n self.batch_size = 64\n self.input_dim = 8\n self.hidden_dim = 31\n self.batch_per_device = self.batch_size // len(devices)\n\n data_parallel_model.Parallelize(\n model,\n input_builder_fun=input_builder_fun,\n forward_pass_builder_fun=model_build_fun,\n param_update_builder_fun=param_update_fun,\n devices=devices,\n optimize_gradient_memory=True,\n cpu_device=not gpu,\n )\n\n # Change all initialization to be ConstantFills so that\n # the everything is deterministic\n for op in model.param_init_net.Proto().op:\n if op.type.endswith('Fill'):\n op.type = 'ConstantFill'\n\n # Each run has same input, independent of number of gpus\n np.random.seed(20150210)\n for i in range(0, 10):\n full_data = np.random.rand(self.T, self.batch_size, self.input_dim)\n full_target = np.random.rand(\n self.T, self.batch_size, self.hidden_dim\n )\n\n for (j, g) in enumerate(devices):\n st = j * self.batch_per_device\n en = st + self.batch_per_device\n data = full_data[:, st:en, :].astype(np.float32)\n targets = full_target[:, st:en, :].astype(np.float32)\n with core.DeviceScope(core.DeviceOption(model._device_type, g)):\n workspace.FeedBlob(\n \"{}_{}/data\".format(model._device_prefix, g), data\n )\n workspace.FeedBlob(\n \"{}_{}/target\".format(model._device_prefix, g), targets\n )\n\n if i == 0:\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net)\n\n workspace.RunNet(model.net.Proto().name)\n\n return workspace.FetchBlob(\"{}_0/partest/i2h_w\".format(model._device_prefix))\n\n @unittest.skip(\"Test is flaky: https://github.com/pytorch/pytorch/issues/10322\")\n def test_equiv_recurrent(self):\n '''\n Test that the model produces exactly same results given\n total batchsize, independent of number of GPUs/CPUs.\n '''\n for gpu in [True, False]:\n if gpu and not workspace.has_gpu_support:\n continue\n result_2gpus = self.run_model([0, 1], gpu)\n result_1gpus = self.run_model([0], gpu)\n\n self.assertTrue(np.allclose(result_1gpus, result_2gpus))\n\n if not gpu or workspace.NumCudaDevices() >= 4:\n result_4gpus = self.run_model(list(range(4)), gpu)\n self.assertTrue(np.allclose(result_1gpus, result_4gpus))\n\n if not gpu or workspace.NumCudaDevices() >= 8:\n result_8gpus = self.run_model(list(range(8)), gpu)\n self.assertTrue(np.allclose(result_1gpus, result_8gpus))\n\n\[email protected](not workspace.has_gpu_support, \"No gpu support.\")\[email protected](workspace.NumCudaDevices() < 2, \"Need at least 2 GPUs.\")\nclass SparseDataParallelModelTest(TestCase):\n\n '''\n Create and run the model. We try with both storing indices for gather\n on CPU and on GPU\n '''\n def run_model(self, V, gpu_devices, cpu_indices):\n\n def input_builder_fun(model):\n return None\n\n def model_build_fun(model, loss_scale):\n if cpu_indices:\n with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):\n gathered_cpu = model.net.Gather(\n [self.vecs, 'indices'], 'gathered_cpu')\n\n gathered = model.CopyCPUToGPU(gathered_cpu, \"gathered\")\n else:\n gpu_vecs = model.param_init_net.CopyCPUToGPU(\n self.vecs, \"gpuvecs\",\n )\n model.params.append(gpu_vecs)\n gathered = model.net.Gather([gpu_vecs, 'indices'], 'gathered')\n flattened = model.Flatten(gathered, \"flattened\")\n fc = model.FC(flattened, \"fc\", 16 * 16, 1,\n (\"ConstantFill\", {}), (\"ConstantFill\", {}))\n fc_fl = model.FlattenToVec(fc, \"fc_fl\")\n sigm = model.Sigmoid(fc_fl, \"sigm\")\n sq = model.SquaredL2Distance([sigm, \"label\"], \"sq\")\n loss = model.AveragedLoss(sq, \"loss\")\n loss = model.Scale(loss, scale=loss_scale)\n return [loss]\n\n def param_update_fun(model):\n ONE = model.param_init_net.ConstantFill(\n [], \"ONE\", shape=[1], value=1.0,\n )\n LR = model.CopyCPUToGPU(self.LR, \"LR\")\n for param in model.GetParams():\n param_grad = model.param_to_grad[param]\n if not isinstance(param_grad, core.GradientSlice):\n model.WeightedSum([param, ONE, param_grad, LR], param)\n else:\n param_momentum = model.param_init_net.ConstantFill(\n [param],\n param + '_momentum',\n value=0.0,\n )\n model.net.SparseMomentumSGDUpdate(\n [\n param_grad.values,\n param_momentum,\n LR,\n param,\n param_grad.indices,\n ],\n [\n param_grad.values, param_momentum, param\n ],\n momentum=0.1,\n nesterov=0,\n )\n\n workspace.ResetWorkspace()\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"sparse_test{}\".format(gpu_devices),\n )\n\n with core.NameScope(\"cpu\"):\n with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):\n self.ITER = model.Iter(\"ITER\")\n self.LR = model.net.LearningRate(\n [self.ITER],\n \"LR\",\n base_lr=(-0.1),\n policy=\"fixed\",\n )\n self.vecs = model.param_init_net.UniformFill(\n [], \"vecs\", shape=[V, 16])\n if cpu_indices:\n model.params.append(self.vecs)\n self.ONE_CPU = model.param_init_net.ConstantFill(\n [], \"ONE_CPU\", shape=[1], value=1.0,\n )\n\n data_parallel_model.Parallelize_GPU(\n model,\n input_builder_fun=input_builder_fun,\n forward_pass_builder_fun=model_build_fun,\n param_update_builder_fun=param_update_fun,\n devices=gpu_devices,\n )\n\n # Update the vecs\n if cpu_indices:\n with core.NameScope(\"cpu\"):\n with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):\n for param in model.GetParams():\n param_grad = model.param_to_grad[param]\n model.ScatterWeightedSum([param, self.ONE_CPU,\n param_grad.indices,\n param_grad.values,\n self.LR],\n self.vecs)\n else:\n with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, 0)):\n model.CopyGPUToCPU(\"gpu_0/gpuvecs\", self.vecs)\n\n np.random.seed(2603)\n\n # Each run has same input, independent of number of gpus\n batch_size = 64\n for i in range(0, 10):\n full_indices = np.random.permutation(V)[:batch_size * 16].reshape(\n batch_size, 16\n )\n full_labels = full_indices[:, 0] % 2\n batch_per_device = batch_size // len(gpu_devices)\n\n for (j, g) in enumerate(gpu_devices):\n st = j * batch_per_device\n en = st + batch_per_device\n indices = full_indices[st:en, :].astype(np.int32)\n labels = full_labels[st:en].astype(np.float32)\n\n device_for_indices = core.DeviceOption(caffe2_pb2.CPU)\n if not cpu_indices:\n device_for_indices = core.DeviceOption(workspace.GpuDeviceType, g)\n\n with core.DeviceScope(device_for_indices):\n workspace.FeedBlob(\"gpu_{}/indices\".format(g), indices)\n\n with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, g)):\n workspace.FeedBlob(\"gpu_{}/label\".format(g), labels)\n\n if i == 0:\n workspace.RunNetOnce(model.param_init_net)\n # Force vecs to be same on all runs\n orig_vecs = np.random.rand(V, 16).astype(np.float32)\n workspace.FeedBlob(\n self.vecs,\n orig_vecs\n )\n if not cpu_indices:\n for g in gpu_devices:\n workspace.FeedBlob(\n \"gpu_{}/gpuvecs\".format(g),\n orig_vecs,\n device_option=core.DeviceOption(workspace.GpuDeviceType, g),\n )\n workspace.CreateNet(model.net)\n\n workspace.RunNet(model.net.Proto().name)\n if len(gpu_devices) == 2:\n if not cpu_indices:\n idx = workspace.FetchBlob(\"gpu_0/indices\")\n idx = list(idx.flatten())\n n = len(idx)\n nu = len(set(idx))\n assert n == nu, \"We cannot have duplicate indices\"\n\n # Sanity check to see the vecs were updated\n self.assertFalse(\n np.allclose(workspace.FetchBlob(self.vecs), orig_vecs))\n return [workspace.FetchBlob(self.vecs if cpu_indices else \"gpu_0/gpuvecs\"),\n workspace.FetchBlob(\"gpu_0/fc_w\")]\n\n def _test_equiv_sparse(self, cpu_indices):\n '''\n Test that the model produces exactly same results given\n total batchsize, independent of number of GPUs.\n '''\n V = 10000\n result_2gpus = self.run_model(V, [0, 1], cpu_indices)\n result_1gpus = self.run_model(V, [0], cpu_indices)\n\n self.assertTrue(np.allclose(result_1gpus[0], result_2gpus[0]))\n self.assertTrue(np.allclose(result_1gpus[1], result_2gpus[1]))\n\n if workspace.NumCudaDevices() >= 4:\n result_4gpus = self.run_model(V, list(range(4)), cpu_indices)\n self.assertTrue(np.allclose(result_1gpus[0], result_4gpus[0]))\n self.assertTrue(np.allclose(result_1gpus[1], result_4gpus[1]))\n\n if workspace.NumCudaDevices() >= 8:\n result_8gpus = self.run_model(V, list(range(8)), cpu_indices)\n self.assertTrue(np.allclose(result_1gpus[0], result_8gpus[0]))\n self.assertTrue(np.allclose(result_1gpus[1], result_8gpus[1]))\n\n def test_equiv_sparse(self):\n self._test_equiv_sparse(True)\n self._test_equiv_sparse(False)\n\n\[email protected](not workspace.has_gpu_support, \"No gpu support.\")\[email protected](workspace.NumGpuDevices() < 2, \"Need at least 2 GPUs.\")\nclass ParallelizeBMUFTest(TestCase):\n\n def _run_model(self, gpu_devices):\n '''\n Helper function for test_equiv\n '''\n def input_builder_fun(model):\n return None\n\n def _model_build_fun(self, model, loss_scale):\n fc = model.FC(\n \"data\", \"fc\", 16, 1, (\"ConstantFill\", {}), (\"ConstantFill\", {})\n )\n fc_fl = model.FlattenToVec(fc, \"fc_fl\")\n sigm = model.Sigmoid(fc_fl, \"sigm\")\n sq = model.SquaredL2Distance([sigm, \"label\"], \"sq\")\n loss = model.AveragedLoss(sq, \"loss\")\n loss = model.Scale(loss, scale=loss_scale)\n\n return [loss]\n\n def _param_update_fun(self, model):\n ITER = model.Iter(\"ITER\")\n LR = model.net.LearningRate(\n [ITER],\n \"LR\",\n base_lr=(-0.1),\n policy=\"fixed\",\n )\n ONE = model.param_init_net.ConstantFill(\n [], \"ONE\", shape=[1], value=1.0,\n )\n for param in model.GetParams():\n grad = model.param_to_grad[param]\n model.WeightedSum([param, ONE, grad, LR], param)\n\n def _generate_data(self, devices, device_type, device_prefix):\n np.random.seed(26)\n # Each run has same input, independent of number of gpus\n batch_size = 64\n for _ in range(0, 10):\n full_data = np.random.rand(batch_size, 16)\n full_labels = np.round(full_data[:, 0])\n batch_per_device = batch_size // len(devices)\n\n for (j, g) in enumerate(devices):\n st = j * batch_per_device\n en = st + batch_per_device\n data = full_data[st:en, :].astype(np.float32)\n labels = full_labels[st:en].astype(np.float32)\n with core.DeviceScope(core.DeviceOption(device_type, g)):\n workspace.FeedBlob(\"{}_{}/data\".format(device_prefix, g), data)\n workspace.FeedBlob(\"{}_{}/label\".format(device_prefix, g), labels)\n\n @given(\n cpu_device=st.booleans()\n )\n def test_parallelize_bmuf(self, cpu_device):\n assume(cpu_device or workspace.has_gpu_support or workspace.has_hip_support)\n\n workspace.ResetWorkspace()\n\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"test\"\n )\n devices = [0, 1]\n\n def input_builder_fun(model):\n return None\n\n if not cpu_device:\n device_type = workspace.GpuDeviceType\n device_prefix = \"gpu\"\n else:\n device_type = caffe2_pb2.CPU\n device_prefix = \"cpu\"\n self._generate_data(devices, device_type, device_prefix)\n\n data_parallel_model.Parallelize_BMUF(\n model,\n input_builder_fun,\n self._model_build_fun,\n self._param_update_fun,\n devices=devices,\n cpu_device=cpu_device\n )\n\n data_parallel_model.RunInitNet(model)\n\n # Check initial momentum params are zeros\n self.assertEqual(\n list(viewkeys(model._device_grouped_blobs)), ['fc_w', 'fc_b']\n )\n self.assertEqual(workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix)), 0)\n np.testing.assert_equal(\n workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix)),\n np.zeros(16).astype(np.float32).reshape(1, 16)\n )\n\n # Run the algorithm for one iteration to have non-zero params.\n data_parallel_model.RunNet(model, 1)\n\n # Save iteration momentum and post local update params\n v_b_ = workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix))\n v_w_ = workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix))\n\n workspace.RunNetOnce(model.net)\n\n b_0_ = workspace.FetchBlob('{}_0/fc_b'.format(device_prefix))\n w_0_ = workspace.FetchBlob('{}_0/fc_w'.format(device_prefix))\n b_1_ = workspace.FetchBlob('{}_1/fc_b'.format(device_prefix))\n w_1_ = workspace.FetchBlob('{}_1/fc_w'.format(device_prefix))\n\n # Compute block gradients.\n b_g_ = workspace.FetchBlob('{}_0/fc_b_g'.format(device_prefix))\n w_g_ = workspace.FetchBlob('{}_0/fc_w_g'.format(device_prefix))\n workspace.RunNetOnce(model._global_model_param_updates_net)\n\n g_b = (b_0_ + b_1_) / 2 - b_g_\n g_w = (w_0_ + w_1_) / 2 - w_g_\n v_b = workspace.FetchBlob('{}_0/fc_b_v'.format(device_prefix))\n v_w = workspace.FetchBlob('{}_0/fc_w_v'.format(device_prefix))\n\n w_g = workspace.FetchBlob('{}_0/fc_w_g'.format(device_prefix))\n b_g = workspace.FetchBlob('{}_0/fc_b_g'.format(device_prefix))\n w_0 = workspace.FetchBlob('{}_0/fc_w'.format(device_prefix))\n b_0 = workspace.FetchBlob('{}_0/fc_b'.format(device_prefix))\n w_1 = workspace.FetchBlob('{}_1/fc_w'.format(device_prefix))\n b_1 = workspace.FetchBlob('{}_1/fc_b'.format(device_prefix))\n\n # Check momentum update step\n np.testing.assert_equal(v_b, 0.5 * v_b_ + g_b)\n np.testing.assert_equal(v_w, 0.5 * v_w_ + g_w)\n\n np.testing.assert_equal(w_g, w_0)\n np.testing.assert_equal(w_g, w_1)\n np.testing.assert_equal(b_g, b_0)\n np.testing.assert_equal(b_g, b_1)\n\n # Check params update step\n np.testing.assert_equal(w_0, w_g_ + v_w)\n np.testing.assert_equal(b_0, b_g_ + v_b)\n\n\[email protected](not workspace.has_gpu_support, \"No gpu support.\")\[email protected](workspace.NumGpuDevices() < 2, \"Need at least 2 GPUs.\")\nclass SparseDataParallelModelTestWithSharedIndices(TestCase):\n\n '''\n Create and run the model. We try with both storing indices for gather\n on CPU and on GPU\n '''\n def run_model(self, V, gpu_devices):\n\n def input_builder_fun(model):\n return None\n\n def model_build_fun(model, loss_scale):\n gpu_vecs_gathered = []\n gpu_vecs = []\n for num, vec in enumerate(self.vecs):\n gpu_vec = model.param_init_net.CopyCPUToGPU(\n vec, 'gpuvec_{}'.format(num),\n )\n if num != 2:\n model.params.append(gpu_vec)\n gpu_vecs.append(gpu_vec)\n for num, gpu_vec in enumerate(gpu_vecs):\n gpu_vec_gathered = model.net.Gather(\n [gpu_vec, 'indices'],\n ['gpu_vec_gathered_{}'.format(num)]\n )\n gpu_vecs_gathered.append(gpu_vec_gathered)\n\n assert len(gpu_vecs_gathered) == 3\n\n fc = model.net.FC(\n [\n gpu_vecs_gathered[2],\n gpu_vecs_gathered[0],\n gpu_vecs_gathered[1],\n ],\n ['fc'],\n )\n _, loss = model.net.SoftmaxWithLoss(\n [fc, 'label'],\n ['ce_loss', 'avg_loss'],\n only_loss=True,\n )\n loss = model.Scale(loss, scale=loss_scale)\n model.net.Print(loss, [], limit=10)\n return [loss]\n\n def param_update_fun(model):\n ONE = model.param_init_net.ConstantFill(\n [], \"ONE\", shape=[1], value=1.0,\n )\n LR = model.CopyCPUToGPU(self.LR, \"LR\")\n for param in model.GetParams():\n param_grad = model.param_to_grad[param]\n if not isinstance(param_grad, core.GradientSlice):\n model.WeightedSum([param, ONE, param_grad, LR], param)\n else:\n model.net.ScatterWeightedSum(\n [\n param,\n ONE,\n param_grad.indices,\n param_grad.values,\n ONE,\n ],\n param,\n )\n\n workspace.ResetWorkspace()\n model = cnn.CNNModelHelper(\n order=\"NHWC\",\n name=\"sparse_test{}\".format(gpu_devices),\n )\n batch_size = 32\n batch_per_device = batch_size // len(gpu_devices)\n\n with core.NameScope(\"cpu\"):\n with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):\n self.ITER = model.Iter(\"ITER\")\n self.LR = model.net.LearningRate(\n [self.ITER],\n \"LR\",\n base_lr=(-0.1),\n policy=\"fixed\",\n )\n '''\n self.vecs consists of 3 big blobs on which we call Gather:\n 1) FC weights, shape=(V, 16)\n 2) FC bias, shape=(V)\n 3) FC input, shape=(batch_per_device, 16)\n '''\n self.vecs = [\n model.param_init_net.UniformFill(\n [], \"vec_{}\".format(num), shape=[V, 16])\n for num in range(2)\n ]\n self.vecs.append(\n model.param_init_net.UniformFill(\n [],\n \"vec_2\", shape=[batch_per_device, 16]\n )\n )\n self.ONE_CPU = model.param_init_net.ConstantFill(\n [], \"ONE_CPU\", shape=[1], value=1.0,\n )\n\n data_parallel_model.Parallelize_GPU(\n model,\n input_builder_fun=input_builder_fun,\n forward_pass_builder_fun=model_build_fun,\n param_update_builder_fun=param_update_fun,\n devices=gpu_devices,\n )\n\n # Update the vecs\n with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, 0)):\n for num, vec in enumerate(self.vecs[:-1]):\n model.CopyGPUToCPU(\"gpu_0/gpuvec_{}\".format(num), vec)\n\n # Each run has same input, independent of number of gpus\n for i in range(0, 10):\n np.random.seed(2603)\n full_indices = np.random.permutation(V)[:batch_size].reshape(\n batch_size\n )\n full_labels = full_indices[:] % batch_per_device\n\n for (j, g) in enumerate(gpu_devices):\n st = j * batch_per_device\n en = st + batch_per_device\n indices = full_indices[st:en].astype(np.int32)\n labels = full_labels[st:en].astype(np.int32)\n\n with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, g)):\n workspace.FeedBlob(\"gpu_{}/indices\".format(g), indices)\n workspace.FeedBlob(\"gpu_{}/label\".format(g), labels)\n\n if i == 0:\n workspace.RunNetOnce(model.param_init_net)\n # Force vecs to be same on all runs\n orig_vecs = [\n np.random.rand(V, 16).astype(np.float32),\n np.random.rand(V).astype(np.float32),\n np.random.rand(V, 16).astype(np.float32),\n ]\n for vec, orig_vec in zip(self.vecs, orig_vecs):\n workspace.FeedBlob(\n vec,\n orig_vec\n )\n for g in gpu_devices:\n for num, orig_vec in enumerate(orig_vecs):\n workspace.FeedBlob(\n \"gpu_{}/gpuvec_{}\".format(g, num),\n orig_vec,\n device_option=core.DeviceOption(\n workspace.GpuDeviceType, g),\n )\n workspace.CreateNet(model.net)\n\n workspace.RunNet(model.net.Proto().name)\n\n idx = workspace.FetchBlob('gpu_0/indices')\n grad_slices = [\n workspace.FetchBlob(\n 'gpu_{}/gpu_vec_gathered_{}_grad'.format(g, num))\n for g in gpu_devices for num in range(2)\n ]\n for grad_slice in grad_slices:\n # print (len(idx), len(grad_slice))\n assert len(idx) == len(grad_slice), (\n 'Number of indices {} is not same as number of gradient '\n 'slices {}. This might lead to illegal memory access'.format(\n len(idx), len(grad_slice)\n )\n )\n\n def test_sparse_shared_indices_gpu(self):\n '''\n Test that the model has same number of indices and gradient rows\n given total batchsize, independent of number of GPUs.\n '''\n V = 10000\n self.run_model(V, [0, 1])\n self.run_model(V, [0])\n\n if workspace.NumGpuDevices() >= 4:\n self.run_model(V, list(range(4)))\n\n if workspace.NumGpuDevices() >= 8:\n self.run_model(V, list(range(8)))\n\n\nif __name__ == \"__main__\":\n import unittest\n unittest.main()\n", "import unittest\nimport io\nimport tempfile\nimport torch\nimport torch.utils.show_pickle\n\nfrom torch.testing._internal.common_utils import IS_WINDOWS\n\nclass TestShowPickle(unittest.TestCase):\n\n @unittest.skipIf(IS_WINDOWS, \"Can't re-open temp file on Windows\")\n def test_scripted_model(self):\n class MyCoolModule(torch.nn.Module):\n def __init__(self, weight):\n super().__init__()\n self.weight = weight\n\n def forward(self, x):\n return x * self.weight\n\n m = torch.jit.script(MyCoolModule(torch.tensor([2.0])))\n\n with tempfile.NamedTemporaryFile() as tmp:\n torch.jit.save(m, tmp)\n tmp.flush()\n buf = io.StringIO()\n torch.utils.show_pickle.main([\"\", tmp.name + \"@*/data.pkl\"], output_stream=buf)\n output = buf.getvalue()\n self.assertRegex(output, \"MyCoolModule\")\n self.assertRegex(output, \"weight\")\n\n\nif __name__ == '__main__':\n unittest.main()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom caffe2.python import core\nfrom hypothesis import given\nimport caffe2.python.hypothesis_test_util as hu\nimport caffe2.python.serialized_test.serialized_test_util as serial\nimport hypothesis.strategies as st\nimport numpy as np\n\n\n# Reference implementation from detectron/lib/utils/boxes.py\ndef bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)):\n \"\"\"Forward transform that maps proposal boxes to predicted ground-truth\n boxes using bounding-box regression deltas. See bbox_transform_inv for a\n description of the weights argument.\n \"\"\"\n if boxes.shape[0] == 0:\n return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype)\n\n boxes = boxes.astype(deltas.dtype, copy=False)\n\n widths = boxes[:, 2] - boxes[:, 0] + 1.0\n heights = boxes[:, 3] - boxes[:, 1] + 1.0\n ctr_x = boxes[:, 0] + 0.5 * widths\n ctr_y = boxes[:, 1] + 0.5 * heights\n\n wx, wy, ww, wh = weights\n dx = deltas[:, 0::4] / wx\n dy = deltas[:, 1::4] / wy\n dw = deltas[:, 2::4] / ww\n dh = deltas[:, 3::4] / wh\n\n # Prevent sending too large values into np.exp()\n BBOX_XFORM_CLIP = np.log(1000. / 16.)\n dw = np.minimum(dw, BBOX_XFORM_CLIP)\n dh = np.minimum(dh, BBOX_XFORM_CLIP)\n\n pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis]\n pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis]\n pred_w = np.exp(dw) * widths[:, np.newaxis]\n pred_h = np.exp(dh) * heights[:, np.newaxis]\n\n pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype)\n # x1\n pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w\n # y1\n pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h\n # x2 (note: \"- 1\" is correct; don't be fooled by the asymmetry)\n pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - 1\n # y2 (note: \"- 1\" is correct; don't be fooled by the asymmetry)\n pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - 1\n\n return pred_boxes\n\n\n# Reference implementation from detectron/lib/utils/boxes.py\ndef clip_tiled_boxes(boxes, im_shape):\n \"\"\"Clip boxes to image boundaries. im_shape is [height, width] and boxes\n has shape (N, 4 * num_tiled_boxes).\"\"\"\n assert (\n boxes.shape[1] % 4 == 0\n ), \"boxes.shape[1] is {:d}, but must be divisible by 4.\".format(\n boxes.shape[1]\n )\n # x1 >= 0\n boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)\n # y1 >= 0\n boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)\n # x2 < im_shape[1]\n boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)\n # y2 < im_shape[0]\n boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0)\n return boxes\n\n\ndef generate_rois(roi_counts, im_dims):\n assert len(roi_counts) == len(im_dims)\n all_rois = []\n for i, num_rois in enumerate(roi_counts):\n if num_rois == 0:\n continue\n # [batch_idx, x1, y1, x2, y2]\n rois = np.random.uniform(0, im_dims[i], size=(roi_counts[i], 5)).astype(\n np.float32\n )\n rois[:, 0] = i # batch_idx\n # Swap (x1, x2) if x1 > x2\n rois[:, 1], rois[:, 3] = (\n np.minimum(rois[:, 1], rois[:, 3]),\n np.maximum(rois[:, 1], rois[:, 3]),\n )\n # Swap (y1, y2) if y1 > y2\n rois[:, 2], rois[:, 4] = (\n np.minimum(rois[:, 2], rois[:, 4]),\n np.maximum(rois[:, 2], rois[:, 4]),\n )\n all_rois.append(rois)\n if len(all_rois) > 0:\n return np.vstack(all_rois)\n return np.empty((0, 5)).astype(np.float32)\n\n\ndef bbox_transform_rotated(\n boxes,\n deltas,\n weights=(1.0, 1.0, 1.0, 1.0),\n angle_bound_on=True,\n angle_bound_lo=-90,\n angle_bound_hi=90,\n):\n \"\"\"\n Similar to bbox_transform but for rotated boxes with angle info.\n \"\"\"\n if boxes.shape[0] == 0:\n return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype)\n\n boxes = boxes.astype(deltas.dtype, copy=False)\n\n ctr_x = boxes[:, 0]\n ctr_y = boxes[:, 1]\n widths = boxes[:, 2]\n heights = boxes[:, 3]\n angles = boxes[:, 4]\n\n wx, wy, ww, wh = weights\n dx = deltas[:, 0::5] / wx\n dy = deltas[:, 1::5] / wy\n dw = deltas[:, 2::5] / ww\n dh = deltas[:, 3::5] / wh\n da = deltas[:, 4::5] * 180.0 / np.pi\n\n # Prevent sending too large values into np.exp()\n BBOX_XFORM_CLIP = np.log(1000. / 16.)\n dw = np.minimum(dw, BBOX_XFORM_CLIP)\n dh = np.minimum(dh, BBOX_XFORM_CLIP)\n\n pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype)\n pred_boxes[:, 0::5] = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis]\n pred_boxes[:, 1::5] = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis]\n pred_boxes[:, 2::5] = np.exp(dw) * widths[:, np.newaxis]\n pred_boxes[:, 3::5] = np.exp(dh) * heights[:, np.newaxis]\n\n pred_angle = da + angles[:, np.newaxis]\n if angle_bound_on:\n period = angle_bound_hi - angle_bound_lo\n assert period % 180 == 0\n pred_angle[np.where(pred_angle < angle_bound_lo)] += period\n pred_angle[np.where(pred_angle > angle_bound_hi)] -= period\n pred_boxes[:, 4::5] = pred_angle\n\n return pred_boxes\n\n\ndef clip_tiled_boxes_rotated(boxes, im_shape, angle_thresh=1.0):\n \"\"\"\n Similar to clip_tiled_boxes but for rotated boxes with angle info.\n Only clips almost horizontal boxes within angle_thresh. The rest are\n left unchanged.\n \"\"\"\n assert (\n boxes.shape[1] % 5 == 0\n ), \"boxes.shape[1] is {:d}, but must be divisible by 5.\".format(\n boxes.shape[1]\n )\n\n (H, W) = im_shape[:2]\n\n # Filter boxes that are almost upright within angle_thresh tolerance\n idx = np.where(np.abs(boxes[:, 4::5]) <= angle_thresh)\n idx5 = idx[1] * 5\n # convert to (x1, y1, x2, y2)\n x1 = boxes[idx[0], idx5] - (boxes[idx[0], idx5 + 2] - 1) / 2.0\n y1 = boxes[idx[0], idx5 + 1] - (boxes[idx[0], idx5 + 3] - 1) / 2.0\n x2 = boxes[idx[0], idx5] + (boxes[idx[0], idx5 + 2] - 1) / 2.0\n y2 = boxes[idx[0], idx5 + 1] + (boxes[idx[0], idx5 + 3] - 1) / 2.0\n # clip\n x1 = np.maximum(np.minimum(x1, W - 1), 0)\n y1 = np.maximum(np.minimum(y1, H - 1), 0)\n x2 = np.maximum(np.minimum(x2, W - 1), 0)\n y2 = np.maximum(np.minimum(y2, H - 1), 0)\n # convert back to (xc, yc, w, h)\n boxes[idx[0], idx5] = (x1 + x2) / 2.0\n boxes[idx[0], idx5 + 1] = (y1 + y2) / 2.0\n boxes[idx[0], idx5 + 2] = x2 - x1 + 1\n boxes[idx[0], idx5 + 3] = y2 - y1 + 1\n\n return boxes\n\n\ndef generate_rois_rotated(roi_counts, im_dims):\n rois = generate_rois(roi_counts, im_dims)\n # [batch_id, ctr_x, ctr_y, w, h, angle]\n rotated_rois = np.empty((rois.shape[0], 6)).astype(np.float32)\n rotated_rois[:, 0] = rois[:, 0] # batch_id\n rotated_rois[:, 1] = (rois[:, 1] + rois[:, 3]) / 2. # ctr_x = (x1 + x2) / 2\n rotated_rois[:, 2] = (rois[:, 2] + rois[:, 4]) / 2. # ctr_y = (y1 + y2) / 2\n rotated_rois[:, 3] = rois[:, 3] - rois[:, 1] + 1.0 # w = x2 - x1 + 1\n rotated_rois[:, 4] = rois[:, 4] - rois[:, 2] + 1.0 # h = y2 - y1 + 1\n rotated_rois[:, 5] = np.random.uniform(-90.0, 90.0) # angle in degrees\n return rotated_rois\n\n\nclass TestBBoxTransformOp(serial.SerializedTestCase):\n @serial.given(\n num_rois=st.integers(1, 10),\n num_classes=st.integers(1, 10),\n im_dim=st.integers(100, 600),\n skip_batch_id=st.booleans(),\n rotated=st.booleans(),\n angle_bound_on=st.booleans(),\n clip_angle_thresh=st.sampled_from([-1.0, 1.0]),\n **hu.gcs_cpu_only\n )\n def test_bbox_transform(\n self,\n num_rois,\n num_classes,\n im_dim,\n skip_batch_id,\n rotated,\n angle_bound_on,\n clip_angle_thresh,\n gc,\n dc,\n ):\n \"\"\"\n Test with all rois belonging to a single image per run.\n \"\"\"\n rois = (\n generate_rois_rotated([num_rois], [im_dim])\n if rotated\n else generate_rois([num_rois], [im_dim])\n )\n box_dim = 5 if rotated else 4\n if skip_batch_id:\n rois = rois[:, 1:]\n deltas = np.random.randn(num_rois, box_dim * num_classes).astype(np.float32)\n im_info = np.array([im_dim, im_dim, 1.0]).astype(np.float32).reshape(1, 3)\n\n def bbox_transform_ref(rois, deltas, im_info):\n boxes = rois if rois.shape[1] == box_dim else rois[:, 1:]\n im_shape = im_info[0, 0:2]\n if rotated:\n box_out = bbox_transform_rotated(\n boxes, deltas, angle_bound_on=angle_bound_on\n )\n box_out = clip_tiled_boxes_rotated(\n box_out, im_shape, angle_thresh=clip_angle_thresh\n )\n else:\n box_out = bbox_transform(boxes, deltas)\n box_out = clip_tiled_boxes(box_out, im_shape)\n return [box_out]\n\n op = core.CreateOperator(\n \"BBoxTransform\",\n [\"rois\", \"deltas\", \"im_info\"],\n [\"box_out\"],\n apply_scale=False,\n correct_transform_coords=True,\n rotated=rotated,\n angle_bound_on=angle_bound_on,\n clip_angle_thresh=clip_angle_thresh,\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[rois, deltas, im_info],\n reference=bbox_transform_ref,\n )\n\n @given(\n roi_counts=st.lists(st.integers(0, 5), min_size=1, max_size=10),\n num_classes=st.integers(1, 10),\n rotated=st.booleans(),\n angle_bound_on=st.booleans(),\n clip_angle_thresh=st.sampled_from([-1.0, 1.0]),\n **hu.gcs_cpu_only\n )\n def test_bbox_transform_batch(\n self,\n roi_counts,\n num_classes,\n rotated,\n angle_bound_on,\n clip_angle_thresh,\n gc,\n dc,\n ):\n \"\"\"\n Test with rois for multiple images in a batch\n \"\"\"\n batch_size = len(roi_counts)\n total_rois = sum(roi_counts)\n im_dims = np.random.randint(100, 600, batch_size)\n rois = (\n generate_rois_rotated(roi_counts, im_dims)\n if rotated\n else generate_rois(roi_counts, im_dims)\n )\n box_dim = 5 if rotated else 4\n deltas = np.random.randn(total_rois, box_dim * num_classes).astype(np.float32)\n im_info = np.zeros((batch_size, 3)).astype(np.float32)\n im_info[:, 0] = im_dims\n im_info[:, 1] = im_dims\n im_info[:, 2] = 1.0\n\n def bbox_transform_ref(rois, deltas, im_info):\n box_out = []\n offset = 0\n for i, num_rois in enumerate(roi_counts):\n if num_rois == 0:\n continue\n cur_boxes = rois[offset : offset + num_rois, 1:]\n cur_deltas = deltas[offset : offset + num_rois]\n im_shape = im_info[i, 0:2]\n if rotated:\n cur_box_out = bbox_transform_rotated(\n cur_boxes, cur_deltas, angle_bound_on=angle_bound_on\n )\n cur_box_out = clip_tiled_boxes_rotated(\n cur_box_out, im_shape, angle_thresh=clip_angle_thresh\n )\n else:\n cur_box_out = bbox_transform(cur_boxes, cur_deltas)\n cur_box_out = clip_tiled_boxes(cur_box_out, im_shape)\n box_out.append(cur_box_out)\n offset += num_rois\n\n if len(box_out) > 0:\n box_out = np.vstack(box_out)\n else:\n box_out = np.empty(deltas.shape).astype(np.float32)\n return [box_out, roi_counts]\n\n op = core.CreateOperator(\n \"BBoxTransform\",\n [\"rois\", \"deltas\", \"im_info\"],\n [\"box_out\", \"roi_batch_splits\"],\n apply_scale=False,\n correct_transform_coords=True,\n rotated=rotated,\n angle_bound_on=angle_bound_on,\n clip_angle_thresh=clip_angle_thresh,\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[rois, deltas, im_info],\n reference=bbox_transform_ref,\n )\n", "import torch\n\n\nt = torch.randn(2, 3)\nu = torch.randn(2, 3)\nt.copy_(u)\n(t == u).all()\n", "## @package optimizer_test_util\n# Module caffe2.python.optimizer_test_util\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport unittest\nimport numpy as np\nfrom caffe2.python import brew, core, workspace, cnn, optimizer\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python.modeling.initializers import (\n Initializer, PseudoFP16Initializer)\n\nfrom caffe2.python.model_helper import ModelHelper\n\n\nclass OptimizerTestBase(object):\n \"\"\"\n This is an abstract base class.\n Don't inherit from unittest.TestCase, and don't name it 'Test*'.\n Do, however, do these things in classes which inherit from this.\n \"\"\"\n\n def _createDense(self, dtype=core.DataType.FLOAT):\n perfect_model = np.array([2, 6, 5, 0, 1]).astype(np.float32)\n np.random.seed(123) # make test deterministic\n numpy_dtype = np.float32 if dtype == core.DataType.FLOAT else np.float16\n initializer = Initializer if dtype == core.DataType.FLOAT else \\\n PseudoFP16Initializer\n data = np.random.randint(\n 2,\n size=(20, perfect_model.size)).astype(numpy_dtype)\n label = np.dot(data, perfect_model)[:, np.newaxis]\n\n model = ModelHelper(name=\"test\", arg_scope={'order': 'NCHW'})\n out = brew.fc(\n model,\n 'data', 'fc', perfect_model.size, 1, ('ConstantFill', {}),\n ('ConstantFill', {}), axis=0,\n WeightInitializer=initializer, BiasInitializer=initializer\n )\n if dtype == core.DataType.FLOAT16:\n out = model.HalfToFloat(out, out + \"_fp32\")\n sq = model.SquaredL2Distance([out, 'label'])\n loss = model.AveragedLoss(sq, \"avg_loss\")\n grad_map = model.AddGradientOperators([loss])\n self.assertIsInstance(grad_map['fc_w'], core.BlobReference)\n return (model, perfect_model, data, label)\n\n def testDense(self):\n model, perfect_model, data, label = self._createDense()\n optimizer = self.build_optimizer(model)\n workspace.FeedBlob('data', data[0])\n workspace.FeedBlob('label', label[0])\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net, True)\n for _ in range(2000):\n idx = np.random.randint(data.shape[0])\n workspace.FeedBlob('data', data[idx])\n workspace.FeedBlob('label', label[idx])\n workspace.RunNet(model.net.Proto().name)\n\n np.testing.assert_allclose(\n perfect_model[np.newaxis, :],\n workspace.FetchBlob('fc_w'),\n atol=1e-2\n )\n self.check_optimizer(optimizer)\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support\")\n def testGPUDense(self, dtype=core.DataType.FLOAT):\n device_opt = core.DeviceOption(workspace.GpuDeviceType, 0)\n with core.DeviceScope(device_opt):\n model, _perfect_model, data, label = self._createDense(dtype)\n if dtype == core.DataType.FLOAT16:\n fc_fp32_for_host = model.HalfToFloat('fc', 'fc_fp32_for_host')\n model.CopyGPUToCPU(fc_fp32_for_host, 'fc_cpu')\n else:\n model.CopyGPUToCPU('fc', 'fc_cpu')\n workspace.FeedBlob('data', data[0])\n workspace.FeedBlob('label', label[0])\n\n # Add some CPU ops\n brew.fc(model, 'fc_cpu', 'fc2', dim_in=1, dim_out=10, axis=0)\n\n # Create optimizer in default device scope\n self.build_optimizer(model)\n\n if self._skip_gpu:\n return\n\n # Run net to see it does not crash\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net, True)\n workspace.RunNet(model.net.Proto().name)\n\n def testSparse(self):\n # to test duplicated indices we assign two indices to each weight and\n # thus each weight might count once or twice\n DUPLICATION = 2\n perfect_model = np.array([2, 6, 5, 0, 1]).astype(np.float32)\n np.random.seed(123) # make test deterministic\n data = np.random.randint(\n 2,\n size=(20, perfect_model.size * DUPLICATION)).astype(np.float32)\n label = np.dot(data, np.repeat(perfect_model, DUPLICATION))\n\n model = cnn.CNNModelHelper(\"NCHW\", name=\"test\")\n # imitate what model wrapper does\n w = model.param_init_net.ConstantFill(\n [], 'w', shape=[perfect_model.size], value=0.0)\n model.params.append(w)\n picked = model.net.Gather([w, 'indices'], 'gather')\n out = model.ReduceFrontSum(picked, 'sum')\n\n sq = model.SquaredL2Distance([out, 'label'])\n loss = model.AveragedLoss(sq, \"avg_loss\")\n grad_map = model.AddGradientOperators([loss])\n self.assertIsInstance(grad_map['w'], core.GradientSlice)\n optimizer = self.build_optimizer(model)\n\n workspace.CreateBlob('indices')\n workspace.CreateBlob('label')\n\n for indices_type in [np.int32, np.int64]:\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net, True)\n for _ in range(2000):\n idx = np.random.randint(data.shape[0])\n # transform into indices of binary features\n indices = np.repeat(np.arange(perfect_model.size),\n DUPLICATION)[data[idx] == 1]\n if indices.size == 0:\n continue\n workspace.FeedBlob(\n 'indices',\n indices.reshape((indices.size,)).astype(indices_type)\n )\n workspace.FeedBlob('label',\n np.array(label[idx]).astype(np.float32))\n workspace.RunNet(model.net.Proto().name)\n\n np.testing.assert_allclose(\n perfect_model,\n workspace.FetchBlob('w'),\n atol=1e-2\n )\n self.check_optimizer(optimizer)\n\n\nclass LRModificationTestBase(object):\n \"\"\"\n This is an abstract base class.\n Don't inherit from unittest.TestCase, and don't name it 'Test*'.\n Do, however, do these things in classes which inherit from this.\n \"\"\"\n\n def _gradient_ratio_reference(self, model, params, max_gradient_norm):\n from caffe2.python import core\n sum_squared_norms = 0.0\n for param in params:\n grad = (\n model.param_to_grad[param]\n if not isinstance(\n model.param_to_grad[param],\n core.GradientSlice,\n ) else model.param_to_grad[param].values\n )\n val = workspace.FetchBlob(grad)\n sum_squared_norms += np.power(np.linalg.norm(val), 2.0)\n global_norm = np.sqrt(sum_squared_norms)\n clip_norm = max_gradient_norm\n norm_ratio = clip_norm / np.maximum(clip_norm, global_norm)\n return norm_ratio\n\n def test_global_norm_based_gradient_clipping(self):\n max_gradient_norm = 1.0\n model, perfect_model, data, label = self._createDense()\n opt = self.build_optimizer(model, max_gradient_norm=max_gradient_norm)\n\n params = []\n for param in model.GetParams(top_scope=True):\n if param in model.param_to_grad:\n if not isinstance(\n model.param_to_grad[param],\n core.GradientSlice,\n ):\n params.append(param)\n\n workspace.FeedBlob('data', data[0])\n workspace.FeedBlob('label', label[0])\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net, True)\n self.assertIsNotNone(opt._lr_multiplier)\n\n # Run net once\n idx = np.random.randint(data.shape[0])\n workspace.FeedBlob('data', data[idx])\n workspace.FeedBlob('label', label[idx])\n workspace.RunNet(model.net.Proto().name)\n\n reference = self._gradient_ratio_reference(\n model,\n params,\n max_gradient_norm,\n )\n norm_ratio = workspace.FetchBlob(\n 'norm_clipped_grad_update/norm_ratio')\n np.testing.assert_almost_equal(norm_ratio, reference)\n self.assertTrue(\n reference < 1.0, \"Bad test, gradient not being scaled.\"\n )\n\n def test_lr_injection(self):\n model, perfect_model, data, label = self._createDense()\n opt = self.build_optimizer(\n model, max_gradient_norm=1, allow_lr_injection=True\n )\n\n workspace.FeedBlob('data', data[0])\n workspace.FeedBlob('label', label[0])\n workspace.RunNetOnce(model.param_init_net)\n workspace.CreateNet(model.net, True)\n\n # Test LR injection initialized properly\n self.assertIsNotNone(opt._lr_multiplier)\n self.assertEqual(optimizer.get_lr_injection(), 1)\n\n # Test that we're able to modify the value of the lr_injection\n optimizer.set_lr_injection(0)\n self.assertEqual(optimizer.get_lr_injection(), 0)\n\n # Test that setting the lr_injector properly propagates to the\n # lr_multiplier. Here, we have both lr_injector and norm_ratio that\n # affect the lr_multiplier\n workspace.RunNet(model.net.Proto().name)\n self.assertEqual(workspace.FetchBlob('lr_multiplier'), 0)\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom caffe2.python import core, workspace\nimport caffe2.python.hypothesis_test_util as hu\n\nfrom hypothesis import given\nimport numpy as np\n\n\nclass TestCastOp(hu.HypothesisTestCase):\n\n @given(**hu.gcs)\n def test_cast_int_float(self, gc, dc):\n data = np.random.rand(5, 5).astype(np.int32)\n # from int to float\n op = core.CreateOperator('Cast', 'data', 'data_cast', to=1, from_type=2)\n self.assertDeviceChecks(dc, op, [data], [0])\n # This is actually 0\n self.assertGradientChecks(gc, op, [data], 0, [0])\n\n @given(**hu.gcs)\n def test_cast_int_float_empty(self, gc, dc):\n data = np.random.rand(0).astype(np.int32)\n # from int to float\n op = core.CreateOperator('Cast', 'data', 'data_cast', to=1, from_type=2)\n self.assertDeviceChecks(dc, op, [data], [0])\n # This is actually 0\n self.assertGradientChecks(gc, op, [data], 0, [0])\n\n @given(data=hu.tensor(dtype=np.int32), **hu.gcs_cpu_only)\n def test_cast_int_to_string(self, data, gc, dc):\n op = core.CreateOperator(\n 'Cast', 'data', 'data_cast', to=core.DataType.STRING)\n\n def ref(data):\n ret = data.astype(dtype=np.str)\n # the string blob will be fetched as object, we feed and re-fetch\n # to mimic this.\n with hu.temp_workspace('tmp_ref_int_to_string'):\n workspace.FeedBlob('tmp_blob', ret)\n fetched_ret = workspace.FetchBlob('tmp_blob')\n return (fetched_ret, )\n\n self.assertReferenceChecks(gc, op, inputs=[data], reference=ref)\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom caffe2.python import core, workspace\nfrom hypothesis import given, assume\nimport caffe2.python.hypothesis_test_util as hu\nimport hypothesis.strategies as st\nimport numpy as np\n\nimport unittest\nimport os\n\nclass TestElementwiseOps(hu.HypothesisTestCase):\n\n @given(X=hu.tensor(dtype=np.float32), **hu.gcs)\n def test_abs(self, X, gc, dc):\n op = core.CreateOperator(\n \"Abs\",\n [\"X\"],\n [\"Y\"],\n )\n\n def abs_ref(X):\n return [np.absolute(X)]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=abs_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)\n\n @given(X=hu.tensor(dtype=np.float32), inplace=st.booleans(), **hu.gcs)\n def test_exp(self, X, inplace, gc, dc):\n op = core.CreateOperator(\n \"Exp\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"],\n )\n\n def exp_ref(X):\n return [np.exp(X)]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=exp_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6),\n seed=st.integers(0, 1000), **hu.gcs)\n def test_log(self, n, m, gc, dc, seed):\n np.random.seed(seed)\n X = np.random.rand(n, m).astype(np.float32) + 1.0\n\n def log_op(X):\n return [np.log(X)]\n\n op = core.CreateOperator(\n \"Log\",\n [\"X\"],\n [\"Z\"]\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=log_op,\n ensure_outputs_are_inferred=True,\n )\n\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2,\n ensure_outputs_are_inferred=True)\n\n @given(n=st.integers(0, 10), m=st.integers(4, 6),\n d=st.integers(2, 3), seed=st.integers(0, 1000), **hu.gcs)\n def test_powt(self, n, m, d, gc, dc, seed):\n np.random.seed(seed)\n X = np.random.rand(n, m, d).astype(np.float32) + 1.0\n Y = np.random.rand(n, m, d).astype(np.float32) + 2.0\n\n def powt_op(X, Y):\n return [np.power(X, Y)]\n\n #two gradients Y*X^(Y-1) and X^Y * ln(X)\n def powt_grad(g_out, outputs, fwd_inputs):\n [X, Y] = fwd_inputs\n Z = outputs[0]\n return ([Y * np.power(X, Y - 1), Z * np.log(X)] * g_out)\n\n op = core.CreateOperator(\n \"Pow\",\n [\"X\", \"Y\"],\n [\"Z\"]\n )\n\n self.assertReferenceChecks(device_option=gc,\n op=op,\n inputs=[X, Y],\n reference=powt_op,\n output_to_grad=\"Z\",\n grad_reference=powt_grad,\n ensure_outputs_are_inferred=True)\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6),\n seed=st.integers(0, 1000), **hu.gcs)\n def test_sqr(self, n, m, gc, dc, seed):\n np.random.seed(seed)\n X = np.random.rand(n, m).astype(np.float32)\n\n def sqr_op(X):\n return [np.square(X)]\n\n op = core.CreateOperator(\n \"Sqr\",\n [\"X\"],\n [\"Z\"]\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=sqr_op,\n ensure_outputs_are_inferred=True,\n )\n\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2,\n ensure_outputs_are_inferred=True)\n\n @given(\n X=hu.tensor(\n elements=hu.floats(0.1, 10),\n # allow empty tensor\n min_value=0),\n inplace=st.booleans(),\n **hu.gcs\n )\n def test_sqrt(self, X, inplace, gc, dc):\n def sqrt_op(X):\n return [np.sqrt(X)]\n\n op = core.CreateOperator(\n \"Sqrt\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"]\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=sqrt_op,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n # stepsize need to be smaller than the possible minimum X, so the\n # sqrt is well defined\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)\n\n @given(X=hu.tensor(dtype=np.float32), inplace=st.booleans(), **hu.gcs)\n def test_softsign(self, X, inplace, gc, dc):\n op = core.CreateOperator(\n \"Softsign\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"],\n )\n\n def softsign_ref(X):\n return [X / (1.0 + np.absolute(X))]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=softsign_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n if not inplace:\n self.assertGradientChecks(\n gc, op, [X], 0, [0],\n ensure_outputs_are_inferred=True,\n )\n\n @given(X=hu.tensor(elements=hu.floats(0.1, 10.0), dtype=np.float32),\n inplace=st.booleans(), **hu.gcs)\n def test_rsqrt(self, X, inplace, gc, dc):\n op = core.CreateOperator(\n \"Rsqrt\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"],\n )\n\n def rsqrt_ref(X):\n return [1.0 / np.sqrt(X)]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=rsqrt_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=5e-3,\n ensure_outputs_are_inferred=True,\n )\n\n @given(X=hu.tensor(dtype=np.float32), **hu.gcs)\n def test_cube(self, X, gc, dc):\n op = core.CreateOperator(\n \"Cube\",\n [\"X\"],\n [\"Y\"],\n )\n\n def cube_ref(X):\n return [np.power(X, 3)]\n\n def cube_grad_ref(g_out, outputs, fwd_inputs):\n dY = g_out\n [X] = fwd_inputs\n return [dY * np.square(X) * 3]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=cube_ref,\n output_to_grad=\"Y\",\n grad_reference=cube_grad_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n\n @given(X=hu.tensor(dtype=np.float32), in_place=st.booleans(), **hu.gcs)\n def test_cbrt(self, X, in_place, gc, dc):\n op = core.CreateOperator(\n \"Cbrt\",\n [\"X\"],\n [\"X\"] if in_place else [\"Y\"],\n )\n\n def cbrt_ref(X):\n return [np.cbrt(X)]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=cbrt_ref,\n ensure_outputs_are_inferred=True,\n )\n\n @given(X=hu.tensor(elements=hu.floats(1.0, 10.0), dtype=np.float32),\n in_place=st.booleans(), **hu.gcs)\n def test_cbrt_grad(self, X, in_place, gc, dc):\n op = core.CreateOperator(\n \"Cbrt\",\n [\"X\"],\n [\"X\"] if in_place else [\"Y\"],\n )\n\n self.assertGradientChecks(\n gc, op, [X], 0, [0],\n ensure_outputs_are_inferred=True,\n )\n self.assertGradientChecks(\n gc, op, [-X], 0, [0],\n ensure_outputs_are_inferred=True,\n )\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6),\n seed=st.integers(0, 1000), **hu.gcs)\n def test_swish(self, n, m, gc, dc, seed):\n np.random.seed(seed)\n X = np.random.rand(n, m).astype(np.float32)\n\n def swish(X):\n return [np.divide(X, (1. + np.exp(-X)))]\n\n op = core.CreateOperator(\n \"Swish\",\n [\"X\"],\n [\"Z\"]\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=swish,\n ensure_outputs_are_inferred=True,\n )\n\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2,\n ensure_outputs_are_inferred=True)\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6),\n seed=st.integers(0, 1000), **hu.gcs)\n def test_swish_gradient_inplace(self, n, m, gc, dc, seed):\n np.random.seed(seed)\n\n def swish(X):\n return [np.divide(X, (1. + np.exp(-X)))]\n\n def swish_gradient(X, Y, dY):\n return [dY * (Y + np.divide(1. - Y, 1. + np.exp(-X)))]\n\n X = np.random.rand(n, m).astype(np.float32)\n Y = swish(X)[0]\n dY = np.random.rand(n, m).astype(np.float32)\n op = core.CreateOperator(\n \"SwishGradient\",\n [\"X\", \"Y\", \"grad\"],\n \"grad\"\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X, Y, dY],\n reference=swish_gradient,\n )\n\n @given(X=hu.tensor(dtype=np.float32), inplace=st.booleans(),\n engine=st.sampled_from([\"\", \"CUDNN\"]), **hu.gcs)\n def test_sigmoid(self, X, inplace, engine, gc, dc):\n op = core.CreateOperator(\n \"Sigmoid\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"],\n engine=engine,\n )\n\n def sigmoid_ref(X):\n return [1.0 / (1.0 + np.exp(-X))]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=sigmoid_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)\n\n @given(X=hu.tensor(dtype=np.float32),\n inplace=st.booleans(),\n alpha=st.floats(min_value=-100.0, max_value=100.0),\n beta=st.floats(min_value=-100.0, max_value=100.0),\n engine=st.sampled_from([\"\"]),\n **hu.gcs)\n def test_hard_sigmoid(self, X, inplace, alpha, beta, engine, gc, dc):\n # Prevent alpha and beta from mutually being 0 to avoid a division\n # error when adjusting our inputs\n assume(alpha != 0.0 or beta != 0.0)\n op = core.CreateOperator(\n \"HardSigmoid\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"],\n alpha=alpha,\n beta=beta,\n engine=engine,\n )\n\n def hard_sigmoid_ref(X):\n return [np.minimum(1.0, np.maximum(0.0, X * alpha + beta))]\n\n # Adjust inputs to avoid differentitating at inflection points\n if abs(alpha) > 0.001:\n Y = X * alpha + beta\n Y += 0.04 * np.sign(Y)\n Y[Y == 0.0] += 0.1\n Y[Y == 1.0] -= 0.1\n X = (Y - beta) / alpha\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=hard_sigmoid_ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2,\n ensure_outputs_are_inferred=True)\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6), **hu.gcs)\n def test_eq(self, n, m, gc, dc):\n # Set broadcast and no axis, i.e. broadcasting last dimensions.\n X = np.random.randint(2, size=(n, m))\n Y = np.random.randint(2, size=(n, m))\n op = core.CreateOperator(\"EQ\", [\"X\", \"Y\"], \"out\", broadcast=1)\n\n def eq(X, Y):\n return [X == Y]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X, Y],\n reference=eq,\n ensure_outputs_are_inferred=True,\n )\n\n workspace.FeedBlob('X', X)\n workspace.FeedBlob('Y', Y)\n\n net = core.Net(\"batch_bucket_one_hot_test\")\n result = net.EQ([\"X\", \"Y\"], 1)\n (shapes, types) = workspace.InferShapesAndTypes([net])\n workspace.RunNetOnce(net)\n\n self.assertEqual(shapes[result], list(workspace.blobs[result].shape))\n self.assertEqual(shapes[result], list(X.shape))\n self.assertEqual(types[result], core.DataType.BOOL)\n\n @given(n=st.integers(0, 6), m=st.integers(4, 6), **hu.gcs)\n def test_eq_bcast(self, n, m, gc, dc):\n # Set broadcast and no axis, i.e. broadcasting last dimensions.\n X = np.random.randint(2, size=(n, m))\n Y = np.random.randint(2, size=(m,))\n op = core.CreateOperator(\"EQ\", [\"X\", \"Y\"], \"out\", broadcast=1)\n\n def eq(X, Y):\n return [X == Y]\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X, Y],\n reference=eq,\n ensure_outputs_are_inferred=True,\n )\n\n workspace.FeedBlob('X', X)\n workspace.FeedBlob('Y', Y)\n\n net = core.Net(\"eq_bast\")\n result = net.EQ([\"X\", \"Y\"], 1, broadcast=1)\n (shapes, types) = workspace.InferShapesAndTypes([net])\n workspace.RunNetOnce(net)\n self.assertTrue(str(result) in shapes)\n self.assertEqual(shapes[result], list(workspace.blobs[result].shape))\n self.assertEqual(shapes[result], list(X.shape))\n self.assertEqual(types[result], core.DataType.BOOL)\n\n net_2 = core.Net(\"eq_bast_invalid\")\n result_2 = net_2.EQ([\"X\", \"Y\"], 1)\n (shapes, types) = workspace.InferShapesAndTypes([net])\n self.assertTrue(str(result_2) not in shapes)\n\n def _run_single_test(\n self, op, ref, A, B, reverse_inputs, test_grad, gc, dc):\n inputs = [A, B]\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=inputs,\n reference=ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, inputs, [0])\n if test_grad:\n for i in range(len(inputs)):\n self.assertGradientChecks(\n gc, op, inputs, i, [0],\n ensure_outputs_are_inferred=True,\n )\n\n if reverse_inputs:\n inputs = [B, A]\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=inputs,\n reference=ref,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, inputs, [0])\n if test_grad:\n for i in range(len(inputs)):\n self.assertGradientChecks(\n gc, op, inputs, i, [0],\n ensure_outputs_are_inferred=True,\n )\n\n def _test_binary_op(\n self, op_name, np_ref, n, m, k, t, bias, test_grad, gc, dc):\n op = core.CreateOperator(\n op_name,\n [\"A\", \"B\"],\n [\"C\"],\n )\n\n def ref(A, B):\n return [np_ref(A, B)]\n\n A = np.random.rand(n, m, k, t).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(1).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(k, t).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(n, m, 1, 1).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(1, m, k, 1).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(m, 1, t).astype(np.float32) + bias\n B = np.random.rand(n, m, k, t).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n A = np.random.rand(1, m, 1, t).astype(np.float32) + bias\n B = np.random.rand(n, 1, k, 1).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, True, test_grad, gc, dc)\n\n def _test_binary_op_in_place(\n self, op_name, np_ref, n, m, bias, test_grad, in_place_2nd, gc, dc):\n def ref(A, B):\n return [np_ref(A, B)]\n\n op = core.CreateOperator(\n op_name,\n [\"A\", \"B\"],\n [\"A\"],\n )\n A = np.random.rand(n, m).astype(np.float32) + bias\n B = np.random.rand(m).astype(np.float32) + bias\n\n self._run_single_test(op, ref, A, B, False, test_grad, gc, dc)\n A = np.random.rand(n, m).astype(np.float32) + bias\n B = np.random.rand(n, 1).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, False, test_grad, gc, dc)\n\n if in_place_2nd:\n op = core.CreateOperator(\n op_name,\n [\"A\", \"B\"],\n [\"B\"],\n )\n A = np.random.rand(m).astype(np.float32) + bias\n B = np.random.rand(n, m).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, False, test_grad, gc, dc)\n A = np.random.rand(n, 1).astype(np.float32) + bias\n B = np.random.rand(n, m).astype(np.float32) + bias\n self._run_single_test(op, ref, A, B, False, test_grad, gc, dc)\n\n @given(n=st.integers(0, 5), m=st.integers(0, 5), k=st.integers(0, 5),\n t=st.integers(0, 5), **hu.gcs)\n def test_add(self, n, m, k, t, gc, dc):\n self._test_binary_op(\"Add\", np.add, n, m, k, t, -0.5, True, gc, dc)\n self._test_binary_op_in_place(\n \"Add\", np.add, n, m, -0.5, True, True, gc, dc)\n\n @given(n=st.integers(0, 5), m=st.integers(0, 5), k=st.integers(0, 5),\n t=st.integers(0, 5), **hu.gcs)\n def test_sub(self, n, m, k, t, gc, dc):\n self._test_binary_op(\"Sub\", np.subtract, n, m,\n k, t, -0.5, True, gc, dc)\n self._test_binary_op_in_place(\n \"Sub\", np.subtract, n, m, -0.5, True, True, gc, dc)\n\n @given(n=st.integers(0, 5), m=st.integers(0, 5), k=st.integers(0, 5),\n t=st.integers(0, 5), **hu.gcs)\n def test_mul(self, n, m, k, t, gc, dc):\n self._test_binary_op(\"Mul\", np.multiply, n, m,\n k, t, -0.5, True, gc, dc)\n\n @given(n=st.integers(0, 5), m=st.integers(0, 5), k=st.integers(0, 5),\n t=st.integers(0, 5), **hu.gcs)\n def test_div(self, n, m, k, t, gc, dc):\n self._test_binary_op(\"Div\", np.divide, n, m, k, t, 1.0, True, gc, dc)\n self._test_binary_op_in_place(\n \"Div\", np.divide, n, m, 1.0, True, False, gc, dc)\n\n @given(n=st.integers(1, 5), m=st.integers(1, 5), broadcast=st.booleans(),\n **hu.gcs)\n def test_div_legacy_grad(self, n, m, broadcast, gc, dc):\n op = core.CreateOperator(\n \"DivGradient\",\n [\"B\", \"C\", \"dC\"],\n [\"dA\", \"dB\"],\n )\n\n def div_grad_ref(B, C, dC):\n dA = dC / B\n dB = -dC * C / B\n if broadcast:\n dB = np.sum(dB, axis=0)\n return [dA, dB]\n\n if broadcast:\n B = np.random.rand(m).astype(np.float32) + 1.0\n else:\n B = np.random.rand(n, m).astype(np.float32) + 1.0\n C = np.random.randn(n, m).astype(np.float32)\n dC = np.random.randn(n, m).astype(np.float32)\n inputs = [B, C, dC]\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=inputs,\n reference=div_grad_ref,\n )\n self.assertDeviceChecks(dc, op, inputs, [0, 1])\n\n def _test_bitwise_binary_op(self, op_name, np_ref, n, m, k, t, gc, dc):\n op = core.CreateOperator(\n op_name,\n [\"A\", \"B\"],\n [\"C\"],\n )\n\n def ref(A, B):\n return [np_ref(A, B)]\n\n A = np.random.randint(128, size=(n, m, k, t))\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=1)\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=(k, t))\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=(n, m, 1, 1))\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=(1, m, k, 1))\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=(m, 1, t))\n B = np.random.randint(128, size=(n, m, k, t))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n A = np.random.randint(128, size=(1, m, 1, t))\n B = np.random.randint(128, size=(n, 1, k, 1))\n self._run_single_test(op, ref, A, B, True, False, gc, dc)\n\n @given(n=st.integers(1, 5), m=st.integers(1, 5), k=st.integers(1, 5),\n t=st.integers(1, 5), **hu.gcs)\n def test_bitwise_and(self, n, m, k, t, gc, dc):\n self._test_bitwise_binary_op(\n \"BitwiseAnd\", np.bitwise_and, n, m, k, t, gc, dc)\n\n @given(n=st.integers(1, 5), m=st.integers(1, 5), k=st.integers(1, 5),\n t=st.integers(1, 5), **hu.gcs)\n def test_bitwise_or(self, n, m, k, t, gc, dc):\n self._test_bitwise_binary_op(\n \"BitwiseOr\", np.bitwise_or, n, m, k, t, gc, dc)\n\n @given(n=st.integers(1, 5), m=st.integers(1, 5), k=st.integers(1, 5),\n t=st.integers(1, 5), **hu.gcs)\n def test_bitwise_xor(self, n, m, k, t, gc, dc):\n self._test_bitwise_binary_op(\n \"BitwiseXor\", np.bitwise_xor, n, m, k, t, gc, dc)\n\n @given(X=hu.tensor(elements=hu.floats(0.5, 2), dtype=np.float32),\n inplace=st.booleans(), **hu.gcs)\n def test_reciprocal(self, X, inplace, gc, dc):\n def reciprocal_op(X):\n return [np.reciprocal(X)]\n\n op = core.CreateOperator(\n \"Reciprocal\",\n [\"X\"],\n [\"X\"] if inplace else [\"Y\"]\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=reciprocal_op,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(\n gc, op, [X], 0, [0], stepsize=1e-3, threshold=0.05,\n ensure_outputs_are_inferred=True)\n\n @given(X=hu.tensor(dtype=np.bool), **hu.gcs)\n def test_not(self, X, gc, dc):\n def not_op(X):\n return [np.logical_not(X)]\n\n op = core.CreateOperator(\n \"Not\",\n [\"X\"],\n [\"Y\"],\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[X],\n reference=not_op,\n ensure_outputs_are_inferred=True,\n )\n self.assertDeviceChecks(dc, op, [X], [0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "from numbers import Number\n\nimport torch\nfrom torch.distributions import constraints\nfrom torch.distributions.distribution import Distribution\nfrom torch.distributions.utils import broadcast_all, probs_to_logits, logits_to_probs, lazy_property\nfrom torch.nn.functional import binary_cross_entropy_with_logits\n\n\nclass Geometric(Distribution):\n r\"\"\"\n Creates a Geometric distribution parameterized by :attr:`probs`,\n where :attr:`probs` is the probability of success of Bernoulli trials.\n It represents the probability that in :math:`k + 1` Bernoulli trials, the\n first :math:`k` trials failed, before seeing a success.\n\n Samples are non-negative integers [0, :math:`\\inf`).\n\n Example::\n\n >>> m = Geometric(torch.tensor([0.3]))\n >>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0\n tensor([ 2.])\n\n Args:\n probs (Number, Tensor): the probability of sampling `1`. Must be in range (0, 1]\n logits (Number, Tensor): the log-odds of sampling `1`.\n \"\"\"\n arg_constraints = {'probs': constraints.unit_interval,\n 'logits': constraints.real}\n support = constraints.nonnegative_integer\n\n def __init__(self, probs=None, logits=None, validate_args=None):\n if (probs is None) == (logits is None):\n raise ValueError(\"Either `probs` or `logits` must be specified, but not both.\")\n if probs is not None:\n self.probs, = broadcast_all(probs)\n if not self.probs.gt(0).all():\n raise ValueError('All elements of probs must be greater than 0')\n else:\n self.logits, = broadcast_all(logits)\n probs_or_logits = probs if probs is not None else logits\n if isinstance(probs_or_logits, Number):\n batch_shape = torch.Size()\n else:\n batch_shape = probs_or_logits.size()\n super(Geometric, self).__init__(batch_shape, validate_args=validate_args)\n\n def expand(self, batch_shape, _instance=None):\n new = self._get_checked_instance(Geometric, _instance)\n batch_shape = torch.Size(batch_shape)\n if 'probs' in self.__dict__:\n new.probs = self.probs.expand(batch_shape)\n if 'logits' in self.__dict__:\n new.logits = self.logits.expand(batch_shape)\n super(Geometric, new).__init__(batch_shape, validate_args=False)\n new._validate_args = self._validate_args\n return new\n\n @property\n def mean(self):\n return 1. / self.probs - 1.\n\n @property\n def variance(self):\n return (1. / self.probs - 1.) / self.probs\n\n @lazy_property\n def logits(self):\n return probs_to_logits(self.probs, is_binary=True)\n\n @lazy_property\n def probs(self):\n return logits_to_probs(self.logits, is_binary=True)\n\n def sample(self, sample_shape=torch.Size()):\n shape = self._extended_shape(sample_shape)\n tiny = torch.finfo(self.probs.dtype).tiny\n with torch.no_grad():\n if torch._C._get_tracing_state():\n # [JIT WORKAROUND] lack of support for .uniform_()\n u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)\n u = u.clamp(min=tiny)\n else:\n u = self.probs.new(shape).uniform_(tiny, 1)\n return (u.log() / (-self.probs).log1p()).floor()\n\n def log_prob(self, value):\n if self._validate_args:\n self._validate_sample(value)\n value, probs = broadcast_all(value, self.probs.clone(memory_format=torch.contiguous_format))\n probs[(probs == 1) & (value == 0)] = 0\n return value * (-probs).log1p() + self.probs.log()\n\n def entropy(self):\n return binary_cross_entropy_with_logits(self.logits, self.probs, reduction='none') / self.probs\n", "#!/usr/bin/env python3\nimport unittest\n\nfrom torch.testing._internal.common_distributed import MultiProcessTestCase\nfrom torch.testing._internal.common_utils import TEST_WITH_ASAN, run_tests\nfrom torch.testing._internal.distributed.rpc.dist_autograd_test import (\n FaultyAgentDistAutogradTest,\n)\n\n\[email protected](\n TEST_WITH_ASAN, \"Skip ASAN as torch + multiprocessing spawn have known issues\"\n)\nclass FaultyAgentDistAutogradTestWithSpawn(MultiProcessTestCase, FaultyAgentDistAutogradTest):\n def setUp(self):\n super(FaultyAgentDistAutogradTestWithSpawn, self).setUp()\n self._spawn_processes()\n\n\nif __name__ == \"__main__\":\n run_tests()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom functools import partial\nfrom hypothesis import given\n\nimport numpy as np\nimport unittest\nimport hypothesis.strategies as st\n\nfrom caffe2.python import core, workspace\nimport caffe2.python.hypothesis_test_util as hu\nimport caffe2.python.serialized_test.serialized_test_util as serial\n\n\nclass TesterBase:\n def segment_reduce_op(self, data, segment_ids, reducer, indices=None):\n segments = self.split(data, segment_ids, indices)\n output = np.zeros((len(segments), ) + data.shape[1:])\n for i, segment in enumerate(segments):\n if len(segment) > 0:\n output[i] = reducer(segment)\n else:\n output[i] = 0.0\n return output\n\n def segment_reduce_grad_op(\n self,\n data,\n segment_ids,\n reducer_grad,\n grad_out,\n output,\n indices=None\n ):\n segments = self.split(data, segment_ids, indices)\n segment_grads = [\n reducer_grad(grad_out[i], [output[i]], [segment])\n for i, segment in enumerate(segments)\n ]\n return self.unsplit(data.shape[1:], segment_grads, segment_ids)\n\n def _test(self, prefix, input_strategy, refs, gpu=False, **kwargs):\n tester = self\n operator_args = kwargs.pop('operator_args', {})\n threshold = kwargs.pop('threshold', 1e-4)\n grad_check = kwargs.pop('grad_check', True)\n\n @given(X=input_strategy, **hu.gcs)\n def test_segment_ops(self, X, gc, dc):\n if not gpu and gc.device_type > 0:\n return\n for op_name, ref, grad_ref in refs:\n inputs = ['input%d' % i for i in range(0, len(X))]\n op = core.CreateOperator(\n prefix + op_name, inputs, ['output'], **operator_args\n )\n print('Operator %s, ' % op.type, gc.device_type)\n\n def seg_reduce(data, *args):\n indices, segments = (\n args if len(args) == 2 else (None, args[0])\n )\n out = tester.segment_reduce_op(\n data=data,\n segment_ids=segments,\n indices=indices,\n reducer=ref\n )\n return (out, )\n\n def seg_reduce_grad(grad_out, outputs, inputs):\n data = inputs[0]\n args = inputs[1:]\n indices, segments = (\n args if len(args) == 2 else (None, args[0])\n )\n # grad r.t. data\n grad_val = tester.segment_reduce_grad_op(\n data, segments, grad_ref, grad_out, outputs[0], indices\n )\n # if sparse, include indices along with data gradient\n data_grad_slice = (\n (grad_val, indices) if indices is not None else grad_val\n )\n # other inputs don't have gradient\n return (data_grad_slice, ) + (None, ) * (len(inputs) - 1)\n\n kwargs = {}\n if grad_check:\n kwargs['output_to_grad'] = 'output'\n kwargs['grad_reference'] = seg_reduce_grad\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=X,\n reference=seg_reduce,\n threshold=threshold,\n **kwargs\n )\n return test_segment_ops\n\n\nclass SegmentsTester(TesterBase):\n def split(self, data, segment_ids, indices=None):\n \"\"\"\n Given:\n data[M1 x M2 x ... x Md]\n the input data\n indices[N] the index of each entry of segment_ids into data,\n where 0 <= index[i] < M1,\n with default indices=[0,1,...N]\n segment_ids[N] the segment_id for each entry of indices,\n\n returns K outputs, each one containing data entries corresponding\n to one of the segments present in `segment_ids`.\n \"\"\"\n if segment_ids.size == 0:\n return []\n K = max(segment_ids) + 1\n outputs = [\n np.zeros(\n (np.count_nonzero(segment_ids == seg_id), ) + data.shape[1:],\n dtype=data.dtype\n ) for seg_id in range(0, K)\n ]\n counts = np.zeros(K, dtype=int)\n for i, seg_id in enumerate(segment_ids):\n data_idx = i if indices is None else indices[i]\n outputs[seg_id][counts[seg_id]] = data[data_idx]\n counts[seg_id] += 1\n return outputs\n\n def unsplit(self, extra_shape, inputs, segment_ids):\n \"\"\" Inverse operation to `split`, with indices=None \"\"\"\n output = np.zeros((len(segment_ids), ) + extra_shape)\n if len(segment_ids) == 0:\n return output\n K = max(segment_ids) + 1\n counts = np.zeros(K, dtype=int)\n for i, seg_id in enumerate(segment_ids):\n output[i] = inputs[seg_id][counts[seg_id]]\n counts[seg_id] += 1\n return output\n\n\nclass LengthsTester(TesterBase):\n def split(self, data, lengths, indices=None):\n K = len(lengths)\n outputs = [\n np.zeros((lengths[seg_id], ) + data.shape[1:],\n dtype=data.dtype) for seg_id in range(0, K)\n ]\n start = 0\n for i in range(0, K):\n for j in range(0, lengths[i]):\n data_index = start + j\n if indices is not None:\n data_index = indices[data_index]\n outputs[i][j] = data[data_index]\n start += lengths[i]\n return outputs\n\n def unsplit(self, extra_shape, inputs, lengths):\n N = sum(lengths)\n output = np.zeros((N, ) + extra_shape)\n K = len(lengths)\n assert len(inputs) == K\n current = 0\n for i in range(0, K):\n for j in range(0, lengths[i]):\n output[current] = inputs[i][j]\n current += 1\n return output\n\n\ndef sum_grad(grad_out, outputs, inputs):\n return np.repeat(\n np.expand_dims(grad_out, axis=0),\n inputs[0].shape[0],\n axis=0\n )\n\n\ndef logsumexp(x):\n return np.log(np.sum(np.exp(x), axis=0))\n\n\ndef logsumexp_grad(grad_out, outputs, inputs):\n sum_exps = np.sum(np.exp(inputs[0]), axis=0)\n return np.repeat(\n np.expand_dims(grad_out / sum_exps, 0),\n inputs[0].shape[0],\n axis=0\n ) * np.exp(inputs[0])\n\n\ndef logmeanexp(x):\n return np.log(np.mean(np.exp(x), axis=0))\n\n\ndef mean(x):\n return np.mean(x, axis=0)\n\n\ndef mean_grad(grad_out, outputs, inputs):\n return np.repeat(\n np.expand_dims(grad_out / inputs[0].shape[0], 0),\n inputs[0].shape[0],\n axis=0\n )\n\n\ndef max_fwd(x):\n return np.amax(x, axis=0)\n\n\ndef max_grad(grad_out, outputs, inputs):\n flat_inputs = inputs[0].flatten()\n flat_outputs = np.array(outputs[0]).flatten()\n flat_grad_in = np.zeros(flat_inputs.shape)\n flat_grad_out = np.array(grad_out).flatten()\n blocks = inputs[0].shape[0]\n if blocks == 0:\n return np.zeros(inputs[0].shape)\n block_size = flat_inputs.shape[0] // blocks\n\n for i in range(block_size):\n out_grad = flat_grad_out[i]\n out = flat_outputs[i]\n for j in range(blocks):\n idx = j * block_size + i\n # we can produce multiple outputs for max\n if out == flat_inputs[idx]:\n flat_grad_in[idx] = out_grad\n\n return np.resize(flat_grad_in, inputs[0].shape)\n\n\nREFERENCES_ALL = [\n ('Sum', partial(np.sum, axis=0), sum_grad),\n ('Mean', partial(np.mean, axis=0), mean_grad),\n]\n\nREFERENCES_SORTED = [\n ('RangeSum', partial(np.sum, axis=0), sum_grad),\n ('RangeLogSumExp', logsumexp, logsumexp_grad),\n # gradient is the same as sum\n ('RangeLogMeanExp', logmeanexp, logsumexp_grad),\n ('RangeMean', mean, mean_grad),\n ('RangeMax', max_fwd, max_grad),\n]\n\nREFERENCES_LENGTHS_ONLY = [\n ('Max', partial(np.amax, axis=0), max_grad),\n]\n\n\ndef sparse_lengths_weighted_sum_ref(D, W, I, L):\n R = np.zeros(shape=(len(L), ) + D.shape[1:], dtype=D.dtype)\n line = 0\n for g in range(len(L)):\n for _ in range(L[g]):\n if len(D.shape) > 1:\n R[g, :] += W[line] * D[I[line], :]\n else:\n R[g] += W[line] * D[I[line]]\n line += 1\n return [R]\n\n\ndef sparse_lengths_weighted_sum_grad_ref(\n GO, fwd_out, fwd_in, grad_on_weights=False):\n D, W, I, L = fwd_in\n GI = np.zeros(shape=(len(I), ) + D.shape[1:], dtype=D.dtype)\n GW = np.zeros(shape=W.shape, dtype=W.dtype) if grad_on_weights else None\n line = 0\n for g in range(len(L)):\n for _ in range(L[g]):\n if len(GO.shape) > 1:\n GI[line, :] = W[line] * GO[g, :]\n else:\n GI[line] = W[line] * GO[g]\n if GW is not None:\n if len(GO.shape) > 1:\n GW[line] = np.dot(GO[g].flatten(), D[I[line], :].flatten())\n else:\n GW[line] = np.dot(GO[g].flatten(), D[I[line]].flatten())\n line += 1\n print(GW)\n return [(GI, I), GW, None, None]\n\n\nclass TestSegmentOps(hu.HypothesisTestCase):\n def test_sorted_segment_ops(self):\n SegmentsTester()._test(\n 'SortedSegment',\n hu.segmented_tensor(\n dtype=np.float32,\n is_sorted=True,\n allow_empty=True\n ),\n REFERENCES_ALL + REFERENCES_SORTED\n )(self)\n\n def test_unsorted_segment_ops(self):\n SegmentsTester()._test(\n 'UnsortedSegment',\n hu.segmented_tensor(\n dtype=np.float32,\n is_sorted=False,\n allow_empty=True\n ),\n REFERENCES_ALL,\n )(self)\n\n def test_unsorted_segment_ops_gpu(self):\n SegmentsTester()._test(\n 'UnsortedSegment',\n hu.segmented_tensor(\n dtype=np.float32,\n is_sorted=False,\n allow_empty=True,\n ),\n REFERENCES_ALL,\n gpu=workspace.has_gpu_support,\n grad_check=False,\n )(self)\n\n def test_sparse_sorted_segment_ops(self):\n SegmentsTester()._test(\n 'SparseSortedSegment',\n hu.sparse_segmented_tensor(\n dtype=np.float32,\n is_sorted=True,\n allow_empty=True\n ),\n REFERENCES_ALL\n )(self)\n\n def test_sparse_unsorted_segment_ops(self):\n SegmentsTester()._test(\n 'SparseUnsortedSegment',\n hu.sparse_segmented_tensor(\n dtype=np.float32,\n is_sorted=False,\n allow_empty=True\n ),\n REFERENCES_ALL\n )(self)\n\n def test_lengths_ops(self):\n LengthsTester()._test(\n 'Lengths',\n hu.lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True\n ),\n REFERENCES_ALL + REFERENCES_LENGTHS_ONLY,\n )(self)\n\n def test_sparse_lengths_ops(self):\n for itype in [np.int32, np.int64]:\n LengthsTester()._test(\n 'SparseLengths',\n hu.sparse_lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True,\n itype=itype,\n ),\n REFERENCES_ALL,\n )(self)\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support\")\n @given(**hu.gcs)\n def test_unsorted_sums_large(self, gc, dc):\n X = np.random.rand(10000, 32, 12).astype(np.float32)\n segments = np.random.randint(0, 10000, size=10000).astype(np.int32)\n op = core.CreateOperator(\"UnsortedSegmentSum\", [\"X\", \"segments\"], \"out\")\n self.assertDeviceChecks(dc, op, [X, segments], [0])\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support\")\n @given(**hu.gcs)\n def test_sorted_segment_range_mean(self, gc, dc):\n X = np.random.rand(6, 32, 12).astype(np.float32)\n segments = np.array([0, 0, 1, 1, 2, 3]).astype(np.int32)\n op = core.CreateOperator(\n \"SortedSegmentRangeMean\",\n [\"X\", \"segments\"],\n \"out\"\n )\n self.assertDeviceChecks(dc, op, [X, segments], [0])\n self.assertGradientChecks(gc, op, [X, segments], 0, [0])\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support\")\n @given(**hu.gcs)\n def test_sorted_segment_range_log_mean_exp(self, gc, dc):\n X = np.random.rand(7, 32, 12).astype(np.float32)\n segments = np.array([0, 0, 1, 1, 2, 2, 3]).astype(np.int32)\n op = core.CreateOperator(\n \"SortedSegmentRangeLogMeanExp\",\n [\"X\", \"segments\"],\n \"out\"\n )\n self.assertDeviceChecks(dc, op, [X, segments], [0])\n self.assertGradientChecks(gc, op, [X, segments], 0, [0])\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No gpu support\")\n @given(**hu.gcs)\n def test_unsorted_means_large(self, gc, dc):\n X = np.random.rand(10000, 31, 19).astype(np.float32)\n segments = np.random.randint(0, 10000, size=10000).astype(np.int32)\n op = core.CreateOperator(\"UnsortedSegmentMean\", [\"X\", \"segments\"], \"out\")\n self.assertDeviceChecks(dc, op, [X, segments], [0])\n\n @serial.given(\n inputs=hu.lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True,\n ),\n **hu.gcs\n )\n def test_lengths_sum(self, inputs, gc, dc):\n X, Y = inputs\n op = core.CreateOperator(\"LengthsSum\", [\"X\", \"Y\"], \"out\")\n\n def ref(D, L):\n R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)\n line = 0\n for g in range(L.size):\n for _ in range(L[g]):\n if len(D.shape) > 1:\n R[g, :] += D[line, :]\n else:\n R[g] += D[line]\n line += 1\n return [R]\n\n self.assertReferenceChecks(gc, op, [X, Y], ref)\n self.assertDeviceChecks(dc, op, [X, Y], [0])\n self.assertGradientChecks(gc, op, [X, Y], 0, [0])\n\n @serial.given(\n inputs=hu.sparse_lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True\n ),\n **hu.gcs\n )\n def test_sparse_lengths_sum(self, inputs, gc, dc):\n X, Y, Z = inputs\n op = core.CreateOperator(\"SparseLengthsSum\", [\"X\", \"Y\", \"Z\"], \"out\")\n\n def ref(D, I, L):\n R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)\n line = 0\n for g in range(L.size):\n for _ in range(L[g]):\n if len(D.shape) > 1:\n R[g, :] += D[I[line], :]\n else:\n R[g] += D[I[line]]\n line += 1\n return [R]\n\n self.assertReferenceChecks(gc, op, [X, Y, Z], ref)\n self.assertDeviceChecks(dc, op, [X, Y, Z], [0])\n self.assertGradientChecks(gc, op, [X, Y, Z], 0, [0])\n\n @serial.given(\n inputs=hu.lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True,\n ),\n **hu.gcs\n )\n def test_lengths_mean(self, inputs, gc, dc):\n X, Y = inputs\n op = core.CreateOperator(\"LengthsMean\", [\"X\", \"Y\"], \"out\")\n\n def ref(D, L):\n R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)\n line = 0\n for g in range(L.size):\n for _ in range(L[g]):\n if len(D.shape) > 1:\n R[g, :] += D[line, :]\n else:\n R[g] += D[line]\n line += 1\n if L[g] > 1:\n if len(D.shape) > 1:\n R[g, :] = R[g, :] / L[g]\n else:\n R[g] = R[g] / L[g]\n\n return [R]\n\n self.assertReferenceChecks(gc, op, [X, Y], ref)\n self.assertDeviceChecks(dc, op, [X, Y], [0])\n self.assertGradientChecks(gc, op, [X, Y], 0, [0])\n\n @serial.given(\n inputs=hu.sparse_lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True\n ),\n **hu.gcs\n )\n def test_sparse_lengths_mean(self, inputs, gc, dc):\n X, Y, Z = inputs\n op = core.CreateOperator(\"SparseLengthsMean\", [\"X\", \"Y\", \"Z\"], \"out\")\n\n def ref(D, I, L):\n R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)\n line = 0\n for g in range(L.size):\n for _ in range(L[g]):\n if len(D.shape) > 1:\n R[g, :] += D[I[line], :]\n else:\n R[g] += D[I[line]]\n line += 1\n\n if L[g] > 1:\n if len(D.shape) > 1:\n R[g, :] = R[g, :] / L[g]\n else:\n R[g] = R[g] / L[g]\n\n return [R]\n\n self.assertReferenceChecks(gc, op, [X, Y, Z], ref)\n self.assertDeviceChecks(dc, op, [X, Y, Z], [0])\n self.assertGradientChecks(gc, op, [X, Y, Z], 0, [0])\n\n @serial.given(\n grad_on_weights=st.booleans(),\n inputs=hu.sparse_lengths_tensor(\n dtype=np.float32,\n min_value=1,\n max_value=5,\n allow_empty=True\n ),\n seed=st.integers(min_value=0, max_value=100),\n **hu.gcs\n )\n def test_sparse_lengths_weighted_sum(\n self, grad_on_weights, inputs, seed, gc, dc):\n D, I, L = inputs\n\n np.random.seed(int(seed))\n\n W = np.random.rand(I.size).astype(np.float32)\n op = core.CreateOperator(\n \"SparseLengthsWeightedSum\",\n [\"D\", \"W\", \"I\", \"L\"],\n \"out\",\n grad_on_weights=grad_on_weights)\n self.assertDeviceChecks(dc, op, [D, W, I, L], [0])\n self.assertReferenceChecks(\n device_option=gc,\n op=op,\n inputs=[D, W, I, L],\n reference=sparse_lengths_weighted_sum_ref,\n threshold=1e-4,\n output_to_grad='out',\n grad_reference=partial(\n sparse_lengths_weighted_sum_grad_ref,\n grad_on_weights=grad_on_weights),\n )\n self.assertGradientChecks(gc, op, [D, W, I, L], 0, [0])\n if grad_on_weights:\n self.assertGradientChecks(gc, op, [D, W, I, L], 1, [0])\n\n @given(**hu.gcs)\n def test_sparse_lengths_indices_in_gradient_sum_gpu(self, gc, dc):\n X = np.random.rand(3, 3, 4, 5).astype(np.float32)\n Y = np.asarray([3, 3, 2]).astype(np.int32)\n Z = np.random.randint(0, 50, size=8).astype(np.int64)\n op = core.CreateOperator(\n \"SparseLengthsIndicesInGradientSumGradient\", [\"X\", \"Y\", \"Z\"], \"out\"\n )\n self.assertDeviceChecks(dc, op, [X, Y, Z], [0])\n\n @given(**hu.gcs)\n def test_sparse_lengths_indices_in_gradient_mean_gpu(self, gc, dc):\n X = np.random.rand(3, 3, 4, 5).astype(np.float32)\n Y = np.asarray([3, 3, 2]).astype(np.int32)\n Z = np.random.randint(0, 50, size=8).astype(np.int64)\n op = core.CreateOperator(\n \"SparseLengthsIndicesInGradientMeanGradient\", [\"X\", \"Y\", \"Z\"], \"out\"\n )\n self.assertDeviceChecks(dc, op, [X, Y, Z], [0])\n\n @given(**hu.gcs_cpu_only)\n def test_legacy_sparse_and_lengths_sum_gradient(self, gc, dc):\n X = np.random.rand(3, 64).astype(np.float32)\n Y = np.asarray([20, 20, 10]).astype(np.int32)\n workspace.FeedBlob(\"X\", X)\n workspace.FeedBlob(\"Y\", Y)\n test_net = core.Net(\"test_net\")\n test_net.SparseLengthsSumGradient([\"X\", \"Y\"], \"out1\")\n test_net.LengthsSumGradient([\"X\", \"Y\"], \"out2\")\n workspace.RunNetOnce(test_net)\n out1 = workspace.FetchBlob(\"out1\")\n out2 = workspace.FetchBlob(\"out2\")\n self.assertTrue((out1 == out2).all())\n\n @given(**hu.gcs)\n def test_sparse_lengths_sum_invalid_index(self, gc, dc):\n D = np.random.rand(50, 3, 4, 5).astype(np.float32)\n I = (np.random.randint(0, 10000, size=10) + 10000).astype(np.int64)\n L = np.asarray([4, 4, 2]).astype(np.int32)\n op = core.CreateOperator(\n \"SparseLengthsSum\",\n [\"D\", \"I\", \"L\"],\n \"out\")\n workspace.FeedBlob('D', D)\n workspace.FeedBlob('I', I)\n workspace.FeedBlob('L', L)\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n\n @serial.given(**hu.gcs_cpu_only)\n def test_sparse_lengths_positional_weighted_sum(\n self, gc, dc):\n D = np.random.rand(50, 3, 4, 5).astype(np.float32)\n W = np.random.rand(50).astype(np.float32)\n indices = np.random.randint(0, 50, size=10).astype(np.int64)\n L = np.asarray([4, 4, 2]).astype(np.int32)\n op = core.CreateOperator(\n \"SparseLengthsPositionalWeightedSum\",\n [\"D\", \"W\", \"indices\", \"L\"],\n \"out\")\n\n def ref_sparse(D, W, indices, L):\n workspace.FeedBlob(\"L\", L)\n lengths_range_fill_op = core.CreateOperator(\n \"LengthsRangeFill\", [\"L\"], [\"L_pos_seq\"])\n workspace.RunOperatorOnce(lengths_range_fill_op)\n\n workspace.FeedBlob(\"W\", W)\n gather_op = core.CreateOperator(\n \"Gather\", [\"W\", \"L_pos_seq\"], [\"W_gathered\"])\n workspace.RunOperatorOnce(gather_op)\n\n workspace.FeedBlob(\"D\", D)\n workspace.FeedBlob(\"indices\", indices)\n sparse_op = core.CreateOperator(\n \"SparseLengthsWeightedSum\",\n [\"D\", \"W_gathered\", \"indices\", \"L\"],\n \"out_ref\")\n workspace.RunOperatorOnce(sparse_op)\n\n return (workspace.FetchBlob(\"out_ref\"),)\n\n self.assertReferenceChecks(\n gc, op, [D, W, indices, L], ref_sparse)\n\n # @given(\n # inputs=hu.lengths_tensor(\n # dtype=np.float32,\n # min_value=1,\n # max_value=5,\n # min_dim=1,\n # max_dim=1,\n # allow_empty=False,\n # ),\n # **hu.gcs\n # )\n # def test_lengths_max_gpu(self, inputs, gc, dc):\n # def lengths_max_ref(I, L):\n # R = np.zeros(shape=(len(L)), dtype=I.dtype)\n # line = 0\n # for g in range(len(L)):\n # for i in range(L[g]):\n # if i == 0:\n # R[g] = I[line]\n # else:\n # R[g] = max(R[g], I[line])\n # line += 1\n # return [R]\n\n # X, lengths = inputs\n # op = core.CreateOperator(\"LengthsMax\", [\"X\", \"lengths\"], \"out\")\n # self.assertDeviceChecks(dc, op, [X, lengths], [0])\n # self.assertReferenceChecks(\n # device_option=gc,\n # op=op,\n # inputs=[X, lengths],\n # reference=lengths_max_ref,\n # threshold=1e-4,\n # output_to_grad='out',\n # )\n\n\nif __name__ == \"__main__\":\n import unittest\n unittest.main()\n", "\nr\"\"\"\nThe torch package contains data structures for multi-dimensional\ntensors and mathematical operations over these are defined.\nAdditionally, it provides many utilities for efficient serializing of\nTensors and arbitrary types, and other useful utilities.\n\nIt has a CUDA counterpart, that enables you to run your tensor computations\non an NVIDIA GPU with compute capability >= 3.0.\n\"\"\"\n\nimport os\nimport sys\nimport platform\nimport ctypes\n\nif sys.version_info < (3,):\n raise Exception(\"Python 2 has reached end-of-life and is no longer supported by PyTorch.\")\n\nfrom ._utils import _import_dotted_name\nfrom ._utils_internal import get_file_path, prepare_multiprocessing_environment, \\\n USE_RTLD_GLOBAL_WITH_LIBTORCH, USE_GLOBAL_DEPS\nfrom .version import __version__\nfrom ._six import string_classes as _string_classes\n\nfrom typing import Set, Type\n\n#__all__ 作用是模块级别暴露接口,如果定义了__all__,其他文件中使用from xxx import *导入该文件时,\n#只会导入 __all__ 列出的成员,可以其他成员都被排除在外。\n#控制了from xxx import *的行为,避免非下划线开头的成员被导入到环境中,弄脏当前的命名空间\n__all__ = [\n 'typename', 'is_tensor', 'is_storage', 'set_default_tensor_type',\n 'set_rng_state', 'get_rng_state', 'manual_seed', 'initial_seed', 'seed',\n 'save', 'load', 'set_printoptions', 'chunk', 'split', 'stack', 'matmul',\n 'no_grad', 'enable_grad', 'rand', 'randn',\n 'DoubleStorage', 'FloatStorage', 'LongStorage', 'IntStorage',\n 'ShortStorage', 'CharStorage', 'ByteStorage', 'BoolStorage',\n 'DoubleTensor', 'FloatTensor', 'LongTensor', 'IntTensor',\n 'ShortTensor', 'CharTensor', 'ByteTensor', 'BoolTensor', 'Tensor',\n 'lobpcg', '_set_deterministic', '_is_deterministic'\n]\n\n################################################################################\n# Load the extension module\n################################################################################\n\nif sys.platform == 'win32':\n pfiles_path = os.getenv('ProgramFiles', 'C:\\\\Program Files')\n py_dll_path = os.path.join(sys.exec_prefix, 'Library', 'bin')\n th_dll_path = os.path.join(os.path.dirname(__file__), 'lib')\n\n # When users create a virtualenv that inherits the base environment,\n # we will need to add the corresponding library directory into\n # DLL search directories. Otherwise, it will rely on `PATH` which\n # is dependent on user settings.\n if sys.exec_prefix != sys.base_exec_prefix:\n base_py_dll_path = os.path.join(sys.base_exec_prefix, 'Library', 'bin')\n else:\n base_py_dll_path = ''\n\n dll_paths = list(filter(os.path.exists, [th_dll_path, py_dll_path, base_py_dll_path]))\n\n if all([not os.path.exists(os.path.join(p, 'nvToolsExt64_1.dll')) for p in dll_paths]):\n nvtoolsext_dll_path = os.path.join(\n os.getenv('NVTOOLSEXT_PATH', os.path.join(pfiles_path, 'NVIDIA Corporation', 'NvToolsExt')), 'bin', 'x64')\n else:\n nvtoolsext_dll_path = ''\n\n from .version import cuda as cuda_version\n import glob\n if cuda_version and all([not glob.glob(os.path.join(p, 'cudart64*.dll')) for p in dll_paths]):\n cuda_version_1 = cuda_version.replace('.', '_')\n cuda_path_var = 'CUDA_PATH_V' + cuda_version_1\n default_path = os.path.join(pfiles_path, 'NVIDIA GPU Computing Toolkit', 'CUDA', 'v' + cuda_version)\n cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), 'bin')\n else:\n cuda_path = ''\n\n dll_paths.extend(filter(os.path.exists, [nvtoolsext_dll_path, cuda_path]))\n\n kernel32 = ctypes.WinDLL('kernel32.dll', use_last_error=True)\n with_load_library_flags = hasattr(kernel32, 'AddDllDirectory')\n prev_error_mode = kernel32.SetErrorMode(0x0001)\n\n kernel32.LoadLibraryW.restype = ctypes.c_void_p\n if with_load_library_flags:\n kernel32.AddDllDirectory.restype = ctypes.c_void_p\n kernel32.LoadLibraryExW.restype = ctypes.c_void_p\n\n for dll_path in dll_paths:\n if sys.version_info >= (3, 8):\n os.add_dll_directory(dll_path)\n elif with_load_library_flags:\n res = kernel32.AddDllDirectory(dll_path)\n if res is None:\n err = ctypes.WinError(ctypes.get_last_error())\n err.strerror += ' Error adding \"{}\" to the DLL directories.'.format(dll_path)\n raise err\n\n try:\n ctypes.CDLL('vcruntime140.dll')\n ctypes.CDLL('msvcp140.dll')\n if cuda_version not in ('9.2', '10.0'):\n ctypes.CDLL('vcruntime140_1.dll')\n except OSError:\n print('''Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.\n It can be downloaded at https://aka.ms/vs/16/release/vc_redist.x64.exe''')\n\n dlls = glob.glob(os.path.join(th_dll_path, '*.dll'))\n path_patched = False\n for dll in dlls:\n is_loaded = False\n if with_load_library_flags:\n res = kernel32.LoadLibraryExW(dll, None, 0x00001100)\n last_error = ctypes.get_last_error()\n if res is None and last_error != 126:\n err = ctypes.WinError(last_error)\n err.strerror += ' Error loading \"{}\" or one of its dependencies.'.format(dll)\n raise err\n elif res is not None:\n is_loaded = True\n if not is_loaded:\n if not path_patched:\n os.environ['PATH'] = ';'.join(dll_paths + [os.environ['PATH']])\n path_patched = True\n res = kernel32.LoadLibraryW(dll)\n if res is None:\n err = ctypes.WinError(ctypes.get_last_error())\n err.strerror += ' Error loading \"{}\" or one of its dependencies.'.format(dll)\n raise err\n\n kernel32.SetErrorMode(prev_error_mode)\n\n\n# See Note [Global dependencies]\ndef _load_global_deps():\n if platform.system() == 'Windows':\n return\n\n lib_name = 'libtorch_global_deps' + ('.dylib' if platform.system() == 'Darwin' else '.so')\n here = os.path.abspath(__file__)\n lib_path = os.path.join(os.path.dirname(here), 'lib', lib_name)\n\n ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL)\n\n\nif (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv('TORCH_USE_RTLD_GLOBAL')) and \\\n platform.system() != 'Windows':\n # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a\n # few circumstances:\n #\n # 1. You're in a build environment (e.g., fbcode) where\n # libtorch_global_deps is not available, but you still need\n # to get mkl to link in with RTLD_GLOBAL or it will just\n # not work.\n #\n # 2. You're trying to run PyTorch under UBSAN and you need\n # to ensure that only one copy of libtorch is loaded, so\n # vptr checks work properly\n #\n # If you're using this setting, you must verify that all the libraries\n # you load consistently use the same libstdc++, or you may have\n # mysterious segfaults.\n #\n import os as _dl_flags\n if not hasattr(_dl_flags, 'RTLD_GLOBAL') or not hasattr(_dl_flags, 'RTLD_LAZY'):\n try:\n # next try if DLFCN exists\n import DLFCN as _dl_flags # type: ignore\n except ImportError:\n # as a last attempt, use compile-time constants\n import torch._dl as _dl_flags # type: ignore\n old_flags = sys.getdlopenflags()\n sys.setdlopenflags(_dl_flags.RTLD_GLOBAL | _dl_flags.RTLD_LAZY)\n from torch._C import *\n sys.setdlopenflags(old_flags)\n del old_flags\n del _dl_flags\n\nelse:\n # Easy way. You want this most of the time, because it will prevent\n # C++ symbols from libtorch clobbering C++ symbols from other\n # libraries, leading to mysterious segfaults.\n #\n # If building in an environment where libtorch_global_deps isn't available\n # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will\n # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False\n #\n # See Note [Global dependencies]\n if USE_GLOBAL_DEPS: #USE_GLOBAL_DEPS=True\n _load_global_deps()\n from torch._C import *\n\n# Appease the type checker; ordinarily this binding is inserted by the\n# torch._C module initialization code in C\nif False:\n import torch._C as _C\n#dir()的作用,可以用来来列出模块定义的标识符--函数、类和变量\n#当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。\n\n#如果不提供参数,它返回当前模块中定义的名称列表。\n__all__ += [name for name in dir(_C)\n if name[0] != '_' and\n not name.endswith('Base')]\n'''\n['typename', 'is_tensor', 'is_storage', 'set_default_tensor_type', \n'set_rng_state', 'get_rng_state', 'manual_seed', 'initial_seed',\n 'seed', 'save', 'load', 'set_printoptions', 'chunk', 'split', \n 'stack', 'matmul', 'no_grad', 'enable_grad', 'rand', 'randn', \n 'DoubleStorage', 'FloatStorage', 'LongStorage', 'IntStorage', \n 'ShortStorage', 'CharStorage', 'ByteStorage', 'BoolStorage', \n 'DoubleTensor', 'FloatTensor', 'LongTensor', 'IntTensor', 'ShortTensor', \n 'CharTensor', 'ByteTensor', 'BoolTensor', 'Tensor', 'lobpcg', \n 'set_deterministic', 'is_deterministic', 'AVG', 'AggregationType', \n 'AnyType', 'Argument', 'ArgumentSpec', 'BenchmarkConfig', \n 'BenchmarkExecutionStats', 'Block', 'BoolType', 'BufferDict', \n 'CONV_BN_FUSION', 'CallStack', 'Capsule', 'ClassType', 'Code', \n 'CompilationUnit', 'CompleteArgumentSpec', 'ConcreteModuleType', \n 'ConcreteModuleTypeBuilder', 'DeepCopyMemoTable', 'DeviceObjType', \n 'DictType', 'DisableTorchFunction', 'EnumType', 'ErrorReport', \n 'ExecutionPlan', 'ExtraFilesMap', 'FUSE_ADD_RELU', 'FatalError', \n 'FileCheck', 'FloatType', 'FunctionSchema', 'Future', 'FutureType', \n 'Generator', 'Gradient', 'Graph', 'GraphExecutorState', \n 'HOIST_CONV_PACKED_PARAMS', 'INSERT_FOLD_PREPACK_OPS', \n 'IODescriptor', 'IntType', 'InterfaceType', 'JITException', \n 'ListType', 'LiteScriptModule', 'LockingLogger', 'MobileOptimizerType', \n 'ModuleDict', 'Node', 'NoneType', 'NoopLogger', 'NumberType', \n 'OptionalType', 'ParameterDict', 'PyObjectType', 'PyTorchFileReader', '\n PyTorchFileWriter', 'REMOVE_DROPOUT', 'RRefType', 'SUM', 'ScriptClass', \n 'ScriptFunction', 'ScriptMethod', 'ScriptModule', 'ScriptObject', 'Size', \n 'StaticRuntime', 'StringType', 'TensorType', 'ThroughputBenchmark', \n 'TracingState', 'TupleType', 'Type', 'Use', 'Value', 'autocast_decrement_nesting', \n 'autocast_increment_nesting', 'clear_autocast_cache', 'cpp', 'default_generator', \n 'device', 'dtype', 'finfo', 'fork', 'get_default_dtype', \n 'get_num_interop_threads', 'get_num_threads', 'has_cuda', 'has_cudnn', \n 'has_lapack', 'has_mkl', 'has_mkldnn', 'has_openmp', 'iinfo', \n 'import_ir_module', 'import_ir_module_from_buffer', 'init_num_threads', \n 'is_anomaly_enabled', 'is_autocast_enabled', 'is_grad_enabled', 'layout', \n 'memory_format', 'merge_type_from_type_comment', 'parse_ir', \n 'parse_schema', 'parse_type_comment', 'qscheme', 'set_anomaly_enabled', \n 'set_autocast_enabled', 'set_flush_denormal', 'set_grad_enabled', \n 'set_num_interop_threads', 'set_num_threads', 'unify_type_list', 'wait'\n'''\n################################################################################\n# Define basic utilities\n################################################################################\n\n\ndef typename(o):\n if isinstance(o, torch.Tensor):\n return o.type()\n\n module = ''\n class_name = ''\n if hasattr(o, '__module__') and o.__module__ != 'builtins' \\\n and o.__module__ != '__builtin__' and o.__module__ is not None:\n module = o.__module__ + '.'\n\n if hasattr(o, '__qualname__'):\n class_name = o.__qualname__\n elif hasattr(o, '__name__'):\n class_name = o.__name__\n else:\n class_name = o.__class__.__name__\n\n return module + class_name\n\n\ndef is_tensor(obj):\n r\"\"\"Returns True if `obj` is a PyTorch tensor.\n\n Note that this function is simply doing ``isinstance(obj, Tensor)``.\n Using that ``isinstance`` check is better for typechecking with mypy,\n and more explicit - so it's recommended to use that instead of\n ``is_tensor``.\n\n Args:\n obj (Object): Object to test\n \"\"\"\n return isinstance(obj, torch.Tensor)\n\n\ndef is_storage(obj):\n r\"\"\"Returns True if `obj` is a PyTorch storage object.\n\n Args:\n obj (Object): Object to test\n \"\"\"\n return type(obj) in _storage_classes\n\n\ndef set_default_tensor_type(t):\n r\"\"\"Sets the default ``torch.Tensor`` type to floating point tensor type\n ``t``. This type will also be used as default floating point type for\n type inference in :func:`torch.tensor`.\n\n The default floating point tensor type is initially ``torch.FloatTensor``.\n\n Args:\n t (type or string): the floating point tensor type or its name\n\n Example::\n\n >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32\n torch.float32\n >>> torch.set_default_tensor_type(torch.DoubleTensor)\n >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor\n torch.float64\n\n \"\"\"\n if isinstance(t, _string_classes):\n t = _import_dotted_name(t)\n _C._set_default_tensor_type(t)\n\n\ndef set_default_dtype(d):\n r\"\"\"Sets the default floating point dtype to :attr:`d`.\n This dtype is:\n 1. The inferred dtype for python floats in :func:`torch.tensor`.\n 2. Used to infer dtype for python complex numbers. The default complex dtype is set to\n ``torch.complex128`` if default floating point dtype is ``torch.float64``,\n otherwise it's set to ``torch.complex64``\n\n The default floating point dtype is initially ``torch.float32``.\n\n Args:\n d (:class:`torch.dtype`): the floating point dtype to make the default\n\n Example::\n >>> # initial default for floating point is torch.float32\n >>> torch.tensor([1.2, 3]).dtype\n torch.float32\n >>> # initial default for floating point is torch.complex64\n >>> torch.tensor([1.2, 3j]).dtype\n torch.complex64\n >>> torch.set_default_dtype(torch.float64)\n >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor\n torch.float64\n >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor\n torch.complex128\n\n \"\"\"\n _C._set_default_dtype(d)\n\ndef _set_deterministic(d):\n r\"\"\"Sets a global flag to force all operations to use a deterministic\n implementation if available. If an operation that does not have a\n deterministic implementation is called while this setting is True, the\n operation will throw a RuntimeError.\n\n Note that deterministic operations tend to have worse performance than\n non-deterministic operations.\n\n Args:\n d (:class:`bool`): If True, force operations to be deterministic.\n If False, allow non-deterministic operations.\n\n .. warning::\n This feature is experimental and not complete. The above docstring\n represents what the future behavior is intended to be. Right now,\n `_set_deterministic` will only affect `torch.bmm` and convolution\n operators.\n \"\"\"\n _C._set_deterministic(d)\n\ndef _is_deterministic():\n r\"\"\"Returns True if the global deterministic flag is turned on and\n operations are being forced to use a deterministic implementation.\n\n .. warning::\n This feature is experimental and not complete. The above docstring\n represents what the future behavior is intended to be. Right now,\n the global deterministic flag will only affect `torch.bmm` and\n convolution operators.\n \"\"\"\n return _C._get_deterministic()\n\n# If you edit these imports, please update torch/__init__.py.in as well\nfrom .random import set_rng_state, get_rng_state, manual_seed, initial_seed, seed\nfrom .serialization import save, load\nfrom ._tensor_str import set_printoptions\n\n################################################################################\n# Define Storage and Tensor classes\n################################################################################\n#定义python端的Tensor\nfrom .tensor import Tensor\nfrom .storage import _StorageBase\n\n\nclass DoubleStorage(_C.DoubleStorageBase, _StorageBase):\n pass\n\n\nclass FloatStorage(_C.FloatStorageBase, _StorageBase):\n pass\n\n\nclass HalfStorage(_C.HalfStorageBase, _StorageBase):\n pass\n\n\nclass LongStorage(_C.LongStorageBase, _StorageBase):\n pass\n\n\nclass IntStorage(_C.IntStorageBase, _StorageBase):\n pass\n\n\nclass ShortStorage(_C.ShortStorageBase, _StorageBase):\n pass\n\n\nclass CharStorage(_C.CharStorageBase, _StorageBase):\n pass\n\n\nclass ByteStorage(_C.ByteStorageBase, _StorageBase):\n pass\n\n\nclass BoolStorage(_C.BoolStorageBase, _StorageBase):\n pass\n\n\nclass BFloat16Storage(_C.BFloat16StorageBase, _StorageBase):\n pass\n\nclass ComplexDoubleStorage(_C.ComplexDoubleStorageBase, _StorageBase):\n pass\n\nclass ComplexFloatStorage(_C.ComplexFloatStorageBase, _StorageBase):\n pass\n\nclass QUInt8Storage(_C.QUInt8StorageBase, _StorageBase):\n pass\n\nclass QInt8Storage(_C.QInt8StorageBase, _StorageBase):\n pass\n\nclass QInt32Storage(_C.QInt32StorageBase, _StorageBase):\n pass\n\n\n_storage_classes = {\n DoubleStorage, FloatStorage, LongStorage, IntStorage, ShortStorage,\n CharStorage, ByteStorage, HalfStorage, BoolStorage, QUInt8Storage, QInt8Storage,\n QInt32Storage, BFloat16Storage, ComplexFloatStorage, ComplexDoubleStorage\n}\n\n# The _tensor_classes set is initialized by the call to _C._initialize_tensor_type_bindings()\n_tensor_classes: Set[Type] = set()\n\n\n################################################################################\n# Initialize extension\n################################################################################\n\ndef manager_path():\n if platform.system() == 'Windows':\n return b\"\"\n path = get_file_path('torch', 'bin', 'torch_shm_manager')\n prepare_multiprocessing_environment(get_file_path('torch'))\n if not os.path.exists(path):\n raise RuntimeError(\"Unable to find torch_shm_manager at \" + path)\n return path.encode('utf-8')\n\n\n# Shared memory manager needs to know the exact location of manager executable\n##这里调用了Module.cpp里面的c++代码\n#初始化一些python的class,其中有一部分功能是添加float32 float64....这样的对象类型\n#还有FloatTensor DoubleTensor这些对象\n_C._initExtension(manager_path())\ndel manager_path\n\n# Appease the type checker: it can't deal with direct setting of globals().\n# Note that we will see \"too many\" functions when reexporting this way; there\n# is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions\n# so that this import is good enough\nif False:\n from torch._C._VariableFunctions import *\n\nfor name in dir(_C._VariableFunctions):\n if name.startswith('__'):\n continue\n globals()[name] = getattr(_C._VariableFunctions, name)\n #再次向__all__中添加内容,使得可以通过torch.使用\n __all__.append(name)\n\n################################################################################\n# Import interface functions defined in Python\n################################################################################\n\n# needs to be after the above ATen bindings so we can overwrite from Python side\nfrom .functional import *\n\n\n################################################################################\n# Remove unnecessary members\n################################################################################\n\ndel DoubleStorageBase\ndel FloatStorageBase\ndel LongStorageBase\ndel IntStorageBase\ndel ShortStorageBase\ndel CharStorageBase\ndel ByteStorageBase\ndel BoolStorageBase\ndel QUInt8StorageBase\ndel BFloat16StorageBase\ndel ComplexDoubleStorageBase\ndel ComplexFloatStorageBase\n\n################################################################################\n# Import most common subpackages\n################################################################################\n\nimport torch.cuda\nimport torch.autograd\nfrom torch.autograd import no_grad, enable_grad, set_grad_enabled\nimport torch.futures\nimport torch.nn\nimport torch.nn.intrinsic\nimport torch.nn.quantized\nimport torch.optim\nimport torch.multiprocessing\nimport torch.sparse\nimport torch.utils.backcompat\nimport torch.onnx\nimport torch.jit\nimport torch.hub\nimport torch.random\nimport torch.distributions\nimport torch.testing\nimport torch.backends.cuda\nimport torch.backends.mkl\nimport torch.backends.mkldnn\nimport torch.backends.openmp\nimport torch.backends.quantized\nimport torch.quantization\nimport torch.utils.data\nimport torch.__config__\nimport torch.__future__\n#这里调用了Module.cpp里面的c++代码\n_C._init_names(list(torch._storage_classes))\n\n# attach docstrings to torch and tensor functions\nfrom . import _torch_docs, _tensor_docs, _storage_docs\ndel _torch_docs, _tensor_docs, _storage_docs\n\n\ndef compiled_with_cxx11_abi():\n r\"\"\"Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1\"\"\"\n return _C._GLIBCXX_USE_CXX11_ABI\n\n\n# Import the ops \"namespace\"\nfrom torch._ops import ops\nfrom torch._classes import classes\n\n# Import the quasi random sampler\nimport torch.quasirandom\n\n# If you are seeing this, it means that this call site was not checked if\n# the memory format could be preserved, and it was switched to old default\n# behaviour of contiguous\nlegacy_contiguous_format = contiguous_format\n\n# Register fork handler to initialize OpenMP in child processes (see gh-28389)\nfrom torch.multiprocessing._atfork import register_after_fork\nregister_after_fork(torch.get_num_threads)\ndel register_after_fork\n\n# Import tools that require fully imported torch (for applying\n# torch.jit.script as a decorator, for instance):\nfrom ._lobpcg import lobpcg\n\n# These were previously defined in native_functions.yaml and appeared on the\n# `torch` namespace, but we moved them to c10 dispatch to facilitate custom\n# class usage. We add these lines here to preserve backward compatbility.\nquantized_lstm = torch.ops.aten.quantized_lstm\nquantized_gru = torch.ops.aten.quantized_gru\n", "import warnings\nfrom typing import Tuple, Optional\n\nimport torch\nfrom torch import Tensor\nfrom .linear import _LinearWithBias\nfrom torch.nn.init import xavier_uniform_\nfrom torch.nn.init import constant_\nfrom torch.nn.init import xavier_normal_\nfrom torch.nn.parameter import Parameter\nfrom .module import Module\nfrom .. import functional as F\n\n\nclass Threshold(Module):\n r\"\"\"Thresholds each element of the input Tensor.\n\n Threshold is defined as:\n\n .. math::\n y =\n \\begin{cases}\n x, &\\text{ if } x > \\text{threshold} \\\\\n \\text{value}, &\\text{ otherwise }\n \\end{cases}\n\n Args:\n threshold: The value to threshold at\n value: The value to replace with\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n Examples::\n\n >>> m = nn.Threshold(0.1, 20)\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['threshold', 'value', 'inplace']\n\n threshold: float\n value: float\n inplace: bool\n\n def __init__(self, threshold: float, value: float, inplace: bool = False) -> None:\n super(Threshold, self).__init__()\n self.threshold = threshold\n self.value = value\n self.inplace = inplace\n # TODO: check in THNN (if inplace == True, then assert value <= threshold)\n\n def forward(self, input: Tensor) -> Tensor:\n return F.threshold(input, self.threshold, self.value, self.inplace)\n\n def extra_repr(self):\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'threshold={}, value={}{}'.format(\n self.threshold, self.value, inplace_str\n )\n\n\nclass ReLU(Module):\n r\"\"\"Applies the rectified linear unit function element-wise:\n\n :math:`\\text{ReLU}(x) = (x)^+ = \\max(0, x)`\n\n Args:\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/ReLU.png\n\n Examples::\n\n >>> m = nn.ReLU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n\n\n An implementation of CReLU - https://arxiv.org/abs/1603.05201\n\n >>> m = nn.ReLU()\n >>> input = torch.randn(2).unsqueeze(0)\n >>> output = torch.cat((m(input),m(-input)))\n \"\"\"\n __constants__ = ['inplace']\n inplace: bool\n\n def __init__(self, inplace: bool = False):\n super(ReLU, self).__init__()\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.relu(input, inplace=self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = 'inplace=True' if self.inplace else ''\n return inplace_str\n\n\nclass RReLU(Module):\n r\"\"\"Applies the randomized leaky rectified liner unit function, element-wise,\n as described in the paper:\n\n `Empirical Evaluation of Rectified Activations in Convolutional Network`_.\n\n The function is defined as:\n\n .. math::\n \\text{RReLU}(x) =\n \\begin{cases}\n x & \\text{if } x \\geq 0 \\\\\n ax & \\text{ otherwise }\n \\end{cases}\n\n where :math:`a` is randomly sampled from uniform distribution\n :math:`\\mathcal{U}(\\text{lower}, \\text{upper})`.\n\n See: https://arxiv.org/pdf/1505.00853.pdf\n\n Args:\n lower: lower bound of the uniform distribution. Default: :math:`\\frac{1}{8}`\n upper: upper bound of the uniform distribution. Default: :math:`\\frac{1}{3}`\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n Examples::\n\n >>> m = nn.RReLU(0.1, 0.3)\n >>> input = torch.randn(2)\n >>> output = m(input)\n\n .. _`Empirical Evaluation of Rectified Activations in Convolutional Network`:\n https://arxiv.org/abs/1505.00853\n \"\"\"\n __constants__ = ['lower', 'upper', 'inplace']\n\n lower: float\n upper: float\n inplace: bool\n\n def __init__(\n self,\n lower: float = 1. / 8,\n upper: float = 1. / 3,\n inplace: bool = False\n ):\n super(RReLU, self).__init__()\n self.lower = lower\n self.upper = upper\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.rrelu(input, self.lower, self.upper, self.training, self.inplace)\n\n def extra_repr(self):\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'lower={}, upper={}{}'.format(self.lower, self.upper, inplace_str)\n\n\nclass Hardtanh(Module):\n r\"\"\"Applies the HardTanh function element-wise\n\n HardTanh is defined as:\n\n .. math::\n \\text{HardTanh}(x) = \\begin{cases}\n 1 & \\text{ if } x > 1 \\\\\n -1 & \\text{ if } x < -1 \\\\\n x & \\text{ otherwise } \\\\\n \\end{cases}\n\n The range of the linear region :math:`[-1, 1]` can be adjusted using\n :attr:`min_val` and :attr:`max_val`.\n\n Args:\n min_val: minimum value of the linear region range. Default: -1\n max_val: maximum value of the linear region range. Default: 1\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Keyword arguments :attr:`min_value` and :attr:`max_value`\n have been deprecated in favor of :attr:`min_val` and :attr:`max_val`.\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Hardtanh.png\n\n Examples::\n\n >>> m = nn.Hardtanh(-2, 2)\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['min_val', 'max_val', 'inplace']\n\n min_val: float\n max_val: float\n inplace: bool\n\n def __init__(\n self,\n min_val: float = -1.,\n max_val: float = 1.,\n inplace: bool = False,\n min_value: Optional[float] = None,\n max_value: Optional[float] = None\n ) -> None:\n super(Hardtanh, self).__init__()\n if min_value is not None:\n warnings.warn(\"keyword argument min_value is deprecated and rename to min_val\")\n min_val = min_value\n if max_value is not None:\n warnings.warn(\"keyword argument max_value is deprecated and rename to max_val\")\n max_val = max_value\n\n self.min_val = min_val\n self.max_val = max_val\n self.inplace = inplace\n assert self.max_val > self.min_val\n\n def forward(self, input: Tensor) -> Tensor:\n return F.hardtanh(input, self.min_val, self.max_val, self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'min_val={}, max_val={}{}'.format(\n self.min_val, self.max_val, inplace_str\n )\n\n\nclass ReLU6(Hardtanh):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{ReLU6}(x) = \\min(\\max(0,x), 6)\n\n Args:\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/ReLU6.png\n\n Examples::\n\n >>> m = nn.ReLU6()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def __init__(self, inplace: bool = False):\n super(ReLU6, self).__init__(0., 6., inplace)\n\n def extra_repr(self) -> str:\n inplace_str = 'inplace=True' if self.inplace else ''\n return inplace_str\n\n\nclass Sigmoid(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{Sigmoid}(x) = \\sigma(x) = \\frac{1}{1 + \\exp(-x)}\n\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Sigmoid.png\n\n Examples::\n\n >>> m = nn.Sigmoid()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return torch.sigmoid(input)\n\n\nclass Hardsigmoid(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{Hardsigmoid}(x) = \\begin{cases}\n 0 & \\text{if~} x \\le -3, \\\\\n 1 & \\text{if~} x \\ge +3, \\\\\n x / 6 + 1 / 2 & \\text{otherwise}\n \\end{cases}\n\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n Examples::\n\n >>> m = nn.Hardsigmoid()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return F.hardsigmoid(input)\n\n\nclass Tanh(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{Tanh}(x) = \\tanh(x) = \\frac{\\exp(x) - \\exp(-x)} {\\exp(x) + \\exp(-x)}\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Tanh.png\n\n Examples::\n\n >>> m = nn.Tanh()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return torch.tanh(input)\n\n\nclass Hardswish(Module):\n r\"\"\"Applies the hardswish function, element-wise, as described in the paper:\n\n `Searching for MobileNetV3`_.\n\n .. math::\n \\text{Hardswish}(x) = \\begin{cases}\n 0 & \\text{if~} x \\le -3, \\\\\n x & \\text{if~} x \\ge +3, \\\\\n x \\cdot (x + 3) /6 & \\text{otherwise}\n \\end{cases}\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n Examples::\n\n >>> m = nn.Hardswish()\n >>> input = torch.randn(2)\n >>> output = m(input)\n\n .. _`Searching for MobileNetV3`:\n https://arxiv.org/abs/1905.02244\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return F.hardswish(input)\n\n\nclass ELU(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{ELU}(x) = \\max(0,x) + \\min(0, \\alpha * (\\exp(x) - 1))\n\n Args:\n alpha: the :math:`\\alpha` value for the ELU formulation. Default: 1.0\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/ELU.png\n\n Examples::\n\n >>> m = nn.ELU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['alpha', 'inplace']\n alpha: float\n inplace: bool\n\n def __init__(self, alpha: float = 1., inplace: bool = False) -> None:\n super(ELU, self).__init__()\n self.alpha = alpha\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.elu(input, self.alpha, self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'alpha={}{}'.format(self.alpha, inplace_str)\n\n\nclass CELU(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{CELU}(x) = \\max(0,x) + \\min(0, \\alpha * (\\exp(x/\\alpha) - 1))\n\n More details can be found in the paper `Continuously Differentiable Exponential Linear Units`_ .\n\n Args:\n alpha: the :math:`\\alpha` value for the CELU formulation. Default: 1.0\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/CELU.png\n\n Examples::\n\n >>> m = nn.CELU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n\n .. _`Continuously Differentiable Exponential Linear Units`:\n https://arxiv.org/abs/1704.07483\n \"\"\"\n __constants__ = ['alpha', 'inplace']\n alpha: float\n inplace: bool\n\n def __init__(self, alpha: float = 1., inplace: bool = False) -> None:\n super(CELU, self).__init__()\n self.alpha = alpha\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.celu(input, self.alpha, self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'alpha={}{}'.format(self.alpha, inplace_str)\n\n\nclass SELU(Module):\n r\"\"\"Applied element-wise, as:\n\n .. math::\n \\text{SELU}(x) = \\text{scale} * (\\max(0,x) + \\min(0, \\alpha * (\\exp(x) - 1)))\n\n with :math:`\\alpha = 1.6732632423543772848170429916717` and\n :math:`\\text{scale} = 1.0507009873554804934193349852946`.\n\n More details can be found in the paper `Self-Normalizing Neural Networks`_ .\n\n Args:\n inplace (bool, optional): can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/SELU.png\n\n Examples::\n\n >>> m = nn.SELU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n\n .. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515\n \"\"\"\n __constants__ = ['inplace']\n inplace: bool\n\n def __init__(self, inplace: bool = False) -> None:\n super(SELU, self).__init__()\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.selu(input, self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = 'inplace=True' if self.inplace else ''\n return inplace_str\n\n\nclass GLU(Module):\n r\"\"\"Applies the gated linear unit function\n :math:`{GLU}(a, b)= a \\otimes \\sigma(b)` where :math:`a` is the first half\n of the input matrices and :math:`b` is the second half.\n\n Args:\n dim (int): the dimension on which to split the input. Default: -1\n\n Shape:\n - Input: :math:`(\\ast_1, N, \\ast_2)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(\\ast_1, M, \\ast_2)` where :math:`M=N/2`\n\n Examples::\n\n >>> m = nn.GLU()\n >>> input = torch.randn(4, 2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['dim']\n dim: int\n\n def __init__(self, dim: int = -1) -> None:\n super(GLU, self).__init__()\n self.dim = dim\n\n def forward(self, input: Tensor) -> Tensor:\n return F.glu(input, self.dim)\n\n def extra_repr(self) -> str:\n return 'dim={}'.format(self.dim)\n\n\nclass GELU(Module):\n r\"\"\"Applies the Gaussian Error Linear Units function:\n\n .. math:: \\text{GELU}(x) = x * \\Phi(x)\n\n where :math:`\\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/GELU.png\n\n Examples::\n\n >>> m = nn.GELU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n def forward(self, input: Tensor) -> Tensor:\n return F.gelu(input)\n\n\nclass Hardshrink(Module):\n r\"\"\"Applies the hard shrinkage function element-wise:\n\n .. math::\n \\text{HardShrink}(x) =\n \\begin{cases}\n x, & \\text{ if } x > \\lambda \\\\\n x, & \\text{ if } x < -\\lambda \\\\\n 0, & \\text{ otherwise }\n \\end{cases}\n\n Args:\n lambd: the :math:`\\lambda` value for the Hardshrink formulation. Default: 0.5\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Hardshrink.png\n\n Examples::\n\n >>> m = nn.Hardshrink()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['lambd']\n lambd: float\n\n def __init__(self, lambd: float = 0.5) -> None:\n super(Hardshrink, self).__init__()\n self.lambd = lambd\n\n def forward(self, input: Tensor) -> Tensor:\n return F.hardshrink(input, self.lambd)\n\n def extra_repr(self) -> str:\n return '{}'.format(self.lambd)\n\n\nclass LeakyReLU(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{LeakyReLU}(x) = \\max(0, x) + \\text{negative\\_slope} * \\min(0, x)\n\n\n or\n\n .. math::\n \\text{LeakyRELU}(x) =\n \\begin{cases}\n x, & \\text{ if } x \\geq 0 \\\\\n \\text{negative\\_slope} \\times x, & \\text{ otherwise }\n \\end{cases}\n\n Args:\n negative_slope: Controls the angle of the negative slope. Default: 1e-2\n inplace: can optionally do the operation in-place. Default: ``False``\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/LeakyReLU.png\n\n Examples::\n\n >>> m = nn.LeakyReLU(0.1)\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['inplace', 'negative_slope']\n inplace: bool\n negative_slope: float\n\n def __init__(self, negative_slope: float = 1e-2, inplace: bool = False) -> None:\n super(LeakyReLU, self).__init__()\n self.negative_slope = negative_slope\n self.inplace = inplace\n\n def forward(self, input: Tensor) -> Tensor:\n return F.leaky_relu(input, self.negative_slope, self.inplace)\n\n def extra_repr(self) -> str:\n inplace_str = ', inplace=True' if self.inplace else ''\n return 'negative_slope={}{}'.format(self.negative_slope, inplace_str)\n\n\nclass LogSigmoid(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{LogSigmoid}(x) = \\log\\left(\\frac{ 1 }{ 1 + \\exp(-x)}\\right)\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/LogSigmoid.png\n\n Examples::\n\n >>> m = nn.LogSigmoid()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return F.logsigmoid(input)\n\n\nclass Softplus(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{Softplus}(x) = \\frac{1}{\\beta} * \\log(1 + \\exp(\\beta * x))\n\n SoftPlus is a smooth approximation to the ReLU function and can be used\n to constrain the output of a machine to always be positive.\n\n For numerical stability the implementation reverts to the linear function\n when :math:`input \\times \\beta > threshold`.\n\n Args:\n beta: the :math:`\\beta` value for the Softplus formulation. Default: 1\n threshold: values above this revert to a linear function. Default: 20\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Softplus.png\n\n Examples::\n\n >>> m = nn.Softplus()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['beta', 'threshold']\n beta: int\n threshold: int\n\n def __init__(self, beta: int = 1, threshold: int = 20) -> None:\n super(Softplus, self).__init__()\n self.beta = beta\n self.threshold = threshold\n\n def forward(self, input: Tensor) -> Tensor:\n return F.softplus(input, self.beta, self.threshold)\n\n def extra_repr(self) -> str:\n return 'beta={}, threshold={}'.format(self.beta, self.threshold)\n\n\nclass Softshrink(Module):\n r\"\"\"Applies the soft shrinkage function elementwise:\n\n .. math::\n \\text{SoftShrinkage}(x) =\n \\begin{cases}\n x - \\lambda, & \\text{ if } x > \\lambda \\\\\n x + \\lambda, & \\text{ if } x < -\\lambda \\\\\n 0, & \\text{ otherwise }\n \\end{cases}\n\n Args:\n lambd: the :math:`\\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Softshrink.png\n\n Examples::\n\n >>> m = nn.Softshrink()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['lambd']\n lambd: float\n\n def __init__(self, lambd: float = 0.5) -> None:\n super(Softshrink, self).__init__()\n self.lambd = lambd\n\n def forward(self, input: Tensor) -> Tensor:\n return F.softshrink(input, self.lambd)\n\n def extra_repr(self) -> str:\n return str(self.lambd)\n\n\nclass MultiheadAttention(Module):\n r\"\"\"Allows the model to jointly attend to information\n from different representation subspaces.\n See reference: Attention Is All You Need\n\n .. math::\n \\text{MultiHead}(Q, K, V) = \\text{Concat}(head_1,\\dots,head_h)W^O\n \\text{where} head_i = \\text{Attention}(QW_i^Q, KW_i^K, VW_i^V)\n\n Args:\n embed_dim: total dimension of the model.\n num_heads: parallel attention heads.\n dropout: a Dropout layer on attn_output_weights. Default: 0.0.\n bias: add bias as module parameter. Default: True.\n add_bias_kv: add bias to the key and value sequences at dim=0.\n add_zero_attn: add a new batch of zeros to the key and\n value sequences at dim=1.\n kdim: total number of features in key. Default: None.\n vdim: total number of features in value. Default: None.\n\n Note: if kdim and vdim are None, they will be set to embed_dim such that\n query, key, and value have the same number of features.\n\n Examples::\n\n >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)\n >>> attn_output, attn_output_weights = multihead_attn(query, key, value)\n \"\"\"\n __annotations__ = {\n 'bias_k': torch._jit_internal.Optional[torch.Tensor],\n 'bias_v': torch._jit_internal.Optional[torch.Tensor],\n }\n\n def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None):\n super(MultiheadAttention, self).__init__()\n self.embed_dim = embed_dim\n self.kdim = kdim if kdim is not None else embed_dim\n self.vdim = vdim if vdim is not None else embed_dim\n self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim\n\n self.num_heads = num_heads\n self.dropout = dropout\n self.head_dim = embed_dim // num_heads\n assert self.head_dim * num_heads == self.embed_dim, \"embed_dim must be divisible by num_heads\"\n\n if self._qkv_same_embed_dim is False:\n self.q_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim))\n self.k_proj_weight = Parameter(torch.Tensor(embed_dim, self.kdim))\n self.v_proj_weight = Parameter(torch.Tensor(embed_dim, self.vdim))\n self.register_parameter('in_proj_weight', None)\n else:\n self.in_proj_weight = Parameter(torch.empty(3 * embed_dim, embed_dim))\n self.register_parameter('q_proj_weight', None)\n self.register_parameter('k_proj_weight', None)\n self.register_parameter('v_proj_weight', None)\n\n if bias:\n self.in_proj_bias = Parameter(torch.empty(3 * embed_dim))\n else:\n self.register_parameter('in_proj_bias', None)\n self.out_proj = _LinearWithBias(embed_dim, embed_dim)\n\n if add_bias_kv:\n self.bias_k = Parameter(torch.empty(1, 1, embed_dim))\n self.bias_v = Parameter(torch.empty(1, 1, embed_dim))\n else:\n self.bias_k = self.bias_v = None\n\n self.add_zero_attn = add_zero_attn\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n if self._qkv_same_embed_dim:\n xavier_uniform_(self.in_proj_weight)\n else:\n xavier_uniform_(self.q_proj_weight)\n xavier_uniform_(self.k_proj_weight)\n xavier_uniform_(self.v_proj_weight)\n\n if self.in_proj_bias is not None:\n constant_(self.in_proj_bias, 0.)\n constant_(self.out_proj.bias, 0.)\n if self.bias_k is not None:\n xavier_normal_(self.bias_k)\n if self.bias_v is not None:\n xavier_normal_(self.bias_v)\n\n def __setstate__(self, state):\n # Support loading old MultiheadAttention checkpoints generated by v1.1.0\n if '_qkv_same_embed_dim' not in state:\n state['_qkv_same_embed_dim'] = True\n\n super(MultiheadAttention, self).__setstate__(state)\n\n def forward(self, query, key, value, key_padding_mask=None,\n need_weights=True, attn_mask=None):\n # type: (Tensor, Tensor, Tensor, Optional[Tensor], bool, Optional[Tensor]) -> Tuple[Tensor, Optional[Tensor]]\n r\"\"\"\n Args:\n query, key, value: map a query and a set of key-value pairs to an output.\n See \"Attention Is All You Need\" for more details.\n key_padding_mask: if provided, specified padding elements in the key will\n be ignored by the attention. When given a binary mask and a value is True,\n the corresponding value on the attention layer will be ignored. When given\n a byte mask and a value is non-zero, the corresponding value on the attention\n layer will be ignored\n need_weights: output attn_output_weights.\n attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all\n the batches while a 3D mask allows to specify a different mask for the entries of each batch.\n\n Shape:\n - Inputs:\n - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is\n the embedding dimension.\n - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is\n the embedding dimension.\n - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is\n the embedding dimension.\n - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.\n If a ByteTensor is provided, the non-zero positions will be ignored while the position\n with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the\n value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.\n - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.\n 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,\n S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked\n positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend\n while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``\n is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor\n is provided, it will be added to the attention weight.\n\n - Outputs:\n - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,\n E is the embedding dimension.\n - attn_output_weights: :math:`(N, L, S)` where N is the batch size,\n L is the target sequence length, S is the source sequence length.\n \"\"\"\n if not self._qkv_same_embed_dim:\n return F.multi_head_attention_forward(\n query, key, value, self.embed_dim, self.num_heads,\n self.in_proj_weight, self.in_proj_bias,\n self.bias_k, self.bias_v, self.add_zero_attn,\n self.dropout, self.out_proj.weight, self.out_proj.bias,\n training=self.training,\n key_padding_mask=key_padding_mask, need_weights=need_weights,\n attn_mask=attn_mask, use_separate_proj_weight=True,\n q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,\n v_proj_weight=self.v_proj_weight)\n else:\n return F.multi_head_attention_forward(\n query, key, value, self.embed_dim, self.num_heads,\n self.in_proj_weight, self.in_proj_bias,\n self.bias_k, self.bias_v, self.add_zero_attn,\n self.dropout, self.out_proj.weight, self.out_proj.bias,\n training=self.training,\n key_padding_mask=key_padding_mask, need_weights=need_weights,\n attn_mask=attn_mask)\n\n\nclass PReLU(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{PReLU}(x) = \\max(0,x) + a * \\min(0,x)\n\n or\n\n .. math::\n \\text{PReLU}(x) =\n \\begin{cases}\n x, & \\text{ if } x \\geq 0 \\\\\n ax, & \\text{ otherwise }\n \\end{cases}\n\n Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single\n parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,\n a separate :math:`a` is used for each input channel.\n\n\n .. note::\n weight decay should not be used when learning :math:`a` for good performance.\n\n .. note::\n Channel dim is the 2nd dim of input. When input has dims < 2, then there is\n no channel dim and the number of channels = 1.\n\n Args:\n num_parameters (int): number of :math:`a` to learn.\n Although it takes an int as input, there is only two values are legitimate:\n 1, or the number of channels at input. Default: 1\n init (float): the initial value of :math:`a`. Default: 0.25\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n Attributes:\n weight (Tensor): the learnable weights of shape (:attr:`num_parameters`).\n\n .. image:: ../scripts/activation_images/PReLU.png\n\n Examples::\n\n >>> m = nn.PReLU()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['num_parameters']\n num_parameters: int\n\n def __init__(self, num_parameters: int = 1, init: float = 0.25) -> None:\n self.num_parameters = num_parameters\n super(PReLU, self).__init__()\n self.weight = Parameter(torch.Tensor(num_parameters).fill_(init))\n\n def forward(self, input: Tensor) -> Tensor:\n return F.prelu(input, self.weight)\n\n def extra_repr(self) -> str:\n return 'num_parameters={}'.format(self.num_parameters)\n\n\nclass Softsign(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{SoftSign}(x) = \\frac{x}{ 1 + |x|}\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Softsign.png\n\n Examples::\n\n >>> m = nn.Softsign()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return F.softsign(input)\n\n\nclass Tanhshrink(Module):\n r\"\"\"Applies the element-wise function:\n\n .. math::\n \\text{Tanhshrink}(x) = x - \\tanh(x)\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(N, *)`, same shape as the input\n\n .. image:: ../scripts/activation_images/Tanhshrink.png\n\n Examples::\n\n >>> m = nn.Tanhshrink()\n >>> input = torch.randn(2)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n return F.tanhshrink(input)\n\n\nclass Softmin(Module):\n r\"\"\"Applies the Softmin function to an n-dimensional input Tensor\n rescaling them so that the elements of the n-dimensional output Tensor\n lie in the range `[0, 1]` and sum to 1.\n\n Softmin is defined as:\n\n .. math::\n \\text{Softmin}(x_{i}) = \\frac{\\exp(-x_i)}{\\sum_j \\exp(-x_j)}\n\n Shape:\n - Input: :math:`(*)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(*)`, same shape as the input\n\n Arguments:\n dim (int): A dimension along which Softmin will be computed (so every slice\n along dim will sum to 1).\n\n Returns:\n a Tensor of the same dimension and shape as the input, with\n values in the range [0, 1]\n\n Examples::\n\n >>> m = nn.Softmin()\n >>> input = torch.randn(2, 3)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['dim']\n dim: Optional[int]\n\n def __init__(self, dim: Optional[int] = None) -> None:\n super(Softmin, self).__init__()\n self.dim = dim\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n if not hasattr(self, 'dim'):\n self.dim = None\n\n def forward(self, input: Tensor) -> Tensor:\n return F.softmin(input, self.dim, _stacklevel=5)\n\n def extra_repr(self):\n return 'dim={dim}'.format(dim=self.dim)\n\nclass Softmax(Module):\n r\"\"\"Applies the Softmax function to an n-dimensional input Tensor\n rescaling them so that the elements of the n-dimensional output Tensor\n lie in the range [0,1] and sum to 1.\n\n Softmax is defined as:\n\n .. math::\n \\text{Softmax}(x_{i}) = \\frac{\\exp(x_i)}{\\sum_j \\exp(x_j)}\n\n When the input Tensor is a sparse tensor then the unspecifed\n values are treated as ``-inf``.\n\n Shape:\n - Input: :math:`(*)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(*)`, same shape as the input\n\n Returns:\n a Tensor of the same dimension and shape as the input with\n values in the range [0, 1]\n\n Arguments:\n dim (int): A dimension along which Softmax will be computed (so every slice\n along dim will sum to 1).\n\n .. note::\n This module doesn't work directly with NLLLoss,\n which expects the Log to be computed between the Softmax and itself.\n Use `LogSoftmax` instead (it's faster and has better numerical properties).\n\n Examples::\n\n >>> m = nn.Softmax(dim=1)\n >>> input = torch.randn(2, 3)\n >>> output = m(input)\n\n \"\"\"\n __constants__ = ['dim']\n dim: Optional[int]\n\n def __init__(self, dim: Optional[int] = None) -> None:\n super(Softmax, self).__init__()\n self.dim = dim\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n if not hasattr(self, 'dim'):\n self.dim = None\n\n def forward(self, input: Tensor) -> Tensor:\n return F.softmax(input, self.dim, _stacklevel=5)\n\n def extra_repr(self) -> str:\n return 'dim={dim}'.format(dim=self.dim)\n\n\nclass Softmax2d(Module):\n r\"\"\"Applies SoftMax over features to each spatial location.\n\n When given an image of ``Channels x Height x Width``, it will\n apply `Softmax` to each location :math:`(Channels, h_i, w_j)`\n\n Shape:\n - Input: :math:`(N, C, H, W)`\n - Output: :math:`(N, C, H, W)` (same shape as input)\n\n Returns:\n a Tensor of the same dimension and shape as the input with\n values in the range [0, 1]\n\n Examples::\n\n >>> m = nn.Softmax2d()\n >>> # you softmax over the 2nd dimension\n >>> input = torch.randn(2, 3, 12, 13)\n >>> output = m(input)\n \"\"\"\n\n def forward(self, input: Tensor) -> Tensor:\n assert input.dim() == 4, 'Softmax2d requires a 4D tensor as input'\n return F.softmax(input, 1, _stacklevel=5)\n\n\nclass LogSoftmax(Module):\n r\"\"\"Applies the :math:`\\log(\\text{Softmax}(x))` function to an n-dimensional\n input Tensor. The LogSoftmax formulation can be simplified as:\n\n .. math::\n \\text{LogSoftmax}(x_{i}) = \\log\\left(\\frac{\\exp(x_i) }{ \\sum_j \\exp(x_j)} \\right)\n\n Shape:\n - Input: :math:`(*)` where `*` means, any number of additional\n dimensions\n - Output: :math:`(*)`, same shape as the input\n\n Arguments:\n dim (int): A dimension along which LogSoftmax will be computed.\n\n Returns:\n a Tensor of the same dimension and shape as the input with\n values in the range [-inf, 0)\n\n Examples::\n\n >>> m = nn.LogSoftmax()\n >>> input = torch.randn(2, 3)\n >>> output = m(input)\n \"\"\"\n __constants__ = ['dim']\n dim: Optional[int]\n\n def __init__(self, dim: Optional[int] = None) -> None:\n super(LogSoftmax, self).__init__()\n self.dim = dim\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n if not hasattr(self, 'dim'):\n self.dim = None\n\n def forward(self, input: Tensor) -> Tensor:\n return F.log_softmax(input, self.dim, _stacklevel=5)\n\n def extra_repr(self):\n return 'dim={dim}'.format(dim=self.dim)\n", "import operator_benchmark as op_bench\nimport torch\n\n\n\"\"\"Microbenchmarks for remainder operators.\"\"\"\n\n\n# Benchmark ops performance with broadcast\nremainder_ops_list = op_bench.op_list(\n attr_names=['op_name', 'op_func'],\n attrs=[\n ['fmod', torch.fmod],\n ['remainder', torch.remainder],\n ],\n)\n\nremainder_short_configs = op_bench.config_list(\n attr_names=['M', 'N', 'K'],\n attrs=[\n [1, 1, 1],\n [64, 64, 64],\n [64, 64, 128],\n ],\n cross_product_configs={\n 'device': ['cpu', 'cuda'],\n 'dtype' : [torch.int32, torch.float, torch.double],\n },\n tags=['short'],\n)\n\nremainder_long_configs = op_bench.cross_product_configs(\n M=[8, 128],\n N=[32, 64],\n K=[256, 512],\n device=['cpu', 'cuda'],\n dtype=[torch.int32, torch.float, torch.double],\n tags=['long']\n)\n\n\nclass RemainderOpBenchmark(op_bench.TorchBenchmarkBase):\n def init(self, M, N, K, device, dtype, op_func):\n self.dividend = torch.rand(M, N, K, device=device)\n self.dividend = (self.dividend * 1000 - 500).to(dtype=dtype)\n\n self.divisor = torch.rand(M, N, K, device=device)\n # +1 so we don't divide by zero\n self.divisor = (self.divisor * 40 + 1).to(dtype=dtype)\n\n self.op_func = op_func\n\n def forward(self):\n return self.op_func(self.dividend, self.divisor)\n\n\nop_bench.generate_pt_tests_from_op_list(remainder_ops_list,\n remainder_short_configs + remainder_long_configs,\n RemainderOpBenchmark)\n\n\nif __name__ == \"__main__\":\n op_bench.benchmark_runner.main()\n", "import torch\n\nimport torch.nn.functional as F\n\nwith torch.autograd.profiler.profile() as prof:\n input1 = torch.randn(1, 50, 2560)\n weight = torch.randn(7680,2560)\n bias = torch.randn(7680)\n m = F.linear(input1, weight, bias)\nprint(prof.key_averages().table(sort_by=\"self_cpu_time_total\"))\n\n\n\n# int_tensor = torch.ones(1, dtype=torch.uint8)\n\n# uint_tensor = torch.ones(1, dtype=torch.short)\n\n\n# x = torch.randn((6,8))\n# # print(x)\n# index_list = np.array([[2,1],[1,0]])\n# index_tensor = [torch.tensor(index_list[0]),torch.tensor(index_list[1])]\n\n# with torch.autograd.profiler.profile(record_shapes=True) as prof:\n# uint_tensor*=int_tensor\n# print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\"))\n# prof.export_chrome_trace(\"trace.json\")\n\n# x = torch.randn((1, 1), requires_grad=True)\n# with torch.autograd.profiler.profile() as prof:\n# for _ in range(100): # any normal python code, really!\n# y = x ** 2\n# y.backward()\n \n# print(prof.key_averages().table(sort_by=\"self_cpu_time_total\"))\n\n\n# print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\"))\n\n# with torch.autograd.profiler.profile() as prof:\n# x[index_list]\n# # x[0:2,[0]]\n# # # for _ in range(100): # any normal python code, really!\n# # # x[index_tensor]\n# print(prof.key_averages().table(sort_by=\"self_cpu_time_total\"))\n# x[torch.tensor(index_list)]\n# # print(x[0:2,0:1])\n# rows = np.array([[0,0],[3,3]])\n# cols = np.array([[0,2],[0,2]]) \n# y = x[rows,cols] \n# print(y)\n", "from __future__ import absolute_import, division, print_function, unicode_literals\nimport operator_benchmark as op_bench\nimport torch\n\nintraop_bench_configs = op_bench.config_list(\n attrs=[\n [8, 16],\n ],\n attr_names=[\"M\", \"N\"], \n tags=[\"short\"], \n)\n\[email protected]\ndef torch_sumall(a, iterations):\n # type: (Tensor, int)\n result = 0.0\n for _ in range(iterations):\n result += float(torch.sum(a))\n a[0][0] += 0.01\n return result\n\n\nclass TorchSumBenchmark(op_bench.TorchBenchmarkBase):\n def init(self, M, N):\n self.input_one = torch.rand(M, N)\n self.set_module_name(\"sum\")\n\n # This is a very temporary method and will be removed soon, so \n # don't use this method in your benchmark\n # TODO(mingzhe): use one forward method for both JIT and Eager \n def jit_forward(self, iters):\n return torch_sumall(self.input_one, iters)\n\nop_bench.generate_pt_test(intraop_bench_configs, TorchSumBenchmark)\n\n\nif __name__ == \"__main__\":\n op_bench.benchmark_runner.main()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom hypothesis import given\nimport hypothesis.strategies as st\n\nimport numpy as np\nimport unittest\n\nfrom caffe2.python import core, workspace, dyndep\nimport caffe2.python.hypothesis_test_util as hu\n\ndyndep.InitOpsLibrary(\"@/caffe2/caffe2/mpi:mpi_ops\")\n\n_has_mpi =False\nCOMM = None\nRANK = 0\nSIZE = 0\n\ndef SetupMPI():\n try:\n from mpi4py import MPI\n global _has_mpi, COMM, RANK, SIZE\n _has_mpi = core.IsOperatorWithEngine(\"CreateCommonWorld\", \"MPI\")\n COMM = MPI.COMM_WORLD\n RANK = COMM.Get_rank()\n SIZE = COMM.Get_size()\n except ImportError:\n _has_mpi = False\n\n\[email protected](not _has_mpi,\n \"MPI is not available. Skipping.\")\nclass TestMPI(hu.HypothesisTestCase):\n @given(X=hu.tensor(),\n root=st.integers(min_value=0, max_value=SIZE - 1),\n device_option=st.sampled_from(hu.device_options),\n **hu.gcs)\n def test_broadcast(self, X, root, device_option, gc, dc):\n # Use mpi4py's broadcast to make sure that all nodes inherit the\n # same hypothesis test.\n X = COMM.bcast(X)\n root = COMM.bcast(root)\n device_option = COMM.bcast(device_option)\n X[:] = RANK\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"CreateCommonWorld\", [], \"comm\", engine=\"MPI\",\n device_option=device_option)))\n self.assertTrue(workspace.FeedBlob(\"X\", X, device_option))\n mpi_op = core.CreateOperator(\n \"Broadcast\", [\"comm\", \"X\"], \"X\", engine=\"MPI\", root=root,\n device_option=device_option)\n self.assertTrue(workspace.RunOperatorOnce(mpi_op))\n new_X = workspace.FetchBlob(\"X\")\n np.testing.assert_array_equal(new_X, root)\n workspace.ResetWorkspace()\n\n @given(X=hu.tensor(),\n root=st.integers(min_value=0, max_value=SIZE - 1),\n device_option=st.sampled_from(hu.device_options),\n **hu.gcs)\n def test_reduce(self, X, root, device_option, gc, dc):\n # Use mpi4py's broadcast to make sure that all nodes inherit the\n # same hypothesis test.\n X = COMM.bcast(X)\n root = COMM.bcast(root)\n device_option = COMM.bcast(device_option)\n X[:] = RANK\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"CreateCommonWorld\", [], \"comm\", engine=\"MPI\",\n device_option=device_option)))\n self.assertTrue(workspace.FeedBlob(\"X\", X, device_option))\n mpi_op = core.CreateOperator(\n \"Reduce\", [\"comm\", \"X\"], \"X_reduced\", engine=\"MPI\", root=root,\n device_option=device_option)\n self.assertTrue(workspace.RunOperatorOnce(mpi_op))\n if (RANK == root):\n new_X = workspace.FetchBlob(\"X\")\n np.testing.assert_array_equal(new_X, root)\n workspace.ResetWorkspace()\n\n @given(X=hu.tensor(),\n root=st.integers(min_value=0, max_value=SIZE - 1),\n device_option=st.sampled_from(hu.device_options),\n inplace=st.booleans(),\n **hu.gcs)\n def test_allreduce(self, X, root, device_option, inplace, gc, dc):\n # Use mpi4py's broadcast to make sure that all nodes inherit the\n # same hypothesis test.\n X = COMM.bcast(X)\n root = COMM.bcast(root)\n device_option = COMM.bcast(device_option)\n inplace = COMM.bcast(inplace)\n X[:] = RANK\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"CreateCommonWorld\", [], \"comm\", engine=\"MPI\",\n device_option=device_option)))\n # Use mpi4py's broadcast to make sure that all copies have the same\n # tensor size.\n X = COMM.bcast(X)\n X[:] = RANK\n self.assertTrue(workspace.FeedBlob(\"X\", X, device_option))\n mpi_op = core.CreateOperator(\n \"Allreduce\", [\"comm\", \"X\"],\n \"X\" if inplace else \"X_reduced\",\n engine=\"MPI\", root=root,\n device_option=device_option)\n self.assertTrue(workspace.RunOperatorOnce(mpi_op))\n new_X = workspace.FetchBlob(\"X\" if inplace else \"X_reduced\")\n np.testing.assert_array_equal(new_X, SIZE * (SIZE - 1) / 2)\n workspace.ResetWorkspace()\n\n @given(X=hu.tensor(),\n device_option=st.sampled_from(hu.device_options),\n specify_send_blob=st.booleans(),\n specify_recv_blob=st.booleans(),\n **hu.gcs)\n def test_sendrecv(\n self, X, device_option, specify_send_blob, specify_recv_blob,\n gc, dc):\n # Use mpi4py's broadcast to make sure that all nodes inherit the\n # same hypothesis test.\n X = COMM.bcast(X)\n device_option = COMM.bcast(device_option)\n specify_send_blob = COMM.bcast(specify_send_blob)\n specify_recv_blob = COMM.bcast(specify_recv_blob)\n X[:] = RANK\n\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"CreateCommonWorld\", [], \"comm\", engine=\"MPI\",\n device_option=device_option)))\n self.assertTrue(workspace.FeedBlob(\"X\", X, device_option))\n for src in range(SIZE):\n for dst in range(SIZE):\n tag = src * SIZE + dst\n if src == dst:\n continue\n elif RANK == src:\n X[:] = RANK\n self.assertTrue(workspace.FeedBlob(\"X\", X, device_option))\n if specify_send_blob:\n self.assertTrue(workspace.FeedBlob(\n \"dst\", np.array(dst, dtype=np.int32)))\n self.assertTrue(workspace.FeedBlob(\n \"tag\", np.array(tag, dtype=np.int32)))\n mpi_op = core.CreateOperator(\n \"SendTensor\", [\"comm\", \"X\", \"dst\", \"tag\"], [],\n engine=\"MPI\", raw_buffer=True,\n device_option=device_option)\n else:\n mpi_op = core.CreateOperator(\n \"SendTensor\", [\"comm\", \"X\"], [], engine=\"MPI\",\n dst=dst, tag=tag, raw_buffer=True,\n device_option=device_option)\n self.assertTrue(workspace.RunOperatorOnce(mpi_op))\n elif RANK == dst:\n if specify_recv_blob:\n self.assertTrue(workspace.FeedBlob(\n \"src\", np.array(src, dtype=np.int32)))\n self.assertTrue(workspace.FeedBlob(\n \"tag\", np.array(tag, dtype=np.int32)))\n mpi_op = core.CreateOperator(\n \"ReceiveTensor\", [\"comm\", \"X\", \"src\", \"tag\"],\n [\"X\", \"src\", \"tag\"],\n engine=\"MPI\",\n src=src, tag=tag, raw_buffer=True,\n device_option=device_option)\n else:\n mpi_op = core.CreateOperator(\n \"ReceiveTensor\", [\"comm\", \"X\"], [\"X\", \"src\", \"tag\"],\n engine=\"MPI\",\n src=src, tag=tag, raw_buffer=True,\n device_option=device_option)\n self.assertTrue(workspace.RunOperatorOnce(mpi_op))\n received = workspace.FetchBlob(\"X\")\n np.testing.assert_array_equal(received, src)\n src_blob = workspace.FetchBlob(\"src\")\n np.testing.assert_array_equal(src_blob, src)\n tag_blob = workspace.FetchBlob(\"tag\")\n np.testing.assert_array_equal(tag_blob, tag)\n # simply wait for the guys to finish\n COMM.barrier()\n workspace.ResetWorkspace()\n\nif __name__ == \"__main__\":\n SetupMPI()\n import unittest\n unittest.main()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom caffe2.python.test_util import TestCase\nfrom caffe2.python import workspace, brew\nfrom caffe2.python.model_helper import ModelHelper\nfrom caffe2.python.predictor import mobile_exporter\nimport numpy as np\n\n\nclass TestMobileExporter(TestCase):\n def test_mobile_exporter(self):\n model = ModelHelper(name=\"mobile_exporter_test_model\")\n # Test LeNet\n brew.conv(model, 'data', 'conv1', dim_in=1, dim_out=20, kernel=5)\n brew.max_pool(model, 'conv1', 'pool1', kernel=2, stride=2)\n brew.conv(model, 'pool1', 'conv2', dim_in=20, dim_out=50, kernel=5)\n brew.max_pool(model, 'conv2', 'pool2', kernel=2, stride=2)\n brew.fc(model, 'pool2', 'fc3', dim_in=50 * 4 * 4, dim_out=500)\n brew.relu(model, 'fc3', 'fc3')\n brew.fc(model, 'fc3', 'pred', 500, 10)\n brew.softmax(model, 'pred', 'out')\n\n # Create our mobile exportable networks\n workspace.RunNetOnce(model.param_init_net)\n init_net, predict_net = mobile_exporter.Export(\n workspace, model.net, model.params\n )\n\n # Populate the workspace with data\n np_data = np.random.rand(1, 1, 28, 28).astype(np.float32)\n workspace.FeedBlob(\"data\", np_data)\n\n workspace.CreateNet(model.net)\n workspace.RunNet(model.net)\n ref_out = workspace.FetchBlob(\"out\")\n\n # Clear the workspace\n workspace.ResetWorkspace()\n\n # Populate the workspace with data\n workspace.RunNetOnce(init_net)\n # Fake \"data\" is populated by init_net, we have to replace it\n workspace.FeedBlob(\"data\", np_data)\n\n # Overwrite the old net\n workspace.CreateNet(predict_net, True)\n workspace.RunNet(predict_net.name)\n manual_run_out = workspace.FetchBlob(\"out\")\n np.testing.assert_allclose(\n ref_out, manual_run_out, atol=1e-10, rtol=1e-10\n )\n\n # Clear the workspace\n workspace.ResetWorkspace()\n\n # Predictor interface test (simulates writing to disk)\n predictor = workspace.Predictor(\n init_net.SerializeToString(), predict_net.SerializeToString()\n )\n\n # Output is a vector of outputs but we only care about the first and only result\n predictor_out = predictor.run([np_data])\n assert len(predictor_out) == 1\n predictor_out = predictor_out[0]\n\n np.testing.assert_allclose(\n ref_out, predictor_out, atol=1e-10, rtol=1e-10\n )\n\n def test_mobile_exporter_datatypes(self):\n model = ModelHelper(name=\"mobile_exporter_test_model\")\n model.Copy(\"data_int\", \"out\")\n model.params.append(\"data_int\")\n model.Copy(\"data_obj\", \"out_obj\")\n model.params.append(\"data_obj\")\n\n # Create our mobile exportable networks\n workspace.RunNetOnce(model.param_init_net)\n np_data_int = np.random.randint(100, size=(1, 1, 28, 28), dtype=np.int32)\n workspace.FeedBlob(\"data_int\", np_data_int)\n np_data_obj = np.array(['aa', 'bb']).astype(np.dtype('O'))\n workspace.FeedBlob(\"data_obj\", np_data_obj)\n\n init_net, predict_net = mobile_exporter.Export(\n workspace, model.net, model.params\n )\n\n workspace.CreateNet(model.net)\n workspace.RunNet(model.net)\n ref_out = workspace.FetchBlob(\"out\")\n ref_out_obj = workspace.FetchBlob(\"out_obj\")\n\n # Clear the workspace\n workspace.ResetWorkspace()\n\n # Populate the workspace with data\n workspace.RunNetOnce(init_net)\n\n # Overwrite the old net\n workspace.CreateNet(predict_net, True)\n workspace.RunNet(predict_net.name)\n manual_run_out = workspace.FetchBlob(\"out\")\n manual_run_out_obj = workspace.FetchBlob(\"out_obj\")\n np.testing.assert_allclose(\n ref_out, manual_run_out, atol=1e-10, rtol=1e-10\n )\n np.testing.assert_equal(ref_out_obj, manual_run_out_obj)\n\n # Clear the workspace\n workspace.ResetWorkspace()\n\n # Predictor interface test (simulates writing to disk)\n predictor = workspace.Predictor(\n init_net.SerializeToString(), predict_net.SerializeToString()\n )\n\n # Output is a vector of outputs.\n predictor_out = predictor.run([])\n assert len(predictor_out) == 2\n predictor_out_int = predictor_out[1]\n predictor_out_obj = predictor_out[0]\n # The order in predictor_out is non-deterministic. Use type of the entry\n # to figure out what to compare it to.\n if isinstance(predictor_out[1][0], bytes):\n predictor_out_int = predictor_out[0]\n predictor_out_obj = predictor_out[1]\n np.testing.assert_allclose(\n ref_out, predictor_out_int, atol=1e-10, rtol=1e-10\n )\n np.testing.assert_equal(ref_out_obj, predictor_out_obj)\n", "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport collections\n\nimport caffe2.python.hypothesis_test_util as hu\nimport hypothesis.strategies as st\nimport numpy as np\nfrom caffe2.python import core, dyndep, workspace\nfrom caffe2.quantization.server.dnnlowp_test_utils import check_quantized_results_close\nfrom hypothesis import given\n\n\ndyndep.InitOpsLibrary(\"//caffe2/caffe2/quantization/server:dnnlowp_ops\")\nworkspace.GlobalInit([\"caffe2\", \"--caffe2_omp_num_threads=11\"])\n\n\nclass DNNLowPAddOpTest(hu.HypothesisTestCase):\n @given(\n N=st.integers(32, 256),\n is_empty=st.booleans(),\n in_quantized=st.booleans(),\n out_quantized=st.booleans(),\n in_place=st.sampled_from([(False, False), (True, False), (False, True)]),\n **hu.gcs_cpu_only\n )\n def test_dnnlowp_elementwise_add_int(\n self, N, is_empty, in_quantized, out_quantized, in_place, gc, dc\n ):\n if is_empty:\n N = 0\n # FIXME: DNNLOWP Add doesn't support inplace operation and\n # dequantize_output=1 at the same time\n if in_place[0] or in_place[1]:\n in_quantized = True\n out_quantized = True\n\n # A has scale 1, so exactly represented after quantization\n min_ = -100\n max_ = min_ + 255\n A = np.round(np.random.rand(N) * (max_ - min_) + min_)\n A = A.astype(np.float32)\n if N != 0:\n A[0] = min_\n A[1] = max_\n\n # B has scale 1/2, so exactly represented after quantization\n B = np.round(np.random.rand(N) * 255 / 2 - 64).astype(np.float32)\n if N != 0:\n B[0] = -64\n B[1] = 127.0 / 2\n\n Output = collections.namedtuple(\"Output\", [\"Y\", \"op_type\", \"engine\"])\n outputs = []\n\n op_engine_list = [(\"Add\", \"\"), (\"Add\", \"DNNLOWP\"), (\"Int8Add\", \"DNNLOWP\")]\n\n for op_type, engine in op_engine_list:\n net = core.Net(\"test_net\")\n\n do_quantize = \"DNNLOWP\" in engine and in_quantized\n do_dequantize = \"DNNLOWP\" in engine and out_quantized\n\n if do_quantize:\n quantize_A = core.CreateOperator(\n \"Quantize\", [\"A\"], [\"A_q\"], engine=engine, device_option=gc\n )\n net.Proto().op.extend([quantize_A])\n\n quantize_B = core.CreateOperator(\n \"Quantize\", [\"B\"], [\"B_q\"], engine=engine, device_option=gc\n )\n net.Proto().op.extend([quantize_B])\n\n out = \"Y\"\n if in_place[0]:\n out = \"A\"\n elif in_place[1]:\n out = \"B\"\n\n add = core.CreateOperator(\n op_type,\n [\"A_q\", \"B_q\"] if do_quantize else [\"A\", \"B\"],\n [(out + \"_q\") if do_dequantize else out],\n dequantize_output=not do_dequantize,\n engine=engine,\n device_option=gc,\n )\n net.Proto().op.extend([add])\n\n if do_dequantize:\n dequantize = core.CreateOperator(\n \"Dequantize\", [out + \"_q\"], [out], engine=engine, device_option=gc\n )\n net.Proto().op.extend([dequantize])\n\n self.ws.create_blob(\"A\").feed(A, device_option=gc)\n self.ws.create_blob(\"B\").feed(B, device_option=gc)\n self.ws.run(net)\n outputs.append(\n Output(Y=self.ws.blobs[out].fetch(), op_type=op_type, engine=engine)\n )\n\n check_quantized_results_close(outputs)\n\n @given(**hu.gcs_cpu_only)\n def test_dnnlowp_elementwise_add_broadcast(self, gc, dc):\n # Set broadcast and no axis, i.e. broadcasting last dimensions.\n min_ = -100\n max_ = min_ + 255\n A = np.round(np.random.rand(2, 3, 4, 5) * (max_ - min_) + min_)\n A = A.astype(np.float32)\n A[0, 0, 0, 0] = min_\n A[0, 0, 0, 1] = max_\n\n B = np.round(np.random.rand(4, 5) * 255 / 2 - 64).astype(np.float32)\n B[0, 0] = -64\n B[0, 1] = 127.0 / 2\n\n Output = collections.namedtuple(\"Output\", [\"Y\", \"op_type\", \"engine\"])\n outputs = []\n\n op_engine_list = [(\"Add\", \"\"), (\"Add\", \"DNNLOWP\"), (\"Int8Add\", \"DNNLOWP\")]\n\n for op_type, engine in op_engine_list:\n net = core.Net(\"test_net\")\n\n add = core.CreateOperator(\n op_type,\n [\"A\", \"B\"],\n [\"Y\"],\n engine=engine,\n device_option=gc,\n broadcast=1,\n dequantize_output=1,\n )\n net.Proto().op.extend([add])\n\n self.ws.create_blob(\"A\").feed(A, device_option=gc)\n self.ws.create_blob(\"B\").feed(B, device_option=gc)\n self.ws.run(net)\n outputs.append(\n Output(Y=self.ws.blobs[\"Y\"].fetch(), op_type=op_type, engine=engine)\n )\n\n check_quantized_results_close(outputs)\n\n @given(**hu.gcs_cpu_only)\n def test_dnnlowp_elementwise_add_broadcast_axis(self, gc, dc):\n for bdim, axis in [\n ((3, 4), 1), # broadcasting intermediate dimensions\n ((2,), 0), # broadcasting the first dimension\n ((1, 4, 1), 1),\n ]:\n # broadcasting with single elem dimensions at both ends\n\n min_ = -100\n max_ = min_ + 255\n A = np.round(np.random.rand(2, 3, 4, 5) * (max_ - min_) + min_)\n A = A.astype(np.float32)\n B = np.round(np.random.rand(*bdim) * 255 / 2 - 64).astype(np.float32)\n\n A.flat[0] = min_\n A.flat[1] = max_\n B.flat[0] = -64\n B.flat[1] = 127.0 / 2\n\n Output = collections.namedtuple(\"Output\", [\"Y\", \"op_type\", \"engine\"])\n outputs = []\n\n op_engine_list = [(\"Add\", \"\"), (\"Add\", \"DNNLOWP\"), (\"Int8Add\", \"DNNLOWP\")]\n\n for op_type, engine in op_engine_list:\n net = core.Net(\"test_net\")\n\n add = core.CreateOperator(\n op_type,\n [\"A\", \"B\"],\n [\"Y\"],\n engine=engine,\n device_option=gc,\n broadcast=1,\n axis=axis,\n dequantize_output=1,\n )\n net.Proto().op.extend([add])\n\n self.ws.create_blob(\"A\").feed(A, device_option=gc)\n self.ws.create_blob(\"B\").feed(B, device_option=gc)\n self.ws.run(net)\n outputs.append(\n Output(Y=self.ws.blobs[\"Y\"].fetch(), op_type=op_type, engine=engine)\n )\n\n check_quantized_results_close(outputs)\n" ]
[ [ "numpy.random.seed", "torch.autograd.gradcheck.gradgradcheck", "torch.testing._internal.common_cuda.initialize_cuda_context_rng", "numpy.array", "torch.autograd.gradcheck", "torch.testing._compare_tensors_internal" ], [ "torch.testing._internal.common_utils.run_tests" ], [ "numpy.testing.assert_equal", "numpy.allclose", "numpy.random.seed", "numpy.sqrt", "numpy.reshape", "numpy.linalg.norm", "numpy.round", "numpy.concatenate", "numpy.random.permutation", "numpy.mean", "numpy.random.rand", "numpy.var", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.isclose" ], [ "torch.jit.save", "torch.utils.show_pickle.main", "torch.tensor" ], [ "numpy.log", "numpy.minimum", "numpy.maximum", "numpy.abs", "numpy.empty", "numpy.random.randn", "numpy.random.uniform", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.where", "numpy.vstack", "numpy.random.randint" ], [ "torch.randn" ], [ "numpy.dot", "numpy.maximum", "numpy.sqrt", "numpy.random.seed", "numpy.arange", "numpy.linalg.norm", "numpy.testing.assert_almost_equal", "numpy.repeat", "numpy.array", "numpy.random.randint" ], [ "numpy.random.rand" ], [ "numpy.square", "numpy.logical_not", "numpy.log", "numpy.absolute", "numpy.maximum", "numpy.sqrt", "numpy.random.seed", "numpy.power", "numpy.cbrt", "numpy.sign", "numpy.random.randn", "numpy.random.rand", "numpy.reciprocal", "numpy.exp", "numpy.sum", "numpy.random.randint" ], [ "torch.distributions.utils.probs_to_logits", "torch._C._get_tracing_state", "torch.Size", "torch.distributions.utils.logits_to_probs", "torch.nn.functional.binary_cross_entropy_with_logits", "torch.no_grad", "torch.rand", "torch.finfo", "torch.distributions.utils.broadcast_all" ], [ "torch.testing._internal.common_utils.run_tests" ], [ "numpy.amax", "numpy.expand_dims", "numpy.resize", "numpy.asarray", "numpy.mean", "numpy.random.rand", "numpy.count_nonzero", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.random.randint" ], [ "torch._C._get_deterministic", "torch.multiprocessing._atfork.register_after_fork", "torch._C._set_default_dtype", "torch._C._set_default_tensor_type", "torch._C._set_deterministic" ], [ "torch.sigmoid", "torch.empty", "torch.Tensor", "torch.nn.init.constant_", "torch.nn.init.xavier_normal_", "torch.tanh", "torch.nn.init.xavier_uniform_" ], [ "torch.rand" ], [ "torch.randn", "torch.nn.functional.linear", "torch.autograd.profiler.profile" ], [ "torch.sum", "torch.rand" ], [ "numpy.testing.assert_array_equal", "numpy.array" ], [ "numpy.testing.assert_equal", "numpy.dtype", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array", "numpy.random.randint" ], [ "numpy.random.rand" ] ]
[ { "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": [] }, { "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": [] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Geolem/nltk
[ "39b84d97bc857fce4fef185c69b94546b8474551" ]
[ "nltk/parse/dependencygraph.py" ]
[ "# Natural Language Toolkit: Dependency Grammars\n#\n# Copyright (C) 2001-2021 NLTK Project\n# Author: Jason Narad <[email protected]>\n# Steven Bird <[email protected]> (modifications)\n#\n# URL: <http://nltk.org/>\n# For license information, see LICENSE.TXT\n#\n\n\"\"\"\nTools for reading and writing dependency trees.\nThe input is assumed to be in Malt-TAB format\n(http://stp.lingfil.uu.se/~nivre/research/MaltXML.html).\n\"\"\"\n\nfrom collections import defaultdict\nfrom itertools import chain\nfrom pprint import pformat\nimport subprocess\nimport warnings\n\nfrom nltk.tree import Tree\n\n#################################################################\n# DependencyGraph Class\n#################################################################\n\n\nclass DependencyGraph:\n \"\"\"\n A container for the nodes and labelled edges of a dependency structure.\n \"\"\"\n\n def __init__(\n self,\n tree_str=None,\n cell_extractor=None,\n zero_based=False,\n cell_separator=None,\n top_relation_label=\"ROOT\",\n ):\n \"\"\"Dependency graph.\n\n We place a dummy `TOP` node with the index 0, since the root node is\n often assigned 0 as its head. This also means that the indexing of the\n nodes corresponds directly to the Malt-TAB format, which starts at 1.\n\n If zero-based is True, then Malt-TAB-like input with node numbers\n starting at 0 and the root node assigned -1 (as produced by, e.g.,\n zpar).\n\n :param str cell_separator: the cell separator. If not provided, cells\n are split by whitespace.\n\n :param str top_relation_label: the label by which the top relation is\n identified, for examlple, `ROOT`, `null` or `TOP`.\n\n \"\"\"\n self.nodes = defaultdict(\n lambda: {\n \"address\": None,\n \"word\": None,\n \"lemma\": None,\n \"ctag\": None,\n \"tag\": None,\n \"feats\": None,\n \"head\": None,\n \"deps\": defaultdict(list),\n \"rel\": None,\n }\n )\n\n self.nodes[0].update({\"ctag\": \"TOP\", \"tag\": \"TOP\", \"address\": 0})\n\n self.root = None\n\n if tree_str:\n self._parse(\n tree_str,\n cell_extractor=cell_extractor,\n zero_based=zero_based,\n cell_separator=cell_separator,\n top_relation_label=top_relation_label,\n )\n\n def remove_by_address(self, address):\n \"\"\"\n Removes the node with the given address. References\n to this node in others will still exist.\n \"\"\"\n del self.nodes[address]\n\n def redirect_arcs(self, originals, redirect):\n \"\"\"\n Redirects arcs to any of the nodes in the originals list\n to the redirect node address.\n \"\"\"\n for node in self.nodes.values():\n new_deps = []\n for dep in node[\"deps\"]:\n if dep in originals:\n new_deps.append(redirect)\n else:\n new_deps.append(dep)\n node[\"deps\"] = new_deps\n\n def add_arc(self, head_address, mod_address):\n \"\"\"\n Adds an arc from the node specified by head_address to the\n node specified by the mod address.\n \"\"\"\n relation = self.nodes[mod_address][\"rel\"]\n self.nodes[head_address][\"deps\"].setdefault(relation, [])\n self.nodes[head_address][\"deps\"][relation].append(mod_address)\n # self.nodes[head_address]['deps'].append(mod_address)\n\n def connect_graph(self):\n \"\"\"\n Fully connects all non-root nodes. All nodes are set to be dependents\n of the root node.\n \"\"\"\n for node1 in self.nodes.values():\n for node2 in self.nodes.values():\n if node1[\"address\"] != node2[\"address\"] and node2[\"rel\"] != \"TOP\":\n relation = node2[\"rel\"]\n node1[\"deps\"].setdefault(relation, [])\n node1[\"deps\"][relation].append(node2[\"address\"])\n # node1['deps'].append(node2['address'])\n\n def get_by_address(self, node_address):\n \"\"\"Return the node with the given address.\"\"\"\n return self.nodes[node_address]\n\n def contains_address(self, node_address):\n \"\"\"\n Returns true if the graph contains a node with the given node\n address, false otherwise.\n \"\"\"\n return node_address in self.nodes\n\n def to_dot(self):\n \"\"\"Return a dot representation suitable for using with Graphviz.\n\n >>> dg = DependencyGraph(\n ... 'John N 2\\\\n'\n ... 'loves V 0\\\\n'\n ... 'Mary N 2'\n ... )\n >>> print(dg.to_dot())\n digraph G{\n edge [dir=forward]\n node [shape=plaintext]\n <BLANKLINE>\n 0 [label=\"0 (None)\"]\n 0 -> 2 [label=\"ROOT\"]\n 1 [label=\"1 (John)\"]\n 2 [label=\"2 (loves)\"]\n 2 -> 1 [label=\"\"]\n 2 -> 3 [label=\"\"]\n 3 [label=\"3 (Mary)\"]\n }\n\n \"\"\"\n # Start the digraph specification\n s = \"digraph G{\\n\"\n s += \"edge [dir=forward]\\n\"\n s += \"node [shape=plaintext]\\n\"\n\n # Draw the remaining nodes\n for node in sorted(self.nodes.values(), key=lambda v: v[\"address\"]):\n s += '\\n%s [label=\"%s (%s)\"]' % (\n node[\"address\"],\n node[\"address\"],\n node[\"word\"],\n )\n for rel, deps in node[\"deps\"].items():\n for dep in deps:\n if rel is not None:\n s += '\\n%s -> %s [label=\"%s\"]' % (node[\"address\"], dep, rel)\n else:\n s += \"\\n%s -> %s \" % (node[\"address\"], dep)\n s += \"\\n}\"\n\n return s\n\n def _repr_svg_(self):\n \"\"\"Show SVG representation of the transducer (IPython magic).\n\n >>> dg = DependencyGraph(\n ... 'John N 2\\\\n'\n ... 'loves V 0\\\\n'\n ... 'Mary N 2'\n ... )\n >>> dg._repr_svg_().split('\\\\n')[0]\n '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>'\n\n \"\"\"\n dot_string = self.to_dot()\n\n try:\n process = subprocess.Popen(\n [\"dot\", \"-Tsvg\"],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n )\n except OSError as e:\n raise Exception(\"Cannot find the dot binary from Graphviz package\") from e\n out, err = process.communicate(dot_string)\n if err:\n raise Exception(\n \"Cannot create svg representation by running dot from string: {}\"\n \"\".format(dot_string)\n )\n return out\n\n def __str__(self):\n return pformat(self.nodes)\n\n def __repr__(self):\n return \"<DependencyGraph with {0} nodes>\".format(len(self.nodes))\n\n @staticmethod\n def load(\n filename, zero_based=False, cell_separator=None, top_relation_label=\"ROOT\"\n ):\n \"\"\"\n :param filename: a name of a file in Malt-TAB format\n :param zero_based: nodes in the input file are numbered starting from 0\n rather than 1 (as produced by, e.g., zpar)\n :param str cell_separator: the cell separator. If not provided, cells\n are split by whitespace.\n :param str top_relation_label: the label by which the top relation is\n identified, for examlple, `ROOT`, `null` or `TOP`.\n\n :return: a list of DependencyGraphs\n\n \"\"\"\n with open(filename) as infile:\n return [\n DependencyGraph(\n tree_str,\n zero_based=zero_based,\n cell_separator=cell_separator,\n top_relation_label=top_relation_label,\n )\n for tree_str in infile.read().split(\"\\n\\n\")\n ]\n\n def left_children(self, node_index):\n \"\"\"\n Returns the number of left children under the node specified\n by the given address.\n \"\"\"\n children = chain.from_iterable(self.nodes[node_index][\"deps\"].values())\n index = self.nodes[node_index][\"address\"]\n return sum(1 for c in children if c < index)\n\n def right_children(self, node_index):\n \"\"\"\n Returns the number of right children under the node specified\n by the given address.\n \"\"\"\n children = chain.from_iterable(self.nodes[node_index][\"deps\"].values())\n index = self.nodes[node_index][\"address\"]\n return sum(1 for c in children if c > index)\n\n def add_node(self, node):\n if not self.contains_address(node[\"address\"]):\n self.nodes[node[\"address\"]].update(node)\n\n def _parse(\n self,\n input_,\n cell_extractor=None,\n zero_based=False,\n cell_separator=None,\n top_relation_label=\"ROOT\",\n ):\n \"\"\"Parse a sentence.\n\n :param extractor: a function that given a tuple of cells returns a\n 7-tuple, where the values are ``word, lemma, ctag, tag, feats, head,\n rel``.\n\n :param str cell_separator: the cell separator. If not provided, cells\n are split by whitespace.\n\n :param str top_relation_label: the label by which the top relation is\n identified, for examlple, `ROOT`, `null` or `TOP`.\n\n \"\"\"\n\n def extract_3_cells(cells, index):\n word, tag, head = cells\n return index, word, word, tag, tag, \"\", head, \"\"\n\n def extract_4_cells(cells, index):\n word, tag, head, rel = cells\n return index, word, word, tag, tag, \"\", head, rel\n\n def extract_7_cells(cells, index):\n line_index, word, lemma, tag, _, head, rel = cells\n try:\n index = int(line_index)\n except ValueError:\n # index can't be parsed as an integer, use default\n pass\n return index, word, lemma, tag, tag, \"\", head, rel\n\n def extract_10_cells(cells, index):\n line_index, word, lemma, ctag, tag, feats, head, rel, _, _ = cells\n try:\n index = int(line_index)\n except ValueError:\n # index can't be parsed as an integer, use default\n pass\n return index, word, lemma, ctag, tag, feats, head, rel\n\n extractors = {\n 3: extract_3_cells,\n 4: extract_4_cells,\n 7: extract_7_cells,\n 10: extract_10_cells,\n }\n\n if isinstance(input_, str):\n input_ = (line for line in input_.split(\"\\n\"))\n\n lines = (l.rstrip() for l in input_)\n lines = (l for l in lines if l)\n\n cell_number = None\n for index, line in enumerate(lines, start=1):\n cells = line.split(cell_separator)\n if cell_number is None:\n cell_number = len(cells)\n else:\n assert cell_number == len(cells)\n\n if cell_extractor is None:\n try:\n cell_extractor = extractors[cell_number]\n except KeyError as e:\n raise ValueError(\n \"Number of tab-delimited fields ({0}) not supported by \"\n \"CoNLL(10) or Malt-Tab(4) format\".format(cell_number)\n ) from e\n\n try:\n index, word, lemma, ctag, tag, feats, head, rel = cell_extractor(\n cells, index\n )\n except (TypeError, ValueError):\n # cell_extractor doesn't take 2 arguments or doesn't return 8\n # values; assume the cell_extractor is an older external\n # extractor and doesn't accept or return an index.\n word, lemma, ctag, tag, feats, head, rel = cell_extractor(cells)\n\n if head == \"_\":\n continue\n\n head = int(head)\n if zero_based:\n head += 1\n\n self.nodes[index].update(\n {\n \"address\": index,\n \"word\": word,\n \"lemma\": lemma,\n \"ctag\": ctag,\n \"tag\": tag,\n \"feats\": feats,\n \"head\": head,\n \"rel\": rel,\n }\n )\n\n # Make sure that the fake root node has labeled dependencies.\n if (cell_number == 3) and (head == 0):\n rel = top_relation_label\n self.nodes[head][\"deps\"][rel].append(index)\n\n if self.nodes[0][\"deps\"][top_relation_label]:\n root_address = self.nodes[0][\"deps\"][top_relation_label][0]\n self.root = self.nodes[root_address]\n self.top_relation_label = top_relation_label\n else:\n warnings.warn(\n \"The graph doesn't contain a node \" \"that depends on the root element.\"\n )\n\n def _word(self, node, filter=True):\n w = node[\"word\"]\n if filter:\n if w != \",\":\n return w\n return w\n\n def _tree(self, i):\n \"\"\" Turn dependency graphs into NLTK trees.\n\n :param int i: index of a node\n :return: either a word (if the indexed node is a leaf) or a ``Tree``.\n \"\"\"\n node = self.get_by_address(i)\n word = node[\"word\"]\n deps = sorted(chain.from_iterable(node[\"deps\"].values()))\n\n if deps:\n return Tree(word, [self._tree(dep) for dep in deps])\n else:\n return word\n\n def tree(self):\n \"\"\"\n Starting with the ``root`` node, build a dependency tree using the NLTK\n ``Tree`` constructor. Dependency labels are omitted.\n \"\"\"\n node = self.root\n\n word = node[\"word\"]\n deps = sorted(chain.from_iterable(node[\"deps\"].values()))\n return Tree(word, [self._tree(dep) for dep in deps])\n\n def triples(self, node=None):\n \"\"\"\n Extract dependency triples of the form:\n ((head word, head tag), rel, (dep word, dep tag))\n \"\"\"\n\n if not node:\n node = self.root\n\n head = (node[\"word\"], node[\"ctag\"])\n for i in sorted(chain.from_iterable(node[\"deps\"].values())):\n dep = self.get_by_address(i)\n yield (head, dep[\"rel\"], (dep[\"word\"], dep[\"ctag\"]))\n for triple in self.triples(node=dep):\n yield triple\n\n def _hd(self, i):\n try:\n return self.nodes[i][\"head\"]\n except IndexError:\n return None\n\n def _rel(self, i):\n try:\n return self.nodes[i][\"rel\"]\n except IndexError:\n return None\n\n # what's the return type? Boolean or list?\n def contains_cycle(self):\n \"\"\"Check whether there are cycles.\n\n >>> dg = DependencyGraph(treebank_data)\n >>> dg.contains_cycle()\n False\n\n >>> cyclic_dg = DependencyGraph()\n >>> top = {'word': None, 'deps': [1], 'rel': 'TOP', 'address': 0}\n >>> child1 = {'word': None, 'deps': [2], 'rel': 'NTOP', 'address': 1}\n >>> child2 = {'word': None, 'deps': [4], 'rel': 'NTOP', 'address': 2}\n >>> child3 = {'word': None, 'deps': [1], 'rel': 'NTOP', 'address': 3}\n >>> child4 = {'word': None, 'deps': [3], 'rel': 'NTOP', 'address': 4}\n >>> cyclic_dg.nodes = {\n ... 0: top,\n ... 1: child1,\n ... 2: child2,\n ... 3: child3,\n ... 4: child4,\n ... }\n >>> cyclic_dg.root = top\n\n >>> cyclic_dg.contains_cycle()\n [3, 1, 2, 4]\n\n \"\"\"\n distances = {}\n\n for node in self.nodes.values():\n for dep in node[\"deps\"]:\n key = tuple([node[\"address\"], dep])\n distances[key] = 1\n\n for _ in self.nodes:\n new_entries = {}\n\n for pair1 in distances:\n for pair2 in distances:\n if pair1[1] == pair2[0]:\n key = tuple([pair1[0], pair2[1]])\n new_entries[key] = distances[pair1] + distances[pair2]\n\n for pair in new_entries:\n distances[pair] = new_entries[pair]\n if pair[0] == pair[1]:\n path = self.get_cycle_path(self.get_by_address(pair[0]), pair[0])\n return path\n\n return False # return []?\n\n def get_cycle_path(self, curr_node, goal_node_index):\n for dep in curr_node[\"deps\"]:\n if dep == goal_node_index:\n return [curr_node[\"address\"]]\n for dep in curr_node[\"deps\"]:\n path = self.get_cycle_path(self.get_by_address(dep), goal_node_index)\n if len(path) > 0:\n path.insert(0, curr_node[\"address\"])\n return path\n return []\n\n def to_conll(self, style):\n \"\"\"\n The dependency graph in CoNLL format.\n\n :param style: the style to use for the format (3, 4, 10 columns)\n :type style: int\n :rtype: str\n \"\"\"\n\n if style == 3:\n template = \"{word}\\t{tag}\\t{head}\\n\"\n elif style == 4:\n template = \"{word}\\t{tag}\\t{head}\\t{rel}\\n\"\n elif style == 10:\n template = (\n \"{i}\\t{word}\\t{lemma}\\t{ctag}\\t{tag}\\t{feats}\\t{head}\\t{rel}\\t_\\t_\\n\"\n )\n else:\n raise ValueError(\n \"Number of tab-delimited fields ({0}) not supported by \"\n \"CoNLL(10) or Malt-Tab(4) format\".format(style)\n )\n\n return \"\".join(\n template.format(i=i, **node)\n for i, node in sorted(self.nodes.items())\n if node[\"tag\"] != \"TOP\"\n )\n\n def nx_graph(self):\n \"\"\"Convert the data in a ``nodelist`` into a networkx labeled directed graph.\"\"\"\n import networkx\n\n nx_nodelist = list(range(1, len(self.nodes)))\n nx_edgelist = [\n (n, self._hd(n), self._rel(n)) for n in nx_nodelist if self._hd(n)\n ]\n self.nx_labels = {}\n for n in nx_nodelist:\n self.nx_labels[n] = self.nodes[n][\"word\"]\n\n g = networkx.MultiDiGraph()\n g.add_nodes_from(nx_nodelist)\n g.add_edges_from(nx_edgelist)\n\n return g\n\n\nclass DependencyGraphError(Exception):\n \"\"\"Dependency graph exception.\"\"\"\n\n\ndef demo():\n malt_demo()\n conll_demo()\n conll_file_demo()\n cycle_finding_demo()\n\n\ndef malt_demo(nx=False):\n \"\"\"\n A demonstration of the result of reading a dependency\n version of the first sentence of the Penn Treebank.\n \"\"\"\n dg = DependencyGraph(\n \"\"\"Pierre NNP 2 NMOD\nVinken NNP 8 SUB\n, , 2 P\n61 CD 5 NMOD\nyears NNS 6 AMOD\nold JJ 2 NMOD\n, , 2 P\nwill MD 0 ROOT\njoin VB 8 VC\nthe DT 11 NMOD\nboard NN 9 OBJ\nas IN 9 VMOD\na DT 15 NMOD\nnonexecutive JJ 15 NMOD\ndirector NN 12 PMOD\nNov. NNP 9 VMOD\n29 CD 16 NMOD\n. . 9 VMOD\n\"\"\"\n )\n tree = dg.tree()\n tree.pprint()\n if nx:\n # currently doesn't work\n import networkx\n from matplotlib import pylab\n\n g = dg.nx_graph()\n g.info()\n pos = networkx.spring_layout(g, dim=1)\n networkx.draw_networkx_nodes(g, pos, node_size=50)\n # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)\n networkx.draw_networkx_labels(g, pos, dg.nx_labels)\n pylab.xticks([])\n pylab.yticks([])\n pylab.savefig(\"tree.png\")\n pylab.show()\n\n\ndef conll_demo():\n \"\"\"\n A demonstration of how to read a string representation of\n a CoNLL format dependency tree.\n \"\"\"\n dg = DependencyGraph(conll_data1)\n tree = dg.tree()\n tree.pprint()\n print(dg)\n print(dg.to_conll(4))\n\n\ndef conll_file_demo():\n print(\"Mass conll_read demo...\")\n graphs = [DependencyGraph(entry) for entry in conll_data2.split(\"\\n\\n\") if entry]\n for graph in graphs:\n tree = graph.tree()\n print(\"\\n\")\n tree.pprint()\n\n\ndef cycle_finding_demo():\n dg = DependencyGraph(treebank_data)\n print(dg.contains_cycle())\n cyclic_dg = DependencyGraph()\n cyclic_dg.add_node({\"word\": None, \"deps\": [1], \"rel\": \"TOP\", \"address\": 0})\n cyclic_dg.add_node({\"word\": None, \"deps\": [2], \"rel\": \"NTOP\", \"address\": 1})\n cyclic_dg.add_node({\"word\": None, \"deps\": [4], \"rel\": \"NTOP\", \"address\": 2})\n cyclic_dg.add_node({\"word\": None, \"deps\": [1], \"rel\": \"NTOP\", \"address\": 3})\n cyclic_dg.add_node({\"word\": None, \"deps\": [3], \"rel\": \"NTOP\", \"address\": 4})\n print(cyclic_dg.contains_cycle())\n\n\ntreebank_data = \"\"\"Pierre NNP 2 NMOD\nVinken NNP 8 SUB\n, , 2 P\n61 CD 5 NMOD\nyears NNS 6 AMOD\nold JJ 2 NMOD\n, , 2 P\nwill MD 0 ROOT\njoin VB 8 VC\nthe DT 11 NMOD\nboard NN 9 OBJ\nas IN 9 VMOD\na DT 15 NMOD\nnonexecutive JJ 15 NMOD\ndirector NN 12 PMOD\nNov. NNP 9 VMOD\n29 CD 16 NMOD\n. . 9 VMOD\n\"\"\"\n\nconll_data1 = \"\"\"\n1 Ze ze Pron Pron per|3|evofmv|nom 2 su _ _\n2 had heb V V trans|ovt|1of2of3|ev 0 ROOT _ _\n3 met met Prep Prep voor 8 mod _ _\n4 haar haar Pron Pron bez|3|ev|neut|attr 5 det _ _\n5 moeder moeder N N soort|ev|neut 3 obj1 _ _\n6 kunnen kan V V hulp|ott|1of2of3|mv 2 vc _ _\n7 gaan ga V V hulp|inf 6 vc _ _\n8 winkelen winkel V V intrans|inf 11 cnj _ _\n9 , , Punc Punc komma 8 punct _ _\n10 zwemmen zwem V V intrans|inf 11 cnj _ _\n11 of of Conj Conj neven 7 vc _ _\n12 terrassen terras N N soort|mv|neut 11 cnj _ _\n13 . . Punc Punc punt 12 punct _ _\n\"\"\"\n\nconll_data2 = \"\"\"1 Cathy Cathy N N eigen|ev|neut 2 su _ _\n2 zag zie V V trans|ovt|1of2of3|ev 0 ROOT _ _\n3 hen hen Pron Pron per|3|mv|datofacc 2 obj1 _ _\n4 wild wild Adj Adj attr|stell|onverv 5 mod _ _\n5 zwaaien zwaai N N soort|mv|neut 2 vc _ _\n6 . . Punc Punc punt 5 punct _ _\n\n1 Ze ze Pron Pron per|3|evofmv|nom 2 su _ _\n2 had heb V V trans|ovt|1of2of3|ev 0 ROOT _ _\n3 met met Prep Prep voor 8 mod _ _\n4 haar haar Pron Pron bez|3|ev|neut|attr 5 det _ _\n5 moeder moeder N N soort|ev|neut 3 obj1 _ _\n6 kunnen kan V V hulp|ott|1of2of3|mv 2 vc _ _\n7 gaan ga V V hulp|inf 6 vc _ _\n8 winkelen winkel V V intrans|inf 11 cnj _ _\n9 , , Punc Punc komma 8 punct _ _\n10 zwemmen zwem V V intrans|inf 11 cnj _ _\n11 of of Conj Conj neven 7 vc _ _\n12 terrassen terras N N soort|mv|neut 11 cnj _ _\n13 . . Punc Punc punt 12 punct _ _\n\n1 Dat dat Pron Pron aanw|neut|attr 2 det _ _\n2 werkwoord werkwoord N N soort|ev|neut 6 obj1 _ _\n3 had heb V V hulp|ovt|1of2of3|ev 0 ROOT _ _\n4 ze ze Pron Pron per|3|evofmv|nom 6 su _ _\n5 zelf zelf Pron Pron aanw|neut|attr|wzelf 3 predm _ _\n6 uitgevonden vind V V trans|verldw|onverv 3 vc _ _\n7 . . Punc Punc punt 6 punct _ _\n\n1 Het het Pron Pron onbep|neut|zelfst 2 su _ _\n2 hoorde hoor V V trans|ovt|1of2of3|ev 0 ROOT _ _\n3 bij bij Prep Prep voor 2 ld _ _\n4 de de Art Art bep|zijdofmv|neut 6 det _ _\n5 warme warm Adj Adj attr|stell|vervneut 6 mod _ _\n6 zomerdag zomerdag N N soort|ev|neut 3 obj1 _ _\n7 die die Pron Pron betr|neut|zelfst 6 mod _ _\n8 ze ze Pron Pron per|3|evofmv|nom 12 su _ _\n9 ginds ginds Adv Adv gew|aanw 12 mod _ _\n10 achter achter Adv Adv gew|geenfunc|stell|onverv 12 svp _ _\n11 had heb V V hulp|ovt|1of2of3|ev 7 body _ _\n12 gelaten laat V V trans|verldw|onverv 11 vc _ _\n13 . . Punc Punc punt 12 punct _ _\n\n1 Ze ze Pron Pron per|3|evofmv|nom 2 su _ _\n2 hadden heb V V trans|ovt|1of2of3|mv 0 ROOT _ _\n3 languit languit Adv Adv gew|geenfunc|stell|onverv 11 mod _ _\n4 naast naast Prep Prep voor 11 mod _ _\n5 elkaar elkaar Pron Pron rec|neut 4 obj1 _ _\n6 op op Prep Prep voor 11 ld _ _\n7 de de Art Art bep|zijdofmv|neut 8 det _ _\n8 strandstoelen strandstoel N N soort|mv|neut 6 obj1 _ _\n9 kunnen kan V V hulp|inf 2 vc _ _\n10 gaan ga V V hulp|inf 9 vc _ _\n11 liggen lig V V intrans|inf 10 vc _ _\n12 . . Punc Punc punt 11 punct _ _\n\n1 Zij zij Pron Pron per|3|evofmv|nom 2 su _ _\n2 zou zal V V hulp|ovt|1of2of3|ev 7 cnj _ _\n3 mams mams N N soort|ev|neut 4 det _ _\n4 rug rug N N soort|ev|neut 5 obj1 _ _\n5 ingewreven wrijf V V trans|verldw|onverv 6 vc _ _\n6 hebben heb V V hulp|inf 2 vc _ _\n7 en en Conj Conj neven 0 ROOT _ _\n8 mam mam V V trans|ovt|1of2of3|ev 7 cnj _ _\n9 de de Art Art bep|zijdofmv|neut 10 det _ _\n10 hare hare Pron Pron bez|3|ev|neut|attr 8 obj1 _ _\n11 . . Punc Punc punt 10 punct _ _\n\n1 Of of Conj Conj onder|metfin 0 ROOT _ _\n2 ze ze Pron Pron per|3|evofmv|nom 3 su _ _\n3 had heb V V hulp|ovt|1of2of3|ev 0 ROOT _ _\n4 gewoon gewoon Adj Adj adv|stell|onverv 10 mod _ _\n5 met met Prep Prep voor 10 mod _ _\n6 haar haar Pron Pron bez|3|ev|neut|attr 7 det _ _\n7 vriendinnen vriendin N N soort|mv|neut 5 obj1 _ _\n8 rond rond Adv Adv deelv 10 svp _ _\n9 kunnen kan V V hulp|inf 3 vc _ _\n10 slenteren slenter V V intrans|inf 9 vc _ _\n11 in in Prep Prep voor 10 mod _ _\n12 de de Art Art bep|zijdofmv|neut 13 det _ _\n13 buurt buurt N N soort|ev|neut 11 obj1 _ _\n14 van van Prep Prep voor 13 mod _ _\n15 Trafalgar_Square Trafalgar_Square MWU N_N eigen|ev|neut_eigen|ev|neut 14 obj1 _ _\n16 . . Punc Punc punt 15 punct _ _\n\"\"\"\n\nif __name__ == \"__main__\":\n demo()\n" ]
[ [ "matplotlib.pylab.savefig", "matplotlib.pylab.xticks", "matplotlib.pylab.yticks", "matplotlib.pylab.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
leguiart/MSc_Thesis
[ "22ffc73c75d814856850f26c4586d90896b74cf3" ]
[ "evosoro_pymoo/Algorithms/RankAndNoveltySurvival.py" ]
[ "import numpy as np\n\nfrom pymoo.core.survival import Survival\nfrom pymoo.util.nds.non_dominated_sorting import NonDominatedSorting\nfrom pymoo.util.randomized_argsort import randomized_argsort\n\n# ---------------------------------------------------------------------------------------------------------\n# Survival Selection\n# ---------------------------------------------------------------------------------------------------------\n\n\nclass RankAndNoveltySurvival(Survival):\n\n def __init__(self, nds=None) -> None:\n super().__init__(filter_infeasible=True)\n self.nds = nds if nds is not None else NonDominatedSorting()\n\n def _do(self, problem, pop, *args, n_survive=None, **kwargs):\n\n # get the objective space values and objects\n F = pop.get(\"F\").astype(float, copy=False)\n\n # the final indices of surviving individuals\n survivors = []\n\n # do the non-dominated sorting until splitting front\n fronts = self.nds.do(F, n_stop_if_ranked=n_survive)\n\n for k, front in enumerate(fronts):\n\n # calculate the novelty of the front\n novelty_of_front = get_unaligned_novelty(pop[front])\n\n # save rank and crowding in the individual class\n for j, i in enumerate(front):\n pop[i].set(\"rank\", k)\n pop[i].set(\"crowding\", novelty_of_front[j])\n\n # current front sorted by crowding distance if splitting\n if len(survivors) + len(front) > n_survive:\n I = randomized_argsort(novelty_of_front, order='descending', method='numpy')\n I = I[:(n_survive - len(survivors))]\n\n # otherwise take the whole front unsorted\n else:\n I = np.arange(len(front))\n\n # extend the survivors by all or selected individuals\n survivors.extend(front[I])\n\n return pop[survivors]\n\n\ndef get_unaligned_novelty(pop):\n return np.array([x_i.X.unaligned_novelty_metric for x_i in pop])\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
robertklee/SENG474-DataMining
[ "85b6ff300e18320fe8b40c89d5f22fde51ba588e", "85b6ff300e18320fe8b40c89d5f22fde51ba588e" ]
[ "notebooks/imgaug-playground.py", "coco_df.py" ]
[ "import imgaug as ia\nfrom imgaug import augmenters as iaa\nimport numpy as np\nfrom scipy import misc\nimport imageio\nimport cv2\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nfrom imgaug.augmentables import Keypoint, KeypointsOnImage\n\n\nia.seed(1)\n\nimage = ia.quokka(size=(256, 256))\nkps = KeypointsOnImage([\n Keypoint(x=65, y=100),\n Keypoint(x=75, y=200),\n Keypoint(x=100, y=100),\n Keypoint(x=200, y=80)\n], shape=image.shape)\n\nseq = iaa.Sequential([\n iaa.Multiply((1.2, 1.5)), # change brightness, doesn't affect keypoints\n iaa.Affine(\n rotate=10,\n scale=(0.5, 0.7)\n ) # rotate by exactly 10deg and scale to 50-70%, affects keypoints\n])\n\n# Augment keypoints and images.\nimage_aug, kps_aug = seq(image=image, keypoints=kps)\n\n# print coordinates before/after augmentation (see below)\n# use after.x_int and after.y_int to get rounded integer coordinates\nfor i in range(len(kps.keypoints)):\n before = kps.keypoints[i]\n after = kps_aug.keypoints[i]\n print(\"Keypoint %d: (%.8f, %.8f) -> (%.8f, %.8f)\" % (\n i, before.x, before.y, after.x, after.y)\n )\n\n# image with keypoints before/after augmentation (shown below)\nimage_before = kps.draw_on_image(image, size=7)\nimage_after = kps_aug.draw_on_image(image_aug, size=7)\n\ndef main():\n imgs = np.zeros((1, 100, 100, 3), dtype=np.uint8) + 255\n bbs = ia.BoundingBoxesOnImage([\n ia.BoundingBox(x1=0, x2=50, y1=0, y2=50)\n ], shape=imgs.shape[1:])\n\n aug = iaa.Sequential([\n iaa.Crop(px=10),\n iaa.Pad(px=10, pad_cval=128),\n iaa.Affine(scale=0.5, cval=0)\n ])\n\n aug_det = aug.to_deterministic()\n imgs_aug = aug_det.augment_images(imgs)\n bbs_aug = aug_det.augment_bounding_boxes([bbs])\n\n print(\"bbs:\")\n for bbs_aug_i in bbs_aug[0].bounding_boxes:\n print(bbs_aug_i)\n\n cv2.imshow('orig',imgs)\n cv2.imshow('aug',bbs_aug[0].draw_on_image(imgs_aug[0]))\n cv2.waitKey()\n\nif __name__ == \"__main__\":\n main()", "from pycocotools.coco import COCO\nimport numpy as np\nimport pandas as pd\nimport skimage.io as io\n\ndef get_meta(coco):\n ids = list(coco.imgs.keys())\n for i, img_id in enumerate(ids):\n img_meta = coco.imgs[img_id]\n ann_ids = coco.getAnnIds(imgIds=img_id)\n anns = coco.loadAnns(ann_ids)\n img_file_name = img_meta['file_name']\n w = img_meta['width']\n h = img_meta['height']\n url = img_meta['coco_url']\n\n yield [img_id, img_file_name, w, h, url, anns]\n\ndef convert_to_df(coco, data_set):\n images_data = []\n persons_data = []\n\n for img_id, img_fname, w, h, url, meta in get_meta(coco):\n images_data.append({\n 'image_id': int(img_id),\n 'src_set_image_id': int(img_id), # repeat id to reference after join\n 'coco_url': url,\n 'path': data_set + '/' + img_fname,\n 'width': int(w),\n 'height': int(h)\n })\n for m in meta:\n persons_data.append({\n 'ann_id': m['id'],\n 'image_id': m['image_id'],\n 'is_crowd': m['iscrowd'],\n 'bbox': m['bbox'],\n 'bbox_area' : m['bbox'][2] * m['bbox'][3],\n 'area': m['area'],\n 'num_keypoints': m['num_keypoints'],\n 'keypoints': m['keypoints'],\n 'segmentation': m['segmentation']\n })\n\n images_df = pd.DataFrame(images_data)\n images_df.set_index('image_id', inplace=True)\n\n persons_df = pd.DataFrame(persons_data)\n persons_df.set_index('image_id', inplace=True)\n\n return images_df, persons_df\n\ndef get_df(path_to_train_anns, path_to_val_anns):\n train_coco = COCO(path_to_train_anns) # load annotations for training set\n val_coco = COCO(path_to_val_anns) # load annotations for validation set\n images_df, persons_df = convert_to_df(train_coco, 'train2017')\n train_coco_df = pd.merge(images_df, persons_df, right_index=True, left_index=True)\n train_coco_df['source'] = 0\n train_coco_df.head()\n\n images_df, persons_df = convert_to_df(val_coco, 'val2017')\n val_coco_df = pd.merge(images_df, persons_df, right_index=True, left_index=True)\n val_coco_df['source'] = 1\n val_coco_df.head()\n\n return pd.concat([train_coco_df, val_coco_df], ignore_index=True)\n # ^ Dataframe containing all val and test keypoint annotations" ]
[ [ "numpy.zeros" ], [ "pandas.merge", "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "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": [] } ]
anmartinezs/pyseg_system
[ "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3", "5bb07c7901062452a34b73f376057cabc15a13c3" ]
[ "code/pyto/tomo/ctf.py", "code/pyorg/scripts/arp23/arp_uni_2nd_W.py", "code/pyto/util/test/test_numpy_plus.py", "code/pyto/util/test/test_scipy_plus.py", "code/pyto/segmentation/cleft.py", "code/pyorg/scripts/syn/syn_column_analysis.py", "code/tutorials/synth_sumb/tracing/mb_graph_batch.py", "code/pyorg/surf/segmentations.py", "code/pyorg/scripts/synthetic/gen_microsomes.py" ]
[ "\"\"\"\nFunctions related to ctf.\n\nCurrently only few that allow running ctffind from console or notebook.\n\nWork in progress.\n\n# Author: Vladan Lucic (Max Planck Institute for Biochemistry)\n# $Id$\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom builtins import zip\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nfrom past.builtins import basestring\n\n__version__ = \"$Revision$\"\n\nimport os\nimport subprocess\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pyto.util.nested\nfrom pyto.io.image_io import ImageIO\nfrom pyto.grey.image import Image\n\n\nclass Ctf(object):\n \"\"\"\n Determination of CTF by external tools\n \"\"\"\n\n # prefix for validation attributed obtained from gctf\n validation_prefix = \"validation_\"\n\n # default params ctffind 4.0.17, also 4.1\n default_params_ctffind = {\n \"pixel_a\":1, \"cs\":2.7, \"amp\":0.1, \"phase\":\"no\", 'box':512, \n 'min_res':30, 'max_res':5, 'min_def':5000, 'max_def':50000, \n 'def_step':500, 'astig':100, 'known_astig':'no', 'slow_search':'yes',\n 'restraint_astig':'yes', 'tolerated_astig':200,\n 'phase':'yes', 'min_phase':0, 'max_phase':2, 'phase_step':0.1,\n 'expert':'no'}\n\n # parameter list for ctffind 4.0.17 (currently not used, left for reference)\n param_names_ctffind_4_0 = [\n 'pixel_a', 'voltage', 'cs', 'amp', 'box', 'min_res', 'max_res', \n 'min_def', 'max_def', 'def_step', 'astig', 'phase', \n 'min_phase', 'max_phase', 'phase_step']\n\n # default parameter list for 4.1; consistent with default_params_ctffind\n param_names_ctffind_4_1 = [\n 'pixel_a', 'voltage', 'cs', 'amp', 'box', 'min_res', 'max_res', \n 'min_def', 'max_def', 'def_step', 'known_astig', 'slow_search',\n 'restraint_astig','tolerated_astig',\n 'phase', 'min_phase', 'max_phase', 'phase_step', 'expert']\n\n def __init__(self):\n \"\"\"\n Initializes common attributes\n \"\"\"\n\n # attributes\n self.image_path_orig = []\n self.image_inds = []\n self.image_path = []\n self.ctf_path = []\n self.phases = []\n self.defoci_1 = []\n self.defoci_2 = []\n self.defoci = []\n self.resolution = []\n self.pixel_a = []\n self.angle = []\n\n @classmethod\n def find(\n cls, image_dir, image_prefix, ctf_dir, params, pixel_a=None, \n flatten='auto', tool='ctffind', executable=None,\n param_file='ctf_params.txt', fast=False, max_images=None, \n plot_ctf=True, plot_ps=True, b_plot=True, exp_f_plot=False, \n show_legend=True, plot_phases=True, plot_defoci=True, \n plot_resolution=True, print_results=True, print_validation=False):\n \"\"\"\n Determines and shows CTF fits for multiple images. \n\n All files located in (arg) image_dir whose namess start with (arg)\n image_prefix and that have extension mrc, em or st are selected\n for the ctf determination.\n\n If a selected file is 3D (image stack), and arg flatten is True or \n 'auto', all z-slices are summed up (saved in ctf_dir) and the ctf \n is detemined on the resulting (flattened. Alternatively, if arg \n flatten is False, z-slices are extracted, saved in ctf_dir and \n analyzed separately.\n\n All resulting files, as well as the extraced or flattened images \n (in case of 3D files) are saved or moved to directory ctf_dir.\n\n CTF is determined using external tools. Current options are:\n - CTFFIND\n - gCTF \n These tools have to be installed externally.\n\n Parameters for the ctf tools are specified as a dictionary (arg params).\n Parameters used for both ctffind and gctf are:\n - 'pixel_a', 'voltage', 'cs', 'amp', 'box', 'min_res', 'max_res', \n 'min_def', 'max_def', 'def_step', 'astig', 'phase', \n 'min_phase', 'max_phase', 'phase_step'\n Voltage ('voltage') should always be specified. The pixel size \n (pixel_a) has to be specified in case it can not be read from \n the image header. All other parameters are optional, if they are\n not specified the ctffind / gctg default values are used.\n\n The default values should be fine for single particle images.\n Parameter recommendations for phase plate images are given in\n the ctffind / gctf documentation.\n\n In case of ctffind, arg params can also be a list containing the \n parameter values in the same order as specified above, starting\n with voltage.\n\n Important for ctffind: Because the required arguments differ between \n versions 4.0 and 4.1, as well as depend on values specified, it is \n not guaranteed that the dictionary form of arg params will work.\n In case of problems, specify params as a list.\n\n In addition, all other gctf arguments can also be specified \n (without '--'). It is suggested to use:\n 'do_EPA':'', 'do_validation':''\n\n Parameter units are the same as in the ctf deterimantion tools.\n\n Intended for use in an environment such as Jupyter notebook.\n\n Arguments:\n - image_dir: directory where images reside\n - image prefix: beginning of image file(s)\n - ctf_dir: directory where the ctf determination results and \n extracted images are saved\n - pixel_a: pixel size in A\n - params: ctf determination parameters\n - flatten: indicated whether 3D images should be flatten (True or \n 'auto') or not (False).\n - tool: name of the ctf detmination tool\n - executable: ctf tool executable\n - param_file: name of the temporary parameter file \n - fast: flag indicating whether ctffind --fast option is used\n - print_results: flag indicating if phase and defoci found \n are printed for each analyzed image\n - plot_ctf: flag indicating whether ctf is plotted for each \n analyzed image\n - show_legend: flag indicating whether a legend is shown on ctf graphs\n - plot_phases, plot_defoci: flags indicating whether a graph \n containing phases and defoci of all images respectivelly are plotted\n - max_images: max number if image analyzed, for testing\n\n Returns an instance of this class. The following attributes are all \n lists where elements correspond to individual images:\n - image_path_orig: image path of the input file\n - image_path: image path of the image that is actually used\n to deterime ctf. It differs from image_path_orig if the original\n (input) image is a stack that is flattened or used to extract slices\n - image_inds: index of a slice extracted for a stack\n - ctf_path: path of the ctf fit image\n - defocus_1, defocus_2, defocus: defoci along the two axes and the\n mean defocus in um\n - angle: defocus (astigmatism) angle\n - phase: phase shift in multiples of pi\n - resolution: resolution in nm\n - ccc: correlation coefficient\n - pixel_a: pixel size in A\n - b_factor: b-factor (gctf only)\n \"\"\"\n\n # initialize\n index = 0\n new = cls()\n print_head = True\n if plot_ctf and fast: \n print(\n \"Warning: CTF will not be plotted because fast execution\"\n + \" was chosen\")\n\n # check which ctf tool to use\n if tool == 'ctffind':\n if executable is None:\n executable = 'ctffind'\n elif tool == 'gctf':\n if executable is None:\n executable = 'gctf'\n else:\n raise ValueError(\n \"CTF determination tool \" + str(tool) + \" was not understood.\")\n new.tool = tool\n\n # cftfind on all images\n file_list = np.sort(os.listdir(image_dir))\n for image_name in file_list:\n\n # skip files that are not images\n if not image_name.startswith(image_prefix): continue\n if not (image_name.endswith('.mrc') or image_name.endswith('.st') \n or image_name.endswith('.em')): \n continue\n if image_name.endswith('ctf.mrc'): continue\n\n # set input image path \n image_path = os.path.join(image_dir, image_name)\n\n # figure out if to flatten or not (just once, assume all files \n # are the same)\n im_io = ImageIO(file=image_path)\n if image_name.endswith('.st'):\n im_io.readHeader(fileFormat='mrc')\n else:\n im_io.readHeader()\n z_dim = im_io.shape[2]\n n_digits = int(np.ceil(np.log10(z_dim)))\n if isinstance(flatten, bool):\n pass\n elif isinstance(flatten, basestring) and (flatten == 'auto'):\n if z_dim > 1: \n flatten = True\n else:\n flatten = False\n else:\n raise ValueError(\n \"Argument flatten: \"+ str(flatten) +\" was not understood.\") \n\n # load stack and prepare image name, if need to extract images\n if (z_dim > 1) and not flatten:\n image_dir, image_name = os.path.split(image_path)\n image_base, image_extension = image_name.rsplit('.', 1)\n image_name_new_tmplt = (\n image_base + '_%0' + str(n_digits) + 'd.mrc')\n if image_name.endswith('.st'):\n stack = Image.read(\n image_path, memmap=True, fileFormat='mrc')\n else:\n stack = Image.read(image_path, memmap=True)\n else:\n image_path_to_read = image_path\n\n # find ctf of the current image or stack\n for image_in_stack_ind in range(z_dim):\n\n # extract and save images if needed\n if (z_dim > 1) and not flatten:\n if not os.path.exists(ctf_dir): os.makedirs(ctf_dir)\n image_path_to_read = os.path.join(\n ctf_dir, (image_name_new_tmplt % image_in_stack_ind))\n one_image = Image()\n one_image.data = stack.data[:,:,image_in_stack_ind]\n one_image.write(\n file=image_path_to_read, pixel=stack.pixelsize)\n\n # save image path retlated\n new.image_path_orig.append(image_path)\n new.image_inds.append(image_in_stack_ind)\n new.image_path.append(image_path_to_read)\n\n # find ctf\n if tool == 'ctffind':\n\n # ctffind\n res_one = cls.ctffind(\n image_path=image_path_to_read, flatten=flatten, \n ctf_dir=ctf_dir, executable=executable, \n pixel_a=pixel_a, params=params, \n param_file=param_file, fast=fast, print_head=print_head,\n print_results= print_results, \n plot_ctf=plot_ctf, show_legend=show_legend)\n\n elif tool == 'gctf':\n\n # gctf\n res_one = cls.gctf(\n image_path=image_path_to_read, params=params, \n pixel_a=pixel_a, flatten=flatten, ctf_dir=ctf_dir, \n executable=executable, \n plot_ctf=plot_ctf, plot_ps=plot_ps ,b_plot=b_plot, \n exp_f_plot=exp_f_plot, show_legend=show_legend,\n print_results=print_results, \n print_head=print_head, \n print_validation=print_validation)\n \n # save gctf specific data\n try:\n new.b_factor.append(res_one['b_factor'])\n except AttributeError:\n new.b_factor = [res_one['b_factor']]\n for name, value in list(res_one.items()):\n if name.startswith(cls.validation_prefix):\n try:\n previous_val = getattr(new, name)\n previous_val.append(value)\n setattr(new, name, previous_val)\n except AttributeError:\n setattr(new, name, [value])\n\n else:\n raise ValueError(\"Sorry tool: \" + tool + \" was not found.\")\n\n # save data common for ctffind and gctf\n new.phases.append(res_one[\"phase\"])\n new.defoci.append(res_one[\"defocus\"])\n new.defoci_1.append(res_one['defocus_1'])\n new.defoci_2.append(res_one['defocus_2'])\n new.resolution.append(res_one['resolution'])\n new.pixel_a.append(res_one['pixel_a'])\n new.angle.append(res_one['angle'])\n new.ctf_path.append(res_one['ctf_path'])\n\n # keep track of n images processed so far\n print_head = False\n index = index + 1\n if (max_images is not None) and (index > max_images): break\n if flatten: break\n\n # plot phases\n if plot_phases:\n plt.figure()\n plt.bar(list(range(index)), new.phases)\n plt.plot([0, index], [0.5, 0.5], 'r--')\n plt.ylabel('Phase shift [$\\pi$]')\n plt.xlabel('Images')\n plt.title(\"Phase shift summary\")\n\n # plot defocus\n if plot_defoci:\n plt.figure()\n plt.bar(list(range(index)), new.defoci)\n plt.ylabel('Defocus [$\\mu m$]')\n plt.xlabel('Images')\n plt.title(\"Defocus summary\")\n\n # plot resolution\n if plot_resolution:\n plt.figure()\n plt.bar(list(range(index)), new.resolution)\n plt.ylabel('Resolution [nm]')\n plt.xlabel('Images')\n plt.title(\"Resolution summary\")\n\n return new\n\n @classmethod\n def ctffind(\n cls, image_path, ctf_dir, params, pixel_a=None, flatten=False, \n executable='ctffind', param_file='ctf_params.txt', fast=False, \n print_results=True, print_head=True, \n plot_ctf=True, show_legend=True):\n \"\"\"\n Determines and shows CTF fits of one image using ctffind.\n\n See find() for more information.\n \"\"\"\n\n # make ctf dir if doesn't exist\n if not os.path.exists(ctf_dir): os.makedirs(ctf_dir)\n\n # find pixel size\n if pixel_a is None:\n pixel_a = cls.read_pixel_size(image_path=image_path) \n\n # flatten frame stack\n if flatten:\n image_path = cls.flatten_stack(\n stack_path=image_path, flat_dir=ctf_dir)\n\n # default params ctffind 4.0.17 (moved to top of this file anyway)\n #default_params = {\n # \"pixel_a\":1, \"cs\":2.7, \"amp\":0.1, \"phase\":\"no\", 'box':512, \n # 'min_res':30, 'max_res':5, 'min_def':5000, 'max_def':50000, \n # 'def_step':500, 'astig':100, 'phase':'no', 'min_phase':0, \n # 'max_phase':2, 'phase_step':0.1}\n #param_names = [\n # 'pixel_a', 'voltage', 'cs', 'amp', 'box', 'min_res', 'max_res', \n # 'min_def', 'max_def', 'def_step', 'astig', 'phase', \n # 'min_phase', 'max_phase', 'phase_step']\n \n # keep params if list, add default if dict\n if isinstance(params, list):\n comb_params = [pixel_a] + params\n elif isinstance(params, dict):\n params_dict = cls.default_params_ctffind.copy()\n params_dict.update(params)\n params_dict['pixel_a'] = pixel_a\n param_names = cls.make_param_names_ctffind(params=params_dict)\n comb_params = [params_dict[name] for name in param_names]\n\n # set ctffind out paths\n image_dir, image_name = os.path.split(image_path)\n image_base, image_extension = image_name.rsplit('.', 1)\n ctf_path = os.path.join(ctf_dir, image_base + '_ctf.mrc') \n ctf_txt_path = os.path.join(ctf_dir, image_base + '_ctf.txt')\n ctf_avrot_path = os.path.join(ctf_dir, image_base + '_ctf_avrot.txt')\n\n # wite ctf parameters to a file\n param_path = os.path.join(ctf_dir, param_file)\n pf = open(param_path, 'w')\n pf.write(image_path + '\\n')\n pf.write(ctf_path + '\\n')\n str_params = [str(par) + '\\n' for par in comb_params]\n pf.writelines(str_params)\n pf.flush()\n\n # execute ctffind\n # shell commands that work:\n # - ctffind < param_path\n # - cat params.txt | ctffind\n #print(image)\n if fast:\n ctf_cmd = [executable, '--fast']\n else:\n ctf_cmd = [executable]\n try:\n subprocess.check_call(ctf_cmd, stdin=open(param_path))\n except Exception as exc:\n # workaround for ctffind command returning code 255 (4.1.8, 09.2018)\n logging.debug('CalledProcessError: ' + str(exc))\n \n # read results:\n ctf_txt = np.loadtxt(ctf_txt_path)\n results = {\n \"defocus_1\":ctf_txt[1]/10000., \"defocus_2\":ctf_txt[2]/10000., \n \"angle\" : ctf_txt[3], \"phase\":old_div(ctf_txt[4],np.pi), \n \"ccc\" : ctf_txt[5], \"resolution\" : ctf_txt[6] / 10., \n 'pixel_a':pixel_a}\n results['defocus'] = (results['defocus_1'] + results['defocus_2']) / 2.\n results['ctf_path'] = ctf_path\n\n # prepare header for defoci and phases\n if print_head:\n left_space = ' ' * old_div((len(image_name) - 5), 2)\n right_space = ' ' *old_div ((len(image_name) - 4), 2)\n head_1 = (\n left_space + \"Image\" + right_space + \n \" Defocus 1 Defocus 2 Phase Resolution\")\n head_2 = (\n left_space + \" \" + right_space + \n \" um um [pi] nm \")\n\n # prepare results\n if print_results:\n data_format = '%s %6.2f %6.2f %6.2f %6.2f '\n data_vars = (\n image_name, results[\"defocus_1\"], results[\"defocus_2\"], \n results[\"phase\"], results[\"resolution\"])\n\n # print\n if print_head:\n print(head_1)\n print(head_2)\n if print_results:\n print(data_format % data_vars)\n\n # plot ctf\n if plot_ctf:\n plt.figure()\n avrot_data = np.loadtxt(ctf_avrot_path)\n x_data = avrot_data[0] / pixel_a\n plt.plot(x_data, avrot_data[2], 'g-', label='PS')\n plt.plot(\n x_data, avrot_data[3], color='orange', linewidth=2, \n label='CTF fit')\n plt.plot(\n x_data, avrot_data[4], color='blue', linewidth=2, \n label='Quality')\n plt.ylim(-0.1, 1.1)\n plt.xlabel(\"Spatial frequency [1/A])\")\n plt.ylabel(\"Amplitude\")\n if show_legend: plt.legend()\n plt.show()\n\n return results\n\n @classmethod\n def make_param_names_ctffind(cls, params):\n \"\"\"\n Makes a list of parameter names that's suitable for ctffind 4.1 and\n it is in accordance with the specified params.\n\n Argument:\n - params: dict of parameters\n\n Returns parameter list\n \"\"\"\n\n # optional parts\n if params['restraint_astig'] in ['yes', 'y']:\n restraint_astig_part = ['restraint_astig','tolerated_astig']\n else:\n restraint_astig_part = ['restraint_astig']\n if (params['phase'] == 'yes') or (params['phase'] == 'y'):\n phase_part = ['phase', 'min_phase', 'max_phase', 'phase_step']\n else:\n phase_part = ['phase']\n\n # combine\n param_names = (\n cls.param_names_ctffind_4_1[:12] + restraint_astig_part\n + phase_part + ['expert'])\n\n return param_names\n \n @classmethod\n def gctf(\n cls, image_path, ctf_dir, params, pixel_a=None, flatten=False, \n executable='gctf', plot_ps=True, plot_ctf=True, \n b_plot=True, exp_f_plot=False, show_legend=True, \n print_results=True, print_head=True, print_validation=False):\n \"\"\"\n Determines and shows CTF fits of one image using gctf.\n\n See find() for more information.\n \"\"\" \n\n # make ctf dir if doesn't exist\n if not os.path.exists(ctf_dir): os.makedirs(ctf_dir)\n\n # find pixel size\n if pixel_a is None:\n pixel_a = cls.read_pixel_size(image_path=image_path) \n\n # flatten frame stack if needed\n if flatten:\n image_path = cls.flatten_stack(\n stack_path=image_path, flat_dir=ctf_dir)\n\n # prepare parameters\n gctf_names = {\n 'pixel_a':'apix', 'voltage':'kV', 'cs':'Cs', 'amp':'ac', \n 'box':'boxsize', 'min_res':'resL', 'max_res':'resH', \n 'min_def':'defL', 'max_def':'defH', 'def_step':'defS', \n 'astig':'astm', 'phase':'phase', 'min_phase':'phase_shift_L', \n 'max_phase':'phase_shift_H', 'phase_step':'phase_shift_S'}\n params[\"pixel_a\"] = pixel_a \n params_list = [\n [\"--\" + gctf_names.get(key, key), str(val)] \n for key, val in list(params.items())]\n params_list = pyto.util.nested.flatten(params_list)\n params_list = [par for par in params_list if len(par) > 0]\n #print(params_list)\n\n # execute ctffind\n ctf_cmd = [executable] + params_list + [image_path]\n call_status = subprocess.check_call(ctf_cmd)\n\n # set gctf out paths\n image_dir, image_name = os.path.split(image_path)\n image_base, image_extension = image_name.rsplit('.', 1)\n epa_path = os.path.join(ctf_dir, image_base + '_EPA.log')\n gctf_path = os.path.join(ctf_dir, image_base + '_gctf.log') \n ctf_path = os.path.join(ctf_dir, image_base + '.ctf') \n tmp_epa_path = os.path.join(image_dir, image_base + '_EPA.log')\n tmp_gctf_path = os.path.join(image_dir, image_base + '_gctf.log') \n tmp_ctf_path = os.path.join(image_dir, image_base + '.ctf') \n\n # move generated files to ctf_dir\n if image_dir != ctf_dir:\n call_status = subprocess.check_call(['mv', tmp_epa_path, epa_path])\n call_status = subprocess.check_call(\n ['mv', tmp_gctf_path, gctf_path])\n call_status = subprocess.check_call(['mv', tmp_ctf_path, ctf_path])\n call_status = subprocess.check_call(\n ['mv', 'micrographs_all_gctf.star', ctf_dir])\n\n # read results\n in_last_cycle = False\n in_last_cycle_data = False\n validation_lines = []\n for line in open(gctf_path):\n\n # read defocus\n if line.find('LAST CYCLE') >= 0: \n in_last_cycle = True\n #print line.strip('\\n')\n elif in_last_cycle and (line.find('Defocus_U') >= 0): \n #print line.strip('\\n')\n head_split = line.strip().split()\n in_last_cycle_data = True\n elif in_last_cycle_data:\n #print line.strip('\\n')\n data_split = line.strip().split()[:-2]\n in_last_cycle_data = False\n\n # read res limit and b factor\n elif in_last_cycle and line.startswith('Resolution limit'): \n resolution = float(line.split()[-1])\n elif in_last_cycle and line.startswith('Estimated Bfactor'): \n b_factor = float(line.split()[-1])\n in_last_cycle = False\n\n # read validation\n elif line.find('VALIDATION_SCORE') >= 0:\n validation_lines.append(line.strip('\\n'))\n\n # extract results\n results_native = dict(\n [(head, float(value)) \n for head, value in zip(head_split, data_split)])\n results_native[\"Defocus_U\"] = results_native[\"Defocus_U\"] / 10000.\n results_native[\"Defocus_V\"] = results_native[\"Defocus_V\"] / 10000.\n #print(results_native)\n key_dict = {\n \"Defocus_U\":\"defocus_1\", \"Defocus_V\":\"defocus_2\",\n \"Angle\":\"angle\", \"CCC\":\"ccc\", \"Phase_shift\":\"phase\"}\n results = dict([\n (key_dict[old_key], value)\n for old_key, value in list(results_native.items())])\n results['defocus'] = (results['defocus_1'] + results['defocus_2']) / 2.\n results['phase'] = results.get('phase', 0) / 180.\n results[\"resolution\"] = resolution / 10.\n results[\"b_factor\"] = b_factor\n #if results.get(\"phase\") is None: results[\"phase\"] = 0\n results['ctf_path'] = ctf_path\n results['pixel_a'] = pixel_a\n for val_line in validation_lines:\n val_list = val_line.strip().split()\n name_suf = val_list[0].replace('-', '_')\n results[cls.validation_prefix + name_suf] = int(val_list[-1])\n\n # prepare header for defoci and phases\n if print_head:\n left_space = ' ' * (old_div((len(image_name) - 5), 2))\n right_space = ' ' * (old_div((len(image_name) - 4), 2))\n head_1 = (\n left_space + \"Image\" + right_space + \n \" Defocus 1 Defocus 2 Phase Resolution\")\n head_2 = (\n left_space + \" \" + right_space + \n \" um um [pi] nm \")\n\n # prepare results\n if print_results:\n data_format = '%s %6.2f %6.2f %6.2f %6.2f '\n data_vars = (\n image_name, results[\"defocus_1\"], results[\"defocus_2\"], \n results[\"phase\"], results[\"resolution\"])\n\n # add validation to header and results\n val_names = np.sort(\n [val_nam for val_nam in results\n if val_nam.startswith(cls.validation_prefix)])[::-1]\n for val_nam in val_names:\n if print_head:\n head_1 += (\" \" + val_nam.split(cls.validation_prefix, 1)[1])\n head_2 += \" \"\n if print_results:\n data_format += ' %2d '\n data_vars += (results[val_nam],)\n\n # print\n if print_head:\n print(head_1)\n print(head_2)\n if print_results:\n print(data_format % data_vars)\n\n # print validation\n if print_validation:\n for val_line in validation_lines:\n print(val_line)\n\n # plot ctf\n epa = np.loadtxt(epa_path, skiprows=1)\n if plot_ps:\n plt.figure()\n plt.plot(1./epa[:,0], epa[:,2])\n plt.ylabel('ln(|F|)')\n #if show_legend: plt.legend()\n plt.show()\n if plot_ctf:\n plt.figure()\n if b_plot:\n exp_b = np.exp(-b_factor * 1./epa[:,0]**2 / 4.)\n else:\n exp_b = 1\n plt.plot(1./epa[:,0], epa[:,1] * exp_b, label=\"CTF fit\")\n if exp_f_plot:\n plt.plot(\n 1./epa[:,0], np.exp(epa[:,3]), label=\"$e^{ln(|F|-Bg)}$\")\n else:\n plt.plot(1./epa[:,0], epa[:,3], label=\"$ln(|F|-Bg)$\")\n plt.xlabel('Resolution [1/A]')\n if show_legend: plt.legend()\n plt.show()\n\n # return\n return results\n\n @classmethod\n def read_pixel_size(cls, image_path):\n \"\"\"\n Reads pixel size from an image file.\n\n Raises ValueError if pixel size can not be read from the image\n\n Argument:\n - image_path: image path\n\n Returns: pixel size in A\n \"\"\"\n\n image_io = ImageIO()\n if image_path.endswith('.st'):\n image_io.readHeader(file=image_path, fileFormat='mrc')\n else:\n image_io.readHeader(file=image_path)\n if image_io.pixel is not None:\n if isinstance(image_io.pixel, (list, tuple)):\n pixel_a = 10 * image_io.pixel[0] \n else:\n pixel_a = 10 * image_io.pixel\n else:\n raise ValueError(\n \"Pixel size could not be found from image \" + image_path +\n \". Please specify pixel_a as an argument.\")\n\n # in case of 0 pix size\n if pixel_a == 0:\n raise ValueError(\n \"Pixel size could not be found from image \" + image_path +\n \". Please specify pixel_a as an argument.\")\n\n return pixel_a\n\n @classmethod\n def flatten_stack(cls, stack_path, flat_dir):\n \"\"\"\n Flattens image stack, that is sums up all z-slices and writes\n the resulting (flat) image).\n\n Arguments:\n - stack_path: path to the image stack\n - flat_path: path where the resulting image is saved\n\n Returns resulting image path\n \"\"\"\n\n # parse stack path\n stack_dir, stack_name = os.path.split(stack_path)\n stack_base, stack_extension = stack_name.rsplit('.', 1)\n if stack_extension == 'st': \n stack_extension = 'mrc'\n file_format = 'mrc'\n else:\n file_format = None\n\n # read, flatten and write\n flat_path = os.path.join(\n flat_dir, stack_base + '_flat.' + stack_extension)\n frame = Image.read(file=stack_path, fileFormat=file_format)\n frame.data = np.sum(frame.data, axis=2, dtype=frame.data.dtype)\n frame.write(file=flat_path, pixel=frame.pixelsize)\n\n return flat_path\n", "\"\"\"\n\n Performs Univariate 2nd order analysis from a STAR file with a set of ListTomoParticles entries\n\n Input: - A STAR file with a set of ListTomoParticles pickles\n\n Output: - Plots with the analysis\n - Matrix with the analysis for further post-processing\n\n\"\"\"\n\n################# Package import\n\nimport os\nimport pickle\nimport numpy as np\nimport scipy as sp\nimport sys\nimport time\nfrom pyorg import pexceptions, sub, disperse_io, surf\nfrom pyorg.globals import unpickle_obj, sort_dict\nfrom pyorg.surf.model import ModelCSRV\nfrom pyorg.surf.utils import list_tomoparticles_pvalues\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot as plt, rcParams\n\n###### Global variables\n\n__author__ = 'Antonio Martinez-Sanchez'\n\nBAR_WIDTH = .35\n\nrcParams['axes.labelsize'] = 20\nrcParams['xtick.labelsize'] = 20\nrcParams['ytick.labelsize'] = 20\n\n########################################################################################\n# PARAMETERS\n########################################################################################\n\nROOT_PATH = '/fs/pool/pool-lucic2/antonio/tomograms/marion/Arp23complex'\n\n# Input STAR file\nin_star = ROOT_PATH + '/ltomos_sep/W_sep_mask/W_all_mask_ltomos.star' # '/ltomos_all/W_all_mask/W_all_mask_ltomos.star' # '/ref_a3/ltomos/pre_ltomos.star' # '/ref_a2/ltomos/pre_ref_a2_12_ltomos_hold.star'\n\n# Input matrices (optional - organization analysis is skipped)\nin_mats_lists = None # ROOT_PATH + '/uni_sph_sep_W/W_sep_sim10_org_lists.pkl' # ROOT_PATH + '/ref_a3/uni_sph/uni_sph_4_60_2_org_list.pkl'\n\n# Output directory\nout_dir = ROOT_PATH + '/uni_sph_sep_W'\nout_stem = 'W_sep_sim10' # ''uni_sph_4_60_5'\n\n# Analysis variables\nana_res = 1.684 # nm/voxel\nana_rg = np.arange(5, 800, 10) # np.arange(4, 100, 2) # in nm\nana_shell_thick = None # 3\nana_border = True\nana_keep = None\nana_conv_iter = 100\nana_max_iter = 100000\nana_gl = False\nana_npr = 1 # None means Auto\n\n# P-value computation settings\n# Simulation model (currently only CSRV)\ndo_p_value = True\np_nsims = 1\np_per = 5 # %\np_pwise = False\n# Particle surface\np_vtp = ROOT_PATH + '/in/iter19_apix_16.84_center.vtp'\nin_mats_sims = None # ROOT_PATH + '/ref_a3/uni_shell/uni_shell_4_60_3_org_sims.pkl'\n\n# Figure saving options\nfig_fmt = '.png' # if None they showed instead\n\n# Plotting options\npt_xrange = [0, 800]\npt_yrange = [-25, 35] # [0, 10]\npt_cmap = plt.get_cmap('gist_rainbow')\n\n########################################################################################\n# MAIN ROUTINE\n########################################################################################\n\n# Units conversion\nana_rg_v = ana_rg / ana_res\nana_shell_thick_v = None\nif ana_shell_thick is not None:\n ana_shell_thick_v = float(ana_shell_thick) / ana_res\n\n########## Print initial message\n\nprint('Univariate second order analysis for a ListTomoParticles.')\nprint('\\tAuthor: ' + __author__)\nprint('\\tDate: ' + time.strftime(\"%c\") + '\\n')\nprint('Options:')\nprint('\\tOutput directory: ' + str(out_dir))\nprint('\\tOuput stem: ' + str(out_stem))\nprint('\\tInput STAR file: ' + str(in_star))\nif in_mats_lists is None:\n print('\\tOrganization analysis settings: ')\n print('\\t\\t-Range of radius: ' + str(ana_rg) + ' nm')\n print('\\t\\t-Range of radius: ' + str(ana_rg_v) + ' voxels')\n if ana_shell_thick is None:\n print('\\t\\t-Spherical neighborhood')\n else:\n print('\\t\\t-Shell neighborhood with thickness: ' + str(ana_shell_thick) + ' nm')\n print('\\t\\t-Shell neighborhood with thickness: ' + str(ana_shell_thick_v) + ' voxels')\n if ana_keep is not None:\n print('\\t\\t-Keep highest populated tomograms per list: ' + str(ana_keep))\n print('\\t\\t-Convergence number of samples for stochastic volume estimations: ' + str(ana_conv_iter))\n print('\\t\\t-Maximum number of samples for stochastic volume estimations: ' + str(ana_max_iter))\n if ana_gl:\n print('\\t\\t-Global analysis activated.')\n if ana_npr is None:\n print('\\t\\t-Number of processors: Auto')\n else:\n print('\\t\\t-Number of processors: ' + str(ana_npr))\nelse:\n if in_mats_lists is not None:\n print('\\tDensity ratios by list dictionary pickled from file: ' + in_mats_lists)\nif do_p_value:\n print('\\tP-Value computation setting:')\n print('\\t\\t-Percentile: ' + str(p_per) + ' %')\n if in_mats_sims is None:\n print('\\t\\t-Number of instances for simulations: ' + str(p_nsims))\n print('\\t\\t-Particle surface: ' + p_vtp)\n else:\n print('\\t\\t-Using pre-computed matrix for simulations: ' + in_mats_sims)\n if p_pwise:\n print('\\t\\t-Pointwise analysis activated.')\n else:\n print('\\t\\t-Tomogram analysis activated.')\nif fig_fmt is not None:\n print('\\tStoring figures:')\n print('\\t\\t-Format: ' + str(fig_fmt))\nelse:\n print('\\tPlotting settings: ')\nprint('\\t\\t-Colormap: ' + str(pt_cmap))\nprint('\\t\\t-X-axis range: ' + str(pt_xrange))\nprint('\\t\\t-Y-axis range: ' + str(pt_yrange))\nprint('')\n\n######### Process\n\nprint('Main Routine: ')\nmats_lists, gl_lists = None, None\n\nprint('\\tLoading input STAR file...')\nstar = sub.Star()\ntry:\n star.load(in_star)\nexcept pexceptions.PySegInputError as e:\n print('ERROR: input STAR file could not be loaded because of \"' + e.get_message() + '\"')\n print('Terminated. (' + time.strftime(\"%c\") + ')')\n sys.exit(-1)\nset_lists = surf.SetListTomoParticles()\nfor row in range(star.get_nrows()):\n ltomos_pkl = star.get_element('_psPickleFile', row)\n ltomos = unpickle_obj(ltomos_pkl)\n if ana_keep is not None:\n ltomos.clean_low_pouplated_tomos(ana_keep)\n set_lists.add_list_tomos(ltomos, ltomos_pkl)\n\nprint('\\tComputing number of particles by list...')\nnp_lists = set_lists.particles_by_list()\nnp_lists_skeys, np_lists_svalues = sort_dict(np_lists, np_lists, reverse=True)\ncolor_lists, color_lists_inv, klass_lbls, klass_lbls_inv = dict(), dict(), dict(), dict()\nfor i, key in enumerate(np_lists_skeys):\n klass_lbl = os.path.splitext(os.path.split(key)[1])[0]\n try:\n k_idx = klass_lbl.index('_')\n klass_lbl = klass_lbl[:k_idx]\n except IndexError:\n pass\n color_lists[key] = pt_cmap(1.*i/len(np_lists))\n color_lists_inv[i+1] = pt_cmap(1. * i / len(np_lists))\n klass_lbls[key] = klass_lbl\n klass_lbls_inv[int(klass_lbl)] = key\n print('\\t\\t-List ' + str(i+1) + ': ' + str(klass_lbl))\nklass_lbls_inv = dict(sorted(klass_lbls_inv.items()))\nplt.figure()\nplt.title('Num. particles by list')\nplt.ylabel('Num. particles')\nplt.xlabel('List')\nit, bars, lbls = 0, list(), list()\nfor key, val in zip(np_lists_skeys, np_lists_svalues):\n lbl = klass_lbls[key]\n bar, = plt.bar(it, val, width=0.75, color=color_lists[key], label=lbl)\n it += 1\n bars.append(bar)\n lbls.append(lbl)\nplt.legend(bars, lbls, loc=1)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_dir + '/' + out_stem + '_np_lists.png')\nplt.close()\nwith open(out_dir + '/' + out_stem + '_np_lists.pkl', \"wb\") as fl:\n pickle.dump(np_lists, fl)\n fl.close()\n\nprint('\\tComputing number of particles by tomogram...')\nnp_tomos = set_lists.particles_by_tomos()\nnp_tomos_skeys, np_tomos_svalues = sort_dict(np_tomos, np_tomos, reverse=True)\ncolor_tomos, tomo_lbls = dict(), dict()\nfor i, key in enumerate(np_tomos_skeys):\n tomo_lbl = os.path.split(key)[1]\n try:\n t_idx = tomo_lbl.index('_bin')\n tomo_lbl = tomo_lbl[:t_idx]\n except ValueError:\n pass\n color_tomos[key] = pt_cmap(1.*i/len(np_tomos))\n tomo_lbls[key] = tomo_lbl\n print('\\t\\t-Tomogram ' + str(i+1) + ': ' + str(tomo_lbl))\nplt.figure()\nplt.title('Num. particles by tomograms')\nplt.ylabel('Num. particles')\nplt.xlabel('Tomograms')\nit, bars, lbls = 0, list(), list()\nfor key, val in zip(np_tomos_skeys, np_tomos_svalues):\n lbl = tomo_lbls[key]\n bar, = plt.bar(it, val, width=0.75, color=color_tomos[key], label=lbl)\n it += 1\n bars.append(bar)\n lbls.append(lbl)\nplt.legend(bars, lbls, loc=1)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_dir + '/' + out_stem + '_np_tomos.png')\nplt.close()\nwith open(out_dir + '/' + out_stem + '_np_tomos.pkl', \"wb\") as fl:\n pickle.dump(np_tomos, fl)\n fl.close()\n\nprint('\\tComputing densities by list...')\ngl_lists = set_lists.density_by_list(surface=False)\ngl_lists_skeys, gl_lists_svalues = sort_dict(gl_lists, gl_lists, reverse=True)\ncolor_lists, klass_lbls = dict(), dict()\nfor i, key in enumerate(gl_lists_skeys):\n klass_lbl = os.path.splitext(os.path.split(key)[1])[0]\n try:\n k_idx = klass_lbl.index('_')\n klass_lbl = klass_lbl[:k_idx]\n except IndexError:\n pass\n color_lists[key] = pt_cmap(1.*i/len(gl_lists))\n klass_lbls[key] = klass_lbl\n print('\\t\\t-List ' + str(i+1) + ': ' + str(klass_lbl))\nplt.figure()\nplt.title('Density by list')\nden_cte = ana_res**3\nplt.ylabel('Particles/nm**3')\nplt.xlabel('List')\nit, bars, lbls = 0, list(), list()\nfor key, val in zip(gl_lists_skeys, gl_lists_svalues):\n lbl = klass_lbls[key]\n bar, = plt.bar(it, val, width=0.75, color=color_lists[key], label=lbl)\n it += 1\n bars.append(bar)\n lbls.append(lbl)\nplt.legend(bars, lbls, loc=1)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_dir + '/' + out_stem + '_den_lists.png')\nplt.close()\nwith open(out_dir + '/' + out_stem + '_den_lists.pkl', \"wb\") as fl:\n pickle.dump(gl_lists, fl)\n fl.close()\n\nprint('\\tComputing densities by tomogram...')\ngl_tomos = set_lists.density_by_tomos(surface=False)\ngl_tomos_skeys, gl_tomos_svalues = sort_dict(gl_tomos, gl_tomos, reverse=True)\ncolor_tomos, tomo_lbls = dict(), dict()\nfor i, key in enumerate(gl_tomos_skeys):\n tomo_lbl = os.path.split(key)[1]\n try:\n t_idx = tomo_lbl.index('_bin')\n tomo_lbl = tomo_lbl[:t_idx]\n except ValueError:\n pass\n color_tomos[key] = pt_cmap(1.*i/len(gl_tomos))\n tomo_lbls[key] = tomo_lbl\n print('\\t\\t-Tomogram ' + str(i+1) + ': ' + str(tomo_lbl))\nplt.figure()\nplt.title('Density by tomograms')\nplt.ylabel('Particles/nm**3')\nplt.xlabel('Tomograms')\nit, bars, lbls = 0, list(), list()\nfor key, vals in zip(gl_tomos_skeys, gl_tomos_svalues):\n lbl = tomo_lbls[key]\n bar, = plt.bar(it, den_cte*np.asarray(vals, dtype=float), width=0.75, color=color_tomos[key], label=lbl)\n it += 1\n bars.append(bar)\n lbls.append(lbl)\nplt.legend(bars, lbls, loc=1)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_dir + '/' + out_stem + '_den_tomos.png')\nplt.close()\nwith open(out_dir + '/' + out_stem + '_den_tomos.pkl', \"wb\") as fl:\n pickle.dump(gl_tomos, fl)\n fl.close()\n\nif in_mats_lists is None:\n\n if ana_keep is None:\n print('\\tComputing densities proportions of particles for every tomogram...')\n plt.figure()\n plt.title('Class proportions for tomograms.')\n props_dic = set_lists.proportions_by_list()\n set_tomos_name= set_lists.get_set_tomos()\n set_ntomos = len(set_tomos_name)\n index, offset = np.arange(set_ntomos), np.zeros(shape=set_ntomos, dtype=np.float)\n for key_1, props in zip(iter(props_dic.keys()), iter(props_dic.values())):\n plt.bar(index+.5*BAR_WIDTH, props, BAR_WIDTH, color=color_lists[key_1], bottom=offset,\n label=klass_lbls[key_1])\n offset += props\n syn_tomos_name = list()\n for tomos_name in set_tomos_name:\n syn_tomos_name.append(tomo_lbls[tomos_name][4:])\n plt.xticks(index + BAR_WIDTH, syn_tomos_name)\n plt.legend()\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_tomo_prop.png')\n plt.close()\n\n print('\\tComputing organization by list...')\n mats_lists = set_lists.compute_uni_2nd_order_by_list(distances=ana_rg_v, thick=ana_shell_thick_v, border=ana_border,\n conv_iter=ana_conv_iter, max_iter=ana_max_iter,\n dens_gl=ana_gl, npr=ana_npr, verbose=True)\n with open(out_dir + '/' + out_stem + '_org_lists.pkl', \"wb\") as fl:\n pickle.dump(mats_lists, fl)\n fl.close()\n\nprint('\\tPickling organization by lists...')\nif in_mats_lists is not None:\n with open(in_mats_lists, 'r') as pkl:\n mats_lists = pickle.load(pkl)\n\nif mats_lists is not None:\n plt.figure()\n # plt.title('Univariate 2nd Order by list')\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L')\n else:\n plt.ylabel('Ripley\\'s O')\n plt.xlabel('Distance [nm]')\n lines, lbls = list(), list()\n # mats_slists_keys, mats_slists_values = sort_dict(mats_lists, gl_lists, reverse=True)\n # for key, mat in zip(mats_slists_keys, mats_slists_values):\n print(klass_lbls_inv)\n for lbli, key in zip(iter(klass_lbls_inv.keys()), iter(klass_lbls_inv.values())):\n # hold_mat = stat_dict_to_mat(mat, ltomos)\n # arr = hold_mat.mean(axis=0)\n lbl = str(lbli)\n line, = plt.plot(ana_rg, mats_lists[key], color=color_lists_inv[lbli], label=lbl, linewidth=2)\n # plt.plot(ana_rg, mat, color=color_lists[key], linewidth=2)\n lines.append(line)\n lbls.append(lbl)\n # plt.legend(lines, lbls, loc=3)\n plt.legend(lines, lbls, bbox_to_anchor=(0.05, 0.05, 0.25, 0.45))\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_org_list.png')\n plt.close()\nelse:\n print('ERROR: organization could not be computed')\n print('Unsuccessfully terminated. (' + time.strftime(\"%c\") + ')')\n sys.exit(-1)\n\nif do_p_value:\n\n if in_mats_sims is None:\n in_model = ModelCSRV\n try:\n part_vtp = disperse_io.load_poly(p_vtp)\n except pexceptions.PySegInputError as e:\n print('ERROR: reference particle surface file could not be loaded because of \"' + e.get_message() + '\"')\n print('Terminated. (' + time.strftime(\"%c\") + ')')\n sys.exit(-1)\n\n print('\\tComputing simulations for p-value by list...')\n mats_sims = set_lists.simulate_uni_2nd_order_matrix(p_nsims, ModelCSRV, part_vtp,\n ana_rg_v, thick=ana_shell_thick_v, border=ana_border,\n conv_iter=ana_conv_iter, max_iter=ana_max_iter,\n dens_gl=ana_gl, pointwise=p_pwise,\n npr=ana_npr, verbose=True)\n with open(out_dir + '/' + out_stem + '_org_sims.pkl', \"wb\") as fl:\n pickle.dump(mats_sims, fl)\n fl.close()\n else:\n with open(in_mats_sims, 'r') as pkl:\n mats_sims = pickle.load(pkl)\n\n lines, lbls = list(), list()\n mats_slists_keys, mats_slists_values = sort_dict(mats_lists, gl_lists, reverse=True)\n for key, mat in zip(mats_slists_keys, mats_slists_values):\n lbl = klass_lbls[key]\n plt.figure()\n plt.title('Simulation univariate 2nd ' + lbl)\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L - IC [' + str(p_per) + ', ' + str(100-p_per) + ']%')\n else:\n plt.ylabel('Ripley\\'s O - IC [' + str(p_per) + ', ' + str(100-p_per) + ']%')\n plt.xlabel('Radius')\n # hold_mat = stat_dict_to_mat(mat, ltomos)\n # arr = hold_mat.mean(axis=0)\n plt.plot(ana_rg, mat, 'b')\n plt.plot(ana_rg, np.median(mats_sims[key], axis=0), 'k')\n plt.plot(ana_rg, np.percentile(mats_sims[key], p_per, axis=0), 'k--')\n plt.plot(ana_rg, np.percentile(mats_sims[key], 100-p_per, axis=0), 'k--')\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n # plt.show(block=key)\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_' + lbl + '_org_list.png')\n plt.close()\n\n print('\\tComputing p-values...')\n p_values = list_tomoparticles_pvalues(ana_rg, mats_lists, mats_sims)\n\n plt.figure()\n plt.title('Maximum low P-Value')\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L (p-value)')\n else:\n plt.ylabel('Ripley\\'s O (p-value)')\n # plt.xticks(klass_lbls)\n lines, lbls = list(), list()\n p_values_keys, p_values_values = sort_dict(p_values, gl_lists, reverse=True)\n for i, key, p_value in zip(list(range(len(p_values_keys))), p_values_keys, p_values_values):\n lbl = klass_lbls[key]\n line, = plt.bar(i, 1.+.01*p_value[2], color=color_lists[key], label=lbl)\n plt.legend()\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n # plt.show(block=True)\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_pval_low.png')\n plt.close()\n\n plt.figure()\n plt.title('Radius for maximum low P-values')\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L (radius)')\n else:\n plt.ylabel('Ripley\\'s O (radius)')\n # plt.xticks(klass_lbls)\n lines, lbls = list(), list()\n p_values_keys, p_values_values = sort_dict(p_values, gl_lists, reverse=True)\n for i, key, p_value in zip(list(range(len(p_values_keys))), p_values_keys, p_values_values):\n lbl = klass_lbls[key]\n line, = plt.bar(i, p_value[0], color=color_lists[key], label=lbl)\n plt.legend()\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n # plt.show(block=True)\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_pval_low_rad.png')\n plt.close()\n\n plt.figure()\n plt.title('Maximum high P-Value')\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L (p-value)')\n else:\n plt.ylabel('Ripley\\'s O (p-value)')\n # plt.xticks(klass_lbls)\n lines, lbls = list(), list()\n p_values_keys, p_values_values = sort_dict(p_values, gl_lists, reverse=True)\n for i, key, p_value in zip(list(range(len(p_values_keys))), p_values_keys, p_values_values):\n lbl = klass_lbls[key]\n line, = plt.bar(i, 1.-.01*p_value[3], color=color_lists[key], label=lbl)\n plt.legend()\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n # plt.show(block=True)\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_pval_high.png')\n plt.close()\n\n plt.figure()\n plt.title('Radius for maximum low P-values')\n if ana_shell_thick is None:\n plt.ylabel('Ripley\\'s L (radius)')\n else:\n plt.ylabel('Ripley\\'s O (radius)')\n # plt.xticks(klass_lbls)\n lines, lbls = list(), list()\n p_values_keys, p_values_values = sort_dict(p_values, gl_lists, reverse=True)\n for i, key, p_value in zip(list(range(len(p_values_keys))), p_values_keys, p_values_values):\n lbl = klass_lbls[key]\n line, = plt.bar(i, p_value[1], color=color_lists[key], label=lbl)\n plt.legend()\n if pt_xrange is not None:\n plt.xlim(pt_xrange)\n if pt_yrange is not None:\n plt.ylim(pt_yrange)\n plt.tight_layout()\n # plt.show(block=True)\n if fig_fmt is None:\n plt.show(block=True)\n else:\n plt.savefig(out_dir + '/' + out_stem + '_pval_high_rad.png')\n plt.close()\n\nprint('Successfully terminated. (' + time.strftime(\"%c\") + ')')", "\"\"\"\n\nTests module numpy_plus.\n\nCurrently tests trim_slice() only.\n\n# Author: Vladan Lucic (Max Planck Institute for Biochemistry)\n# $Id$\n\"\"\"\nfrom __future__ import unicode_literals\n\n__version__ = \"$Revision$\"\n\nfrom copy import copy, deepcopy\nimport unittest\n\nimport numpy\nimport numpy.testing as np_test \nimport scipy\n\nfrom pyto.util.numpy_plus import trim_slice\n\nclass TestNumpyPlus(np_test.TestCase):\n \"\"\"\n \"\"\"\n\n def test_trim_slice(self):\n \"\"\"\n Tests trim_slice()\n \"\"\"\n\n # inset inside\n result = trim_slice(slice_nd=[slice(1, 3), slice(2, 5)], \n shape=[4, 5])\n desired = ([slice(1, 3), slice(2, 5)], [slice(0, 2), slice(0, 3)])\n np_test.assert_equal(result, desired)\n\n # partially outside\n result = trim_slice(slice_nd=[slice(3, 6), slice(3, 6)], \n shape=[4, 5])\n desired = ((slice(3, 4), slice(3, 5)), (slice(0, 1), slice(0, 2)))\n np_test.assert_equal(result, desired)\n\n # partially outside, negative side\n result = trim_slice(slice_nd=[slice(-2, 1), slice(3, 6)], \n shape=[4, 5])\n desired = ((slice(0, 1), slice(3, 5)), (slice(2, 3), slice(0, 2)))\n np_test.assert_equal(result, desired)\n\n # completely outside\n result = trim_slice(slice_nd=[slice(2, 4), slice(6, 8)], \n shape=[4, 5])\n np_test.assert_equal(result[0] is None, True)\n np_test.assert_equal(result[1] is None, True)\n\n # slices supersed of shape\n result = trim_slice(slice_nd=[slice(-2, 6), slice(2, 5)], \n shape=[4, 5])\n desired = ((slice(0, 4), slice(2, 5)), (slice(2, 6), slice(0, 3)))\n np_test.assert_equal(result, desired)\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestNumpyPlus)\n unittest.TextTestRunner(verbosity=2).run(suite)\n", "\"\"\"\n\nTests module pyto.util.scipy_plus.\n\n# Author: Vladan Lucic (Max Planck Institute for Biochemistry)\n# $Id$\n\"\"\"\nfrom __future__ import unicode_literals\n\n__version__ = \"$Revision$\"\n\nimport unittest\n\nimport numpy\nimport numpy.testing as np_test \nimport scipy\n\nfrom pyto.util.scipy_plus import *\n#from ..scipy_plus import * # no relative import when this file run directly\n\n\nclass TestScipyPlus(np_test.TestCase):\n \"\"\"\n \"\"\"\n\n def setUp(self):\n \"\"\"\n \"\"\"\n pass\n\n def test_chisquare_2(self):\n \"\"\"\n Tests chisquare2()\n \"\"\"\n\n # Statistics for the biological sciences, pg 110\n chisq, p = chisquare_2(f_obs_1=numpy.array([20, 30]), \n f_obs_2=numpy.array([24, 26]),\n yates=True)\n np_test.assert_almost_equal(chisq, 0.364, decimal=2)\n np_test.assert_equal(p>0.25, True)\n np_test.assert_almost_equal(p, 0.546, decimal=3)\n \n # Statistics for the biological sciences, pg 111\n chisq, p = chisquare_2(f_obs_1=numpy.array([60, 32, 28]), \n f_obs_2=numpy.array([28, 17, 45]))\n np_test.assert_almost_equal(chisq, 16.23, decimal=2)\n np_test.assert_equal(p<0.005, True)\n np_test.assert_almost_equal(p, 0.0003, decimal=4)\n desired = scipy.stats.chi2.sf(chisq, 2)\n np_test.assert_almost_equal(p, desired, decimal=4)\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestScipyPlus)\n unittest.TextTestRunner(verbosity=2).run(suite)\n", "\"\"\"\nContains class Cleft for the analysis of a cleft-like region (a region\nbetween two roughly parallel boundaries).\n\n# Author: Vladan Lucic (Max Planck Institute for Biochemistry)\n# $Id$\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom builtins import zip\nfrom builtins import str\nfrom past.utils import old_div\n\n__version__ = \"$Revision$\"\n\n\nimport logging\n#from copy import copy, deepcopy\nimport numpy\nimport scipy\n\nfrom pyto.geometry.vector import Vector\nfrom pyto.geometry.affine_3d import Affine3D\nfrom pyto.geometry.coordinates import Coordinates\nfrom .segment import Segment\nfrom .grey import Grey\n\n\nclass Cleft(Segment):\n \"\"\"\n Important attributes:\n - data: (ndarray) labeled cleft and boundary regions\n - cleftId/bound1Id/bound2Id: ids of cleft / boundary 1 / boundary 2,\n each saved as an ndarray\n - ids: all of the above ids\n\n Methods:\n - makeLayers(): makes layers in the cleft and possibly over boundaries\n - getWidth(): calculates width and the orientation of the cleft\n - getBoundaryDistances(): for each boundary edge voxel, finds the position\n and the distance to closest voxel on the other boundary\n - parametrizeLabels(): puts a coordinate system on labels\n \n \"\"\"\n\n ###############################################################\n #\n # Initialization\n #\n ##############################################################\n\n def __init__(self, data, cleftId=[], bound1Id=[], bound2Id=[], copy=True, \n clean=False):\n \"\"\"\n Sets attributes from arguments.\n\n Each of the id args (cleftId, bound1Id, bound2Id) can be a single int\n or a list (array) in which cases a (boundary or cleft) is formed form \n all specified ids.\n\n Arguments:\n - data: ndarray with labeled cleft and boundary regions\n - bound1Id, bound2Id, cleftId: ids of boundaries 1, 2 and cleft\n - copy: flag indicating if data array is copied\n - clean: flag indicating if segmentss other than those specified\n by boundary and cleft ids are removed from tha data array\n \"\"\"\n\n # set ids\n self.setCleftIds(cleftId=cleftId, bound1Id=bound1Id, bound2Id=bound2Id)\n all_ids = numpy.concatenate([self.cleftId, self.bound1Id, \n self.bound2Id])\n\n # call super to set data and ids\n super(Cleft, self).__init__(data=data, copy=copy, ids=all_ids, \n clean=clean)\n\n def setCleftIds(self, cleftId, bound1Id, bound2Id):\n \"\"\"\n Sets boundary, cleft and all ids as attributes, in addition to \n whatever else super does.\n \"\"\"\n\n # convert args bound1Id, bound2Id and cleftId to ndarrays and save \n # as attributes\n all_ids = []\n for ids in [cleftId, bound1Id, bound2Id]: \n if isinstance(ids, int):\n all_ids.append(numpy.array([ids]))\n else:\n all_ids.append(numpy.asarray(ids))\n self.cleftId, self.bound1Id, self.bound2Id = all_ids\n\n # set self.ids and related\n super(Cleft, self).setIds(ids=all_ids)\n\n\n ###############################################################\n #\n # Geometry\n #\n ##############################################################\n\n def getWidth(self, mode='median', toBoundary=0, maxDistance=None):\n \"\"\"\n Calculates the width and the orientation of the cleft (direction of the \n width vector).\n\n The width is calculated by taking into account only the regions of \n the two boundaries that border the cleft region. First, min distance to \n the boundary specified by toBoundary is calculated for each\n element of a border region of the other boundary. Distance between \n boundaries is then obtained as the mean/median/min/max (depending on the\n arg mode) of the distances for each element. Finally, the cleft width \n is distance between boundaries - 1. For example, if boundaries touch\n exch other the distance between them is 1 and the cleft width is 0.\n\n If toBoundary=0, distances to both boundaries are calculated and the \n width is obtained from all those distances taken together.\n\n The distance vector is calculated in a similar way, except that \n distance vectors are calculated (instead of distances alone) and \n that the average vector is returned. I toBoundary is 1 or 2, average\n of the distance vectors to boundary 1 or 2 is returned. If toBoundary\n is 0, distance vectors are combined and then averaged. In any case,\n the distance vector is oriended from boundary 1 (self.bound1Id) to\n boundary 2 (self.bound2Id).\n\n If arg maxDistance is specified, only those elements of boundaries\n borders (boundary elemnts that touch the cleft) whose distance to the \n other boundary is not larger than maxDistance are taken into account.\n Note that arg MaxDistance here has different meaning from the one in\n Segment.makeLayersBetween().\n\n Argument:\n - mode: cleft width calculating mode, 'mean', 'median', 'min' or \n 'max' (actually can be any appropriate numpy function)\n - toBoundary: distances calculated to that boundary\n - maxDistance: max distance between boundaries\n\n Returns (width, width_vector) where:\n - width: cleft width calculated between boundary edges, that is if \n the boundaries touch each other the width is 0\n - width_vector: (..geometry.Vector) average distance vector\n \"\"\"\n\n # get distances between boundaries\n dis_to_1, pos_to_1, pos_2, dis_to_2, pos_to_2, pos_1 = \\\n self.getBoundaryDistances()\n\n # remove elements that are too far from the other boundary\n if maxDistance is not None:\n pos_to_1 = [single_ind_ar.compress(dis_to_1<=maxDistance) \n for single_ind_ar in pos_to_1]\n pos_2 = [single_ind_ar.compress(dis_to_1<=maxDistance) \n for single_ind_ar in pos_2]\n dis_to_1 = dis_to_1.compress(dis_to_1<=maxDistance)\n pos_to_2 = [single_ind_ar.compress(dis_to_2<=maxDistance) \n for single_ind_ar in pos_to_2]\n pos_1 = [single_ind_ar.compress(dis_to_2<=maxDistance) \n for single_ind_ar in pos_1]\n dis_to_2 = dis_to_2.compress(dis_to_2<=maxDistance)\n\n # calculate mean/median ... distance between boundaries\n if toBoundary == 0:\n dis_to = numpy.concatenate([dis_to_1, dis_to_2])\n elif toBoundary == 1:\n dis_to = dis_to_1\n elif toBoundary == 2:\n dis_to = dis_to_2\n else:\n raise ValueError(\"Argument toBoundary \", str(toBoundary), \n \"can be 0, 1 or 2.\")\n distance = getattr(numpy, mode)(dis_to)\n \n # generate distance vectors between boundary surface elements\n # and their closest elements on the other boundary\n if toBoundary == 0:\n vec1 = numpy.array(pos_2) - numpy.array(pos_to_1)\n vec2 = numpy.array(pos_to_2) - numpy.array(pos_1)\n vectors = numpy.concatenate([vec1, vec2], axis=-1)\n elif toBoundary == 1:\n vectors = numpy.array(pos_2) - numpy.array(pos_to_1) \n elif toBoundary == 2:\n vectors = numpy.array(pos_to_2) - numpy.array(pos_1)\n\n # average distance vector\n width_vector = vectors.mean(axis=1)\n width_vector = Vector(data=width_vector)\n\n return distance-1, width_vector\n\n def getBoundaryDistances(self):\n \"\"\"\n For each boundary element contacting cleft (boundary edge), finds the \n position of the closest element on the other boundary and calculates \n the distance between them. \n\n Uses the smallest inset of the data array to speed up the calculations.\n However, positions calculated are adjusted for self.inset, that is\n they are given in respect to the fully expanded self.data.\n\n Used to provide info to higher level methods that deal with distances \n between boundaries, such as self.getWidth().\n\n Return tuple containing the following ndarrays:\n - distance to boundary 1 from each element of the edge of boundary 2\n - positions of elements of boundary 1 found above\n - positions of edge elements of boundary 2 \n - distance to boundary 2 from each element of the edge of boundary 1\n - positions of elements of boundary 2 found above\n - positions of edge elements of boundary 1 \n The first (last) three are indexed in the same way, that is according \n to the the boundary 2 (boundary 1) edge elements. Positions are \n returned in the form numpy uses for coordinates, that is as a list\n where element i contains array of coordinates along axis i.\n \"\"\"\n\n # inset is extended by this amount to prevent segments touching \n # image edges\n extend_inset = 1\n\n # find inset that contains boundaries and cleft\n inset = self.findInset(ids=self.ids, extend=extend_inset, mode='abs')\n data_inset = self.makeInset(\n ids=self.ids, extend=extend_inset, update=False)\n\n # make cleft mask\n cleft_mask = numpy.zeros(shape=data_inset.shape, dtype=bool)\n for id_ in self.cleftId:\n cleft_mask[data_inset==id_] = True\n\n # extract boundary surfaces that border cleft\n dilated = scipy.ndimage.binary_dilation(input=cleft_mask)\n bound_surf_1 = numpy.zeros(shape=data_inset.shape, dtype=bool)\n for id_ in self.bound1Id:\n bound_surf_1[dilated & (data_inset==id_)] = True\n bound_surf_2 = numpy.zeros(shape=data_inset.shape, dtype=bool)\n for id_ in self.bound2Id:\n bound_surf_2[dilated & (data_inset==id_)] = True\n\n # calculate min distances of all elements of boundary 2 to boundary 1\n if (~bound_surf_1 > 0).all(): # workaround for scipy bug 1089\n raise ValueError(\"Can't calculate distance_function \" +\n \"(no background)\")\n else:\n distance_to_1, position_to_1 = \\\n scipy.ndimage.distance_transform_edt(~bound_surf_1, \n return_indices=True)\n dis_to_1 = distance_to_1[bound_surf_2] \n pos_to_1 = [pos[bound_surf_2] for pos in position_to_1] \n pos_2 = bound_surf_2.nonzero()\n\n # calculate min distances of all elements of boundary 1 to boundary 2\n if (~bound_surf_2 > 0).all(): # workaround for scipy bug 1089\n raise ValueError(\"Can't calculate distance_function \",\n \"(no background)\")\n else:\n distance_to_2, position_to_2 = \\\n scipy.ndimage.distance_transform_edt(~bound_surf_2, \n return_indices=True)\n\n dis_to_2 = distance_to_2[bound_surf_1] \n pos_to_2 = [pos[bound_surf_1] for pos in position_to_2] \n pos_1 = bound_surf_1.nonzero()\n\n # correct coordintates for inset\n pos_to_1 = [pos + ins.start for pos, ins in zip(pos_to_1, inset)]\n pos_2 = [pos + ins.start for pos, ins in zip(pos_2, inset)]\n pos_to_2 = [pos + ins.start for pos, ins in zip(pos_to_2, inset)]\n pos_1 = [pos + ins.start for pos, ins in zip(pos_1, inset)]\n\n return dis_to_1, pos_to_1, pos_2, dis_to_2, pos_to_2, pos_1\n\n\n ########################################################\n #\n # Layers\n #\n #########################################################\n\n def makeLayers(self, nLayers=None, width=None, widthMode='median', \n maxDistance=None, fill=True, nExtraLayers=0, \n extra_1=None, extra_2=None, offset=0.5):\n \"\"\"\n Makes cleft and boundary layers.\n\n Attributes self.bound1Id, self.bound2Id and self.cleftId (defining \n boundaries and the cleft region, respectively) need to be set. Cleft\n layers can be formed on (is a subset of) the cleft region only, while\n the boundary layers are formed on boundaries and extra regions \n (subset again).\n\n If arg width is None, the cleft width is calculated using \n self.getWidth(toBoundary=0). In short, for each element of boundary \n borders (elements of boundaries that contact the cleft region) the \n shortest distance to the other boundary is calculated. The distances\n greater than arg maxDistance are not taken into account, The \n mean/median/min/max (according to the argument widthMode) of these \n values -1 is then cleft width calculated edge-to-edge. Strictly \n speaking, subtracting 1 is valid for relatively flat cleft. The only \n reason for specifying arg width as an argument is to avoid computing \n it twice. \n\n Number of layers is the rounded value of the cleft width.\n\n The layers are then made using Segment.makeLayersBetween() (see for more\n detailed info). If there is no extra layers (nExtraLayers=0) layers of\n approximatelly same thickness are positioned parallel to the boundary \n borders. Specifically, layers are calculated as:\n\n layer_no = floor{(d_1 - offset) * nLayers / (d_1 + d_2 - 2*offset) + 1}\n\n where d_1 and d_2 are the shortest distances to borders of boundary 1 \n and 2. Layers are made only in the cleft region. \n\n If arg maxDistance is specified, the cleft region is restricted to \n those elements that have sum of distances to both boundaries \n <= maxDistance. If arg fill is True the holes created by the \n restriction to maxDistance are filled.\n\n Number of layers is either given by arg nLayers (in which case layer\n thcikness is cleft_width / nLayers) or it equals the cleft width \n (thickness = 1).\n\n In case nExtraLayers is > 0, extra layers are formed in addition to the\n cleft layers (explained above). The extra layers are formed on the\n boundaries and on the extra regions (args extra_1 and extra_2). The\n extra layers are formed based on their euclidean distance to the closest\n cleft layer, and they have the same thickness as the cleft layers. \n This is done using Segment.makeLayersFrom() method. The\n additional layers formed over the first boundary and the first extra\n region are numbered from 1 to nExtraLayers, the ids of the cleft layers\n are shifted by nExtraLayers and the layers formed over the second\n boundary and the second extra region go from \n nLayers_nExtraLayers+1 to nLayers+2*nExtraLayers.\n\n The layers are returned as a Segment object, where layers.data is an\n array that contains all layers. Layers.data can have smaller shape than \n self.data, and layers.offset is set appropriatelly. To be precise, \n layers.data is just big enough to contain all layers as well as regions\n occupied by boundaries.\n\n Arguments:\n - nLayers: number of layers, in None 1-pixel thick layers are formed\n - width: cleft width, calculated if None\n - widthMode: cleft width calculation mode ('mean', 'median', 'min', \n 'max', or any appropriate numpy function), used only if width is None\n - maxDistance: max allowed sum of (minimal) distances to the two \n boundaries, if None no limit is imposed\n - fill: flag indicating if holes created by maxDistance procedure\n are filled (used only if maxDistance is not None)\n - nExtraLayers: (int) number of additional layers formed on each side\n of the cleft\n - extra_1, extra_2: (int, or a list of int's) ids of extra regions 1 \n and 2 respectivly\n - offset: numerical parameter that compensates for the disccrete\n nature of distances, should be 0.5\n \n Returns: layers, width\n - layers: (Segment) layers\n - width: cleft width\n \"\"\"\n\n # find cleft width if needed\n if width is None:\n width, width_vector = self.getWidth(mode=widthMode, \n maxDistance=maxDistance)\n\n # make layers\n cleft_id_list = list(self.cleftId)\n layers, width_other = self.makeLayersBetween(\n bound_1=self.bound1Id, bound_2=self.bound2Id, mask=cleft_id_list, \n nLayers=nLayers, width=width, offset=offset, \n maxDistance=maxDistance, fill=fill, \n nExtraLayers=nExtraLayers, extra_1=extra_1, extra_2=extra_2)\n \n return layers, width\n\n def adjustToRegions(self, regions, ids=None, value=0):\n \"\"\"\n Adjusts self.data to correspond to regions.data.\n\n Sets elements of self.data that have one of the specified ids and that\n correspond at 0-elements of arg regions to arg value.\n\n If arg ids is None, any element of self.data can be set to arg value. \n\n Arguments:\n - regions: (Segment) regions\n - ids: list of ids of this instance where self.data can be adjusted\n - value: value to be adjusted to\n\n Modifies self.data.\n \"\"\"\n\n # position regions to this instance\n reg_data = regions.useInset(inset=self.inset, mode='abs', \n expand=True, update=False)\n\n # set elements\n if ids is None:\n self.data[reg_data==0] = value\n else:\n for id_ in ids:\n self.data[(reg_data==0) & (self.data==id_)] = value\n\n\n ########################################################\n #\n # Columns and layers parametrization\n #\n #########################################################\n\n def makeColumns(\n self, bins, ids=None, system='radial', normalize=False, \n originMode='one', startId=None, metric='euclidean', connectivity=1, \n rimId=0, rimLocation='out', rimConnectivity=1):\n \"\"\"\n Segments cleft to columns, that is segments perpendicular to cleft \n layers. \n\n The attribute data of this instance needs to contain layers, preferably \n of thickness 1. This can be done using makeLayers(nLayers=None).\n\n First, the layers are parametrized, that is layer centers are determined\n (see parametrizeLayers() and pickCenter()) and then a coordinate system\n with origin at the layer center is placed on each of the layers \n according to args system and metric (see self.parametrizeLayers() for \n details). \n\n If arg normalize is False, each layer element is assigned a value\n that equals its distance to the center. Alternatively, if normalize\n is True and a radial distance needs to be calculated (system 'radial' or\n 'polar'), radial values assigned to layer elements are caluclated as:\n\n distance_to_center / (distance_to_center + min_distance_to_rim)\n\n where min_distance_to_rim is the shortest distance to rim which \n surrounds layers. Consequently, center gets value of 0 and layer\n elements that contact the rim are assigned value 1. \n\n Then, each layer element is assigned to a segment based on its\n parametrization and arg bins (see Grey.labelByBins() for details). The\n arg bins can contain one set of binning values for each of the \n coordinates of the specified coordinate system. If bins are not given \n for all coordinates, those at the end are ignored. For example, given:\n\n bin=[[0,2,4], [-pi, 0, pi]], system='polar'\n\n in 3D, rho coordinate is binned according to [0,2,4], phi according\n to [-pi, 0, pi] and z is disregarded (the order of coordinates in the\n polar system is: rho, phi, z).\n\n Lower bin limits are inclsive, while the upper are exclusive except for\n the last one which is inclusive.\n\n Non-asigned array elements are set to 0. The resulting segmented image \n is converted to a Segmentation object that has the same positioning \n as this instance.\n\n For example, if self.data is:\n\n [[5, 5, 5, 5, 5, 5],\n [5, 1, 1, 1, 5, 5],\n [5, 1, 1, 1, 5, 5],\n [5, 1, 1, 1, 5, 5], \n [5, 1, 1, 1, 5, 5],\n [5, 1, 1, 1, 5, 5],\n [5, 1, 1, 1, 5, 5],\n [5, 1, 1, 1, 5, 5],\n [5, 5, 5, 5, 5, 5]])\n \n self.makeColumns(\n ids=[1], system='radial', normalize=False, startId=1, \n metric='euclidean', connectivity=1, rimId=5, bins=[0, 1, 2, 3, 4])\n\n will return:\n\n [[0, 0, 0, 0, 0, 0],\n [0, 4, 4, 4, 0, 0],\n [0, 3, 3, 3, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 2, 1, 2, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 3, 3, 3, 0, 0],\n [0, 4, 4, 4, 0, 0],\n [0, 0, 0, 0, 0, 0]])\n\n while: \n\n self.makeColumns(\n ids=[1], system='radial', normalize=False, startId=1, \n metric='euclidean', connectivity=1, rimId=5, bins=[0, 2, 4])\n\n will return:\n\n [[0, 0, 0, 0, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 2, 2, 2, 0, 0],\n [0, 0, 0, 0, 0, 0]])\n\n Note that there might be a global ambiquity in the parametrization. \n Namely, because there is an ambiguity in the direction of the best\n fit line generated by scipy.linalg.svd(), cartesian axis directions\n and the sign of the polar angle are ambiguous.\n\n Arguments:\n - bins: binning values\n - ids: ids of layer where columns are made\n - system: coordinate syatem, can be 'radial', 'cartesian' or 'polar'\n - normalize: flag indicating if radial distance is normalized\n - metric: distance metric, can be 'euclidean', 'geodesic' or\n 'euclidean-geodesic'\n - connectivity: connectivity of the structure element (as in\n scipy.ndimage.generate_binary_structure() where rank is self.ndim)\n for geodesic distance calculation (int). Not used for euclidean.\n - originMode: determines how centers are determined, currently only \n 'one' (see self.pickLayerCenters())\n - startId: layer where the center is first determined, used in mode \n 'one', None means start from the middle (see self.pickLayerCenters())\n - rimId: id or rim region\n - rimLocation: specifies if the rim is just outside of layers\n ('out') or on the layer boundary ('in')\n - rimConnectivity: (int) connectivity of the structure element\n that defines contact elements between a layer and the rim region.\n\n Returns column-segmented cleft as an instance of Segment where:\n - column.data: (ndarray) labeled array\n - column,binIds: (dict) where each id is a key and the corresponding \n value is a list of lower and uper bin limits for each binning.\n \"\"\"\n\n # get layer ids\n if ids is None:\n ids = self.cleftId\n\n # parametrize layers\n coordinates = self.parametrizeLayers(\n ids=ids, system=system, normalize=normalize, \n originMode=originMode, startId=startId, metric=metric, \n connectivity=connectivity, rimId=rimId, \n rimLocation=rimLocation, rimConnectivity=rimConnectivity, \n noDistance=-1)\n\n # make labels\n col_data, bin_ids = Grey.labelByBins(values=coordinates, bins=bins)\n\n # make self.column object and set as an attribute of this object\n columns = Segment(data=col_data, ids=list(bin_ids.keys()), copy=False)\n columns.copyPositioning(self, saveFull=False)\n columns.binIds = bin_ids\n\n return columns\n\n def parametrizeLayers(\n self, ids, system='radial', normalize=False, originMode='one', \n startId=None, metric='euclidean', connectivity=1, rimId=0, \n rimLocation='out', rimConnectivity=1, noDistance=-1):\n \"\"\"\n Parametrizes layers, that is puts a coordinate system on layer-like\n segments. As a result, each element of self.data that belongs to one of \n the layers (specified by arg ids) is associated with one or more\n coordinates of the new system.\n\n Radial coordinate is calculated as the distance of each layer element\n to the origin of that layer, using the specified distance metric. The \n origin of a layer is an element that has the largest distance to the \n rim surrounding the layer. In case there's more than one element having \n the largest distance, the element closest to the layer center of mass \n is chosen. See self.elementDistanceToRim() and self.pickLayerCenters()\n for the origin determination and self.distanceFromOrigin() for the\n distance from origin.\n\n If arg normalize is False, each layer element is assigned a value\n that equals its distance to the center. Alternatively, if normalize\n is True, the values assigned to layer elements is caluclated as:\n\n distance_to_center / (distance_to_center + min_distance_to_rim)\n\n where min_distance_to_rim is the shortest distance to rim which \n surrounds layers. Consequently, center gets value of 0 and layer\n elements that contact the rim are assigned value 1. \n\n In 2D and >3D only the radial parametrization is possible.\n\n To calculate cartesian coordinates in 3D the layers are rotated so that\n the vector perpendicular to layers (the best fit line for all\n layer origins) is aligned with the z-axis (theta=0), and that that the \n direction towards the lowest z-postions of the original layers is \n aligned with the x-axis (phi=0). The origin of this rotation is the \n layer center, so this rotation is repeated for each layer separately. \n The coordinates of the rotated cleft are taken as the cartesian \n parametrization of the cleft. \n\n If the metric is euclidean for 3D cartesian system, the \n coordinates of the rotated cleft are the calculated coordinates. In\n addition, z coordinate is calculated in repect to the layer center\n (just like x and y). Also, it is not defined if layer ids increase \n along positive or negative z-axis.\n\n Alternatively, if the metric is geodesic for 3D cartesian system,\n first the polar coordinate phi is calculated and the x and y \n coordinates are calculated from the radial and phi coordinate. In\n this case z coordinate is not calculated (nor returned).\n\n Layers of this instance should be thin (of thickness 1 or so), so that\n center of each layer borders layers on both sides.\n\n Polar coordinates can be used in 3D. The angle (phi) is calculated from\n the cartesian coordinates (x and y). The radial coordinate calculated as\n explained above and the z coordinate from the cartesian coordinates\n complete the system.\n \n Note that there might be a global ambiquity in the parametrization. \n Namely, because there is an ambiguity in the direction of the best\n fit line generated by scipy.linalg.svd(), cartesian axis directions\n and the sign of the polar angle are ambiguous.\n\n Arguments:\n - ids: layer ids\n - system: coordinate syatem, can be 'radial', 'cartesian' or 'polar'\n - normalize: flag indicating if radial distance is normalized\n - metric: distance metric, can be 'euclidean', 'geodesic' or\n 'euclidean-geodesic'\n - connectivity: connectivity of the structure element (as in\n scipy.ndimage.generate_binary_structure() where rank is self.ndim)\n for geodesic distance calculation (int). Not used for euclidean.\n - originMode: determines how centers are determined, currently only \n 'one' (see self.pickLayerCenters())\n - startId: layer where the center is first determined, used in mode \n 'one', None means start from the middle (see self.pickLayerCenters())\n - rimId: id or rim region\n - rimLocation: specifies if the rim is just outside of layers\n ('out') or on the layer boundary ('in')\n - rimConnectivity: (int) connectivity of the structure element\n that defines contact elements between a layer and the rim region.\n - noDistance: value used for array elements where the distance is\n not calculated\n\n Returns: masked ndarray where axis 0 denotes a coordinate and the other\n dimensions are the same as those of self.data. Elements outside the\n layers are masked. The coordinates returned depend on the coordinate \n system (arg system):\n - radial: rho\n - cartesian (3D only): [x, y, z]\n - polar (3D only): [rho, phi, z]\n \"\"\"\n\n # set mask containing all segments from ids\n ids_mask = numpy.zeros(shape=self.data.shape, dtype=bool)\n for id_ in ids:\n ids_mask[self.data==id_] = True\n\n # distance to rim\n to_rim = self.elementDistanceToRim(\n ids=ids, metric=metric, connectivity=connectivity, rimId=rimId,\n rimLocation=rimLocation, rimConnectivity=rimConnectivity, \n noDistance=noDistance)\n\n # origin based on max distance to rim\n centers = self.pickLayerCenters(ids=ids, distance=to_rim, \n mode=originMode, startId=startId)\n\n # radial parametrization as distance from origin\n if not ((system == 'cartesian') and (metric == 'euclidean')):\n rho = self.distanceFromOrigin(\n origins=centers, metric=metric, connectivity=connectivity, \n noDistance=noDistance)\n\n # normalize if needed\n if normalize:\n total = rho + to_rim\n rho = numpy.where(total > 0, rho / total.astype(float), 0)\n\n # wrap up the radial parametrization in a masked array\n if (system == 'radial') or (self.ndim == 2):\n #rho = numpy.expand_dims(rho, axis=0)\n rho = numpy.ma.masked_array(rho, mask=~ids_mask, \n fill_value=noDistance)\n return rho\n\n elif self.ndim == 3:\n\n # cartesian parametrization (based on Euclidean metric)\n if (system == 'polar') or (system == 'cartesian'):\n\n # make best fit line for layer centers\n cent = Vector(list(centers.values()))\n cm, vector = cent.bestFitLine()\n \n # extract one point and angles for the centers line\n #origin = numpy.rint(cm.data).astype(int)\n theta = vector.theta\n phi = vector.phi\n\n # make a rotation that brings the cleft axis to the z axis\n # and the steepest z-descent to x-axis (phi=0)\n rot_phi = Affine3D(alpha=-phi, axis='z')\n rot_theta = Affine3D(alpha=-theta, axis='y')\n rot = Affine3D.compose(rot_theta, rot_phi)\n\n # get cartesian parametrization for Euclidean metric\n for id_, origin in list(centers.items()): \n xyz_id = Coordinates.transform(\n shape=self.data.shape, affine=rot, \n origin=origin, center=True)\n id_mask = numpy.array(3 * [self.data == id_])\n try:\n xyz_euc[id_mask] = xyz_id[id_mask]\n except NameError:\n xyz_euc = xyz_id\n\n if (system == 'cartesian') and (metric == 'euclidean'):\n if normalize:\n x_max = numpy.abs(xyz_euc[0]).max()\n y_max = numpy.abs(xyz_euc[1]).max()\n xyz_euc[0] = xyz_euc[0] / float(x_max)\n xyz_euc[1] = xyz_euc[1] / float(y_max)\n xyz = numpy.ma.masked_array(\n xyz_euc, mask=3 * [~ids_mask], fill_value=noDistance)\n return xyz\n \n # get phi from cartesian with Euclid\n phi = numpy.arctan2(xyz_euc[1], xyz_euc[0])\n\n if system == 'polar':\n\n # rho from radial, z from cartesian and mask\n rho_phi_z = numpy.zeros(shape=xyz_euc.shape)\n rho_phi_z[0] = rho\n rho_phi_z[1] = phi\n rho_phi_z[2] = xyz_euc[2]\n rho_phi_z = numpy.ma.masked_array(\n rho_phi_z, mask=3 * [~ids_mask], fill_value=noDistance)\n\n return rho_phi_z\n\n elif system == 'cartesian':\n\n # get xy from rho and phi\n shape = [2] + list(self.data.shape)\n xy = numpy.zeros(shape=shape)\n xy[0] = rho * numpy.cos(phi)\n xy[1] = rho * numpy.sin(phi)\n xy = numpy.ma.masked_array(\n xy, mask=2 * [~ids_mask], fill_value=noDistance)\n\n return xy\n\n else: \n raise ValueError(\n \"Sorry, only 'radial' coordinate can be calculated for Ndim\"\n + \"other than 2 or 3.\") \n\n def pickCenter(self, id_, distance, fromPosition=None):\n \"\"\"\n Returns coordinates of the center of segment specified by arg id_.\n Center is defined as the point that has the highest distance (to the \n rim of the segment). Distances of all points are specified by \n arg distance.\n\n If arg fromPosition is None, the position of global maximum of the\n specified segment is returned. \n\n Alternatively, if arg fromPosition is a coordinate, the position of \n maximum on the specified segment within the neighborhood of the arg \n fromPosition (both rank and connectivity of the structure element are \n self.ndim). If no element with the specified id exists in the \n neighborhood of fromPosition, None is returned.\n\n If more than one max position exist, the one closest to the center of\n mass of the whole segment (having id_) is chosen. If multiple (min\n position to cm) exist, one of them is chosen randomly (calculated by \n scipy.ndimage.minimum_position).\n\n Arguments:\n - id_: segment id\n - distance: (ndarray of the same shape as self.data) distances\n - fromPosition: (1d ndarray) coordinates of a point in the \n neighborhood of or on the specified segment\n\n Returns: (1d ndarray) coordinates of max position\n \"\"\"\n\n # find max distance position(s)\n if fromPosition is None:\n\n # in the whole segment\n max_dist = scipy.ndimage.maximum(\n distance, labels=self.data, index=id_)\n max_indices = numpy.nonzero((distance==max_dist) & (self.data==id_))\n\n else:\n \n # find neighborhood of fromPosition on the id_\n se = scipy.ndimage.generate_binary_structure(self.ndim, self.ndim)\n hood = numpy.zeros(shape=self.data.shape, dtype=bool)\n hood[tuple(fromPosition)] = True\n hood = scipy.ndimage.binary_dilation(hood, structure=se)\n hood[self.data != id_] = False\n if not hood.any():\n return None\n\n # max distance(s) in the hood\n #center_pos = scipy.ndimage.maximum_position(distance, labels=hood)\n max_dist = scipy.ndimage.maximum(distance, labels=hood)\n max_indices = numpy.nonzero((distance==max_dist) & hood)\n\n # extract one max distance position\n if len(max_indices[0]) > 1:\n\n # more than one max, pick the closest to the cm\n max_indices = numpy.asarray(max_indices)\n cm = scipy.ndimage.center_of_mass(self.data==id_)\n cm = numpy.expand_dims(numpy.asarray(cm), axis=-1)\n sq_diff = numpy.square(max_indices - cm)\n cm_dist_sq = numpy.add.reduce(sq_diff, axis=0)\n center_index = scipy.ndimage.minimum_position(cm_dist_sq)[0]\n center_pos = max_indices[:, center_index]\n\n else:\n center_pos = numpy.array([x[0] for x in max_indices])\n\n return numpy.asarray(center_pos)\n\n def pickLayerCenters(self, ids, distance, mode='one', startId=None,\n notFound='previous'):\n \"\"\"\n Returns coordinates of 'centers'of all segments specified by arg ids.\n\n If arg mode is 'one', it starts by finding the max position (center) \n on the distance array (arg distance) on the segment specified by arg\n startId. Afterwards, the center determination proceeds to neighboring \n segments according to the positioning of ids in arg ids, in both \n ascending (to the right) and descending (to the left) order. The \n center of a next layer is determined as the max distance on the region\n of the next layer that is within the neighborhood of the previous \n center. The neighborhood of an element is defined as all elements\n that have at least a vertex in common. If no layer element is found \n within the neighborhood, the center of that layer is set to None \n (arg notFound is None) or to the previous layer center (arg notFound\n is 'previous').\n\n It is necessary that segments are organized as thin layers,\n so that a center of each layer always lies in a neighborhood of the \n layers that are next to it. Layers of thickness 1 most likely \n satisfy this condition. \n\n Max positions are calculated by self.pickCenter, that in turn calls\n scipy.ndimage.maximum_position, which returns only one value if \n multiple max points exist.\n\n Arguments:\n - id_: segment id\n - distance: (ndarray of the same shape as self.data) distances\n - mode: determines how centers are determined, currently only 'one'\n - startId: Segment layer where the center is first determined, \n used in mode 'one', None means start from the middle\n - notFound: determines the returned value for layers whose\n center wasn't found\n\n Returns: (dict) of coordinates, where keys are ids and values are \n (1d ndarray) coordinates of centers, or None if the center was not \n found.\n \"\"\"\n\n centers = {}\n if mode == 'one':\n\n # start id\n if startId is None:\n startId = ids[int(old_div(len(ids), 2))] \n\n # find start center\n start_center = self.pickCenter(id_=startId, distance=distance)\n centers[startId] = start_center\n\n # make ascending and descending sequences\n ids = numpy.asarray(ids)\n index = (ids == startId).nonzero()[0][0]\n ascend = ids[index+1:]\n if index == 0:\n descend = numpy.array([])\n else:\n descend = ids[slice(index-1, None, -1)]\n\n # acsend and descend part\n for id_range in (ascend, descend):\n last_center = start_center\n for id_ in id_range:\n curr_center = self.pickCenter(id_=id_, distance=distance, \n fromPosition=last_center)\n if curr_center is not None:\n centers[id_] = curr_center\n last_center = curr_center\n else:\n if notFound is None:\n centers[id_] = curr_center\n elif notFound == 'previous':\n centers[id_] = last_center\n else:\n raise ValueError(\n \"Arg notFound: \" + notFound + \"was not \"\n + \"understood. Valid values are None and \"\n + \"'previous'.\")\n\n else:\n raise ValueError(\n \"Argument mode: \" + mode + \" not understood.\"\n + \" Only 'one' is currently implemented.\")\n\n return centers\n \n\n ########################################################\n #\n # Input / output\n #\n #########################################################\n\n @classmethod\n def read(cls, cleftId, bound1Id, bound2Id, file, clean=True, \n byteOrder=None, dataType=None, arrayOrder=None, shape=None):\n \"\"\"\n Reads segmented image (label filed) from a file and sets required ids.\n\n Each of the id args (cleftId, bound1Id, bound2Id) can be a single int\n or a list (array) in which cases a (boundary or cleft) is formed form \n all specified ids.\n\n If file is in em or mrc format (file extension em or mrc) only the file\n argument is needed. If the file is in the raw data format (file\n extension raw) all arguments are required.\n\n Arguments:\n - bound1Id, bound2Id, cleftId: ids of boundaries 1, 2 and cleft\n - file: file name\n - clean: if true, only the segments corresponding to ids are kept\n - byteOrder: '<' (little-endian), '>' (big-endian)\n - dataType: any of the numpy types, e.g.: 'int8', 'int16', 'int32',\n 'float32', 'float64'\n - arrayOrder: 'C' (z-axis fastest), or 'F' (x-axis fastest)\n - shape: (x_dim, y_dim, z_dim)\n\n Returns:\n - instance of Segment\n \"\"\"\n\n # read file\n from pyto.io.image_io import ImageIO as ImageIO\n fi = ImageIO()\n fi.read(file=file, byteOrder=byteOrder, dataType=dataType, \n arrayOrder=arrayOrder, shape=shape)\n\n # make new instance\n cleft = cls(data=fi.data, cleftId=cleftId, bound1Id=bound1Id, \n bound2Id=bound2Id, copy=False, clean=clean)\n\n return cleft\n\n \n", "\"\"\"\n\n Find columns on synapse tomograms (ListTomograms) and measure their statistics.\n Files for columns visualization in VTK format.\n\n Input: - 3 STAR files (layers) with the ListTomoParticles pickles\n\n Output: - Plots by tomograms and globaly:\n + Number of columns\n + Columns density\n - Visualization file:\n + vtkPolyData objects for each synapse with the columns\n\n\"\"\"\n\n################# Package import\n\nimport os\nimport copy\nimport csv\nimport numpy as np\nimport sys\nimport time\nfrom pyorg import pexceptions, sub, disperse_io, surf\nfrom pyorg.globals import unpickle_obj, clean_dir\nfrom pyorg.surf.model import ModelCSRV\nfrom pyorg.surf import ColumnsFinder\nfrom matplotlib import pyplot as plt, rcParams\nimport seaborn as sns\nimport pandas as pd\ntry:\n import pickle as pickle\nexcept ImportError:\n import pickle\n\n###### Global variables\n\n__author__ = 'Antonio Martinez-Sanchez'\n\nBAR_WIDTH = .40\n\nrcParams['axes.labelsize'] = 14\nrcParams['xtick.labelsize'] = 14\nrcParams['ytick.labelsize'] = 14\nrcParams['patch.linewidth'] = 2\n\n########################################################################################\n# PARAMETERS\n########################################################################################\n\nROOT_PATH = '/fs/pool/pool-lucic2/antonio/workspace/psd_an/ex/syn/sub/relion/fils'\n\n# Input STAR file\nin_star_1 = ROOT_PATH + '/ves_40/ltomos_tether/ves_40_cleft_premb_mask_ltomos.star' # '/ves_40/ltomos_tether_lap/ves_40_cleft_premb_mask_lap_ltomos.star_ltomos.star' # '/ves_40/ltomos_lap/lap_ltomos.star' # '/ves_40/ltomos_premb_mask/premb_mask_ltomos.star'\nkey_1 = 'tether'\nin_star_2 = ROOT_PATH + '/pre/ref_nomb_1_clean/ltomos_pre_premb_gather_mask/pre_premb_gather_mask_ltomos.star' # '/pre/ref_nomb_1_clean/ltomos_clst_flt_high_lap/clst_flt_high_lap_ltomos.star' # '/pre/ref_nomb_1_clean/ltomos_pre_premb_ABC/pre_premb_ABC_ltomos.star' # '/pre/ref_nomb_1_clean/ltomos_pre_premb_mask_lap/pre_premb_mask_lap_ltomos.star'\nkey_2 = 'pre'\nin_star_3 = ROOT_PATH + '/pst/nrt/ltomos_k4_gather_premb_mask/k4_gather_premb_mask_ltomos.star' # '/pst/nrt/ltomos_clst_flt_high_lap/clst_flt_high_lap_ltomos.star' # '/pst/ampar_vs_nmdar/org/ltomos/ltomos_ampar_nmdar_premb_mask/ampar_nmdar_premb_gather_mask_ltomos.star' # '/pst/nrt/k2_ABC/ltomos_k2_premb_ABC/k2_premb_ABC_ltomos.star' # '/pst/nrt/ltomos_k2_premb_mask/k2_premb_mask_ltomos.star' # '/pst/nrt/ltomos_pst_premb_mask_lap/pst_premb_mask_lap_ltomos.star'\nkey_3 = 'pst'\nin_tethers_csv = ROOT_PATH + '/pre/ref_nomb_1_clean/py_scripts/syn_num_tethers.csv'\nin_wspace = None # ROOT_PATH + '/pst/ampar_vs_nmdar/org/col/col_gather/col_2_sim_20_maxd_10_nn2_1_nn3_1_wspace.pkl'\n\n# Output directory\nout_dir = ROOT_PATH + '/pst/ampar_vs_nmdar/org/col/col_gather'\nout_stem = 'col_3_sim_20_maxd_10_nn2_1_nn3_1' # ''uni_sph_4_60_5'\n\n# Pre-processing variables\npre_ssup = 5 #nm\npre_min_parts = 1\n\n# Analysis variables\nana_res = 0.684 # nm/voxel\nana_max_dist = 10 # nm\nana_nn_2 = 1\nana_nn_3 = 1\n\n# P-value computation settings\n# Simulation model (currently only CSRV)\np_nsims = 20 # 200\np_per = 5 # %\n\n# AP clustering settings\ndo_ap_1, do_ap_2, do_ap_3 = False, False, False\nap_damp = 0.5\nap_max_iter = 20000\nap_conv_iter = 15\nap_pref = -1000\nap_c_rad = 5\n\n# Figure saving options\nfig_fmt = '.png' # if None they showed instead\nfig_weight_tet = True # In categories plotting tomograms are weigthed by the number of tethers\n\n# Plotting options\n\n# Ctrl vs Stim tomograms\nctrl_stems = ('11_2', '11_5', '11_6', '11_9', '14_9', '14_17', '14_18', '14_19', '14_20', '14_22', '14_24', '14_25')\nstim_stems = ('13_1', '13_3', '14_14', '14_15', '14_26', '14_27', '14_28', '14_32', '14_33', '15_7', '15_8', '15_12')\n\n########################################################################################\n# MAIN ROUTINE\n########################################################################################\n\n###### Additional functionality\n\n# Computes IC from a matrix of measurements (n_arrays, array_samples)\ndef compute_ic(per, sims):\n if len(sims.shape) == 1:\n return sims, sims, sims\n ic_low = np.percentile(sims, per, axis=0, interpolation='linear')\n ic_med = np.percentile(sims, 50, axis=0, interpolation='linear')\n ic_high = np.percentile(sims, 100 - per, axis=0, interpolation='linear')\n return ic_low, ic_med, ic_high\n\n# Compute the p-value for a single scalar in an array with the distribution\ndef compute_pval(val, sim, slope='high'):\n if slope == 'high':\n return float((val >= sim).sum()) / float(len(sim))\n else:\n return float((val >= sim).sum()) / float(len(sim))\n\n# Computes pvalue from a matrix of simulations (n_arrays, array_samples)\ndef compute_pvals(exp_med, sims):\n n_sims = float(sims.shape[0])\n p_vals = np.zeros(shape=exp_med.shape, dtype=np.float32)\n for i, exp in enumerate(exp_med):\n sim_slice = sims[:, i]\n p_vals[i] = float((exp >= sim_slice).sum()) / n_sims\n return p_vals\n\n# Check if a set of particles (rows) are aligned from the number of neighbours\ndef are_aligned(neighs, mask):\n aligns = np.zeros(shape=len(neighs), dtype=np.bool)\n for i, p_neigh in enumerate(neighs):\n if ((p_neigh[mask]>0).sum()) > 0:\n aligns[i] = True\n return aligns\n\n# Units conversion\nana_max_dist_v = ana_max_dist / ana_res\n\n########## Print initial message\n\nprint('Second order analysis for colocalization to ListTomoParticles by tomograms.')\nprint('\\tAuthor: ' + __author__)\nprint('\\tDate: ' + time.strftime(\"%c\") + '\\n')\nprint('Options:')\nprint('\\tOutput directory: ' + str(out_dir))\nprint('\\tOuput stem: ' + str(out_stem))\nprint('\\tInput analysis STAR file 1: ' + str(in_star_1))\nprint('\\t\\t-Key: ' + key_1)\nprint('\\tInput analysis STAR file 2: ' + str(in_star_2))\nprint('\\t\\t-Key: ' + key_2)\nprint('\\tInput analysis STAR file 3: ' + str(in_star_3))\nprint('\\t\\t-Key: ' + key_3)\nif in_wspace is not None:\n print('\\tLoad workspace from: ' + in_wspace)\nelse:\n print('\\tPre-processing: ')\n if pre_ssup is not None:\n print('\\t\\t-Scale supression: ' + str(pre_ssup) + ' nm')\nprint('\\tOrganization analysis settings: ')\nprint('\\t\\t-Data resolution: ' + str(ana_res) + ' nm/vx ')\nprint('\\t\\t-Column radius: ' + str(ana_max_dist) + ' nm')\nprint('\\t\\t-Column radius: ' + str(ana_max_dist_v) + ' vx')\nprint('\\t\\t-Number of aligned particles in layer 2: ' + str(ana_nn_2))\nprint('\\t\\t-Number of aligned particles in layer 3: ' + str(ana_nn_3))\nif do_ap_1 or do_ap_2 or do_ap_3:\n print('\\tAffinity propagation settings: ')\n print('\\t\\t-Damping: ' + str(ap_damp))\n print('\\t\\t-Maximum iterations: ' + str(ap_damp))\n print('\\t\\t-Convergence iterations: ' + str(ap_damp))\n print('\\t\\t-Preference: ' + str(ap_damp))\n print('\\t\\t-Centroid radius: ' + str(ap_c_rad))\n print('\\t\\t-Processing layers: ')\n if do_ap_1:\n print('\\t\\t\\t+Layer 1')\n if do_ap_2:\n print('\\t\\t\\t+Layer 2')\n if do_ap_3:\n print('\\t\\t\\t+Layer 3')\nprint('\\tP-Value computation setting:')\nprint('\\t\\t-Percentile: ' + str(p_per) + ' %')\nprint('\\t\\t-Number of instances for simulations: ' + str(p_nsims))\nif fig_fmt is not None:\n print('\\tStoring figures:')\n print('\\t\\t-Format: ' + str(fig_fmt))\nelse:\n print('\\tPlotting settings: ')\nprint('')\n\n######### Process\n\nprint('Main Routine: ')\nmats_lists, gl_lists = None, None\n\nout_stem_dir = out_dir + '/' + out_stem\nprint('\\tCleaning the output dir: ' + out_stem)\nif os.path.exists(out_stem_dir):\n clean_dir(out_stem_dir)\nelse:\n os.makedirs(out_stem_dir)\n\nprint('\\tLoading input data (only the first entry is loaded)...')\nstar_1, star_2, star_3 = sub.Star(), sub.Star(), sub.Star()\ntry:\n star_1.load(in_star_1)\n star_2.load(in_star_2)\n star_3.load(in_star_3)\nexcept pexceptions.PySegInputError as e:\n print('ERROR: input STAR file could not be loaded because of \"' + e.get_message() + '\"')\n print('Terminated. (' + time.strftime(\"%c\") + ')')\n sys.exit(-1)\nltomos_pkl = star_1.get_element('_psPickleFile', 0)\nlist_1 = unpickle_obj(ltomos_pkl)\nltomos_pkl = star_2.get_element('_psPickleFile', 0)\nlist_2 = unpickle_obj(ltomos_pkl)\nltomos_pkl = star_3.get_element('_psPickleFile', 0)\nlist_3 = unpickle_obj(ltomos_pkl)\nset_lists = surf.SetListTomoParticles()\nset_lists.add_list_tomos(list_1, key_1)\nset_lists.add_list_tomos(list_2, key_2)\nset_lists.add_list_tomos(list_3, key_3)\n\nprint('\\tSet pre-processing...')\nif pre_ssup is not None:\n pre_ssup_v = pre_ssup / ana_res\n set_lists.scale_suppression(pre_ssup_v)\nif pre_min_parts > 0:\n set_lists.filter_by_particles_num_tomos(pre_min_parts)\n list_1 = set_lists.get_lists_by_key(key_1)\n list_2 = set_lists.get_lists_by_key(key_2)\n list_3 = set_lists.get_lists_by_key(key_3)\n\nprint('\\tBuilding the dictionaries...')\nshort_tkeys_dic = dict()\ntomos_np_1, tomos_np_2, tomos_np_3 = dict(), dict(), dict()\ntomos_nc, tomos_den, tomos_denv, tomos_dent = dict(), dict(), dict(), dict()\ntomos_nc12, tomos_den12, tomos_denv12, tomos_dent12 = dict(), dict(), dict(), dict()\ntomos_nc13, tomos_den13, tomos_denv13, tomos_dent13 = dict(), dict(), dict(), dict()\ntomos_nc_sims, tomos_den_sims, tomos_denv_sims, tomos_dent_sims = dict(), dict(), dict(), dict()\ntomos_nc_sims12, tomos_den_sims12, tomos_denv_sims12, tomos_dent_sims12 = dict(), dict(), dict(), dict()\ntomos_nc_sims13, tomos_den_sims13, tomos_denv_sims13, tomos_dent_sims13 = dict(), dict(), dict(), dict()\ntomos_nc_sims2, tomos_den_sims2, tomos_denv_sims2, tomos_dent_sims2 = dict(), dict(), dict(), dict()\ntomos_nc_sims212, tomos_den_sims212, tomos_denv_sims212, tomos_dent_sims212 = dict(), dict(), dict(), dict()\ntomos_nc_sims213, tomos_den_sims213, tomos_denv_sims213, tomos_dent_sims213 = dict(), dict(), dict(), dict()\nfor tkey, ltomo in zip(iter(list_1.get_tomos().keys()), iter(list_1.get_tomos().values())):\n try:\n ltomo_1, ltomo_2 = list_2.get_tomo_by_key(tkey), list_2.get_tomo_by_key(tkey)\n except KeyError:\n print('WARNING: tomogram in layer 1 not in lists for layers 2 or 3!')\n continue\n tomos_np_1[tkey], tomos_np_2[tkey], tomos_np_3[tkey] = 0, 0, 0\n tomos_nc[tkey], tomos_den[tkey], tomos_denv[tkey], tot_dent = 0, 0, 0, 0\n tomos_nc12[tkey], tomos_den12[tkey], tomos_denv12[tkey], tot_dent12 = 0, 0, 0, 0\n tomos_nc13[tkey], tomos_den13[tkey], tomos_denv13[tkey], tot_dent13 = 0, 0, 0, 0\n tomos_nc_sims[tkey], tomos_den_sims[tkey], tomos_denv_sims[tkey], tomos_dent_sims[tkey] = \\\n list(), list(), list(), list()\n tomos_nc_sims12[tkey], tomos_den_sims12[tkey], tomos_denv_sims12[tkey], tomos_dent_sims12[tkey] = \\\n list(), list(), list(), list()\n tomos_nc_sims13[tkey], tomos_den_sims13[tkey], tomos_denv_sims13[tkey], tomos_dent_sims13[tkey] = \\\n list(), list(), list(), list()\n tomos_nc_sims2[tkey], tomos_den_sims2[tkey], tomos_denv_sims2[tkey], tomos_dent_sims2[tkey] = \\\n list(), list(), list(), list()\n tomos_nc_sims212[tkey], tomos_den_sims212[tkey], tomos_denv_sims212[tkey], tomos_dent_sims212[tkey] = \\\n list(), list(), list(), list()\n tomos_nc_sims213[tkey], tomos_den_sims213[tkey], tomos_denv_sims213[tkey], tomos_dent_sims213[tkey] = \\\n list(), list(), list(), list()\n short_tkey = os.path.splitext(os.path.split(tkey)[1])[0]\n short_tkeys_dic[short_tkey] = tkey\n\nprint('\\tComputing reference properties...')\nvols = list_1.get_volumes_dict()\nwith open(in_tethers_csv, mode='r') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n vesicles = dict()\n for row in reader:\n try:\n vesicles[short_tkeys_dic[row[0]]] = float(row[1])\n except KeyError:\n continue\n\nout_tomos_dir = out_stem_dir + '/tomos'\nos.makedirs(out_tomos_dir)\nif in_wspace is None:\n\n tomo_count = 0\n print('\\t\\t-Tomograms computing loop:')\n for tkey, ltomo_1 in zip(iter(list_1.get_tomos().keys()), iter(list_1.get_tomos().values())):\n\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n print('\\t\\t\\t+Processing tomogram (' + str(tomo_count + 1) + \\\n ' of ' + str(len(list(tomos_nc.keys()))) + ') : ' + os.path.split(tkey)[1])\n tomo_count += 1\n ltomo_2, ltomo_3 = list_2.get_tomo_by_key(tkey), list_3.get_tomo_by_key(tkey)\n\n cfinder_raw = ColumnsFinder(ltomo_1, ltomo_2, ltomo_3)\n if do_ap_1 or do_ap_2 or do_ap_3:\n hold_dir = out_tomos_dir + '/' + tkey_short\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n if do_ap_1:\n ltomo_1_ap = ltomo_1.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 1: ' + str(ltomo_1.get_num_particles()) \\\n + '->' + str(ltomo_1_ap.get_num_particles()))\n disperse_io.save_vtp(ltomo_1_ap.gen_particles_vtp(), hold_dir + '/' + tkey_short + '_cap1.vtp')\n ltomo_1 = ltomo_1_ap\n if do_ap_2:\n ltomo_2_ap = ltomo_2.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 2: ' + str(ltomo_2.get_num_particles()) \\\n + '->' + str(ltomo_2_ap.get_num_particles()))\n disperse_io.save_vtp(ltomo_2_ap.gen_particles_vtp(), hold_dir + '/' + tkey_short + '_cap2.vtp')\n ltomo_2 = ltomo_2_ap\n if do_ap_3:\n ltomo_3_ap = ltomo_3.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 3: ' + str(ltomo_3.get_num_particles()) \\\n + '->' + str(ltomo_3_ap.get_num_particles()))\n disperse_io.save_vtp(ltomo_3_ap.gen_particles_vtp(), hold_dir + '/' + tkey_short + '_cap3.vtp')\n ltomo_3 = ltomo_3_ap\n\n print('\\t\\t\\t\\t-Count the number of particles...')\n tomos_np_1[tkey] = ltomo_1.get_num_particles()\n tomos_np_2[tkey] = ltomo_2.get_num_particles()\n tomos_np_3[tkey] = ltomo_3.get_num_particles()\n\n print('\\t\\t\\t\\t-Computing columns...')\n cfinder = ColumnsFinder(ltomo_1, ltomo_2, ltomo_3)\n cfinder.find_columns(ana_max_dist_v, ana_nn_2, ana_nn_3)\n cfinder.find_aln12(ana_max_dist_v, ana_nn_2)\n cfinder.find_aln13(ana_max_dist_v, ana_nn_3)\n tomos_nc[tkey] = cfinder.get_num_columns()\n tomos_nc12[tkey] = cfinder.get_num_aln12()\n tomos_nc13[tkey] = cfinder.get_num_aln13()\n tomos_den[tkey] = cfinder.get_den_columns()\n tomos_den12[tkey] = cfinder.get_den_aln12()\n tomos_den13[tkey] = cfinder.get_den_aln13()\n tomos_dent[tkey] = float(cfinder.get_num_columns()) / float(ltomo_1.get_num_particles())\n tomos_dent12[tkey] = float(cfinder.get_num_aln12()) / float(ltomo_1.get_num_particles())\n tomos_dent13[tkey] = float(cfinder.get_num_aln13()) / float(ltomo_1.get_num_particles())\n if vesicles[tkey] > 0:\n tomos_denv[tkey] = float(cfinder.get_num_columns()) / float(vesicles[tkey])\n tomos_denv12[tkey] = float(cfinder.get_num_aln12()) / float(vesicles[tkey])\n tomos_denv13[tkey] = float(cfinder.get_num_aln13()) / float(vesicles[tkey])\n\n print('\\t\\t\\t\\t-Simulating columns (v1):')\n for i in range(p_nsims):\n print('\\t\\t\\t\\t\\t+Simulating instance ' + str(i) + ' of ' + str(p_nsims) + '...')\n sim_lyr_2 = cfinder_raw.gen_layer_model(2, ModelCSRV, mode_emb='center')\n sim_lyr_3 = cfinder_raw.gen_layer_model(3, ModelCSRV, mode_emb='center')\n if do_ap_2:\n hold = sim_lyr_2.get_num_particles()\n sim_lyr_2 = sim_lyr_2.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 2: ' + str(hold) + '->' + str(sim_lyr_2.get_num_particles()))\n if do_ap_3:\n hold = sim_lyr_3.get_num_particles()\n sim_lyr_3 = sim_lyr_3.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 3: ' + str(hold) + '->' + str(sim_lyr_3.get_num_particles()))\n sim_cfinder = ColumnsFinder(ltomo_1, sim_lyr_2, sim_lyr_3)\n sim_cfinder.find_columns(ana_max_dist_v, ana_nn_2, ana_nn_3)\n sim_cfinder.find_aln12(ana_max_dist_v, ana_nn_2)\n sim_cfinder.find_aln13(ana_max_dist_v, ana_nn_3)\n tomos_nc_sims[tkey].append(sim_cfinder.get_num_columns())\n tomos_nc_sims12[tkey].append(sim_cfinder.get_num_aln12())\n tomos_nc_sims13[tkey].append(sim_cfinder.get_num_aln13())\n tomos_den_sims[tkey].append(sim_cfinder.get_den_columns())\n tomos_den_sims12[tkey].append(sim_cfinder.get_den_aln12())\n tomos_den_sims13[tkey].append(sim_cfinder.get_den_aln13())\n tomos_dent_sims[tkey].append(float(sim_cfinder.get_num_columns()) / float(ltomo_1.get_num_particles()))\n tomos_dent_sims12[tkey].append(float(sim_cfinder.get_num_aln12()) / float(ltomo_1.get_num_particles()))\n tomos_dent_sims13[tkey].append(float(sim_cfinder.get_num_aln13()) / float(ltomo_1.get_num_particles()))\n if vesicles[tkey] > 0:\n tomos_denv_sims[tkey].append(float(sim_cfinder.get_num_columns()) / float(vesicles[tkey]))\n tomos_denv_sims12[tkey].append(float(sim_cfinder.get_num_aln12()) / float(vesicles[tkey]))\n tomos_denv_sims13[tkey].append(float(sim_cfinder.get_num_aln13()) / float(vesicles[tkey]))\n\n print('\\t\\t\\t\\t-Simulating columns (v2):')\n for i in range(p_nsims):\n print('\\t\\t\\t\\t\\t+Simulating instance ' + str(i) + ' of ' + str(p_nsims) + '...')\n sim_lyr_1 = cfinder_raw.gen_layer_model(1, ModelCSRV, mode_emb='center')\n if do_ap_1:\n hold = sim_lyr_1.get_num_particles()\n sim_lyr_1 = sim_lyr_1.gen_newtomo_ap(ap_pref, ap_damp, ap_max_iter, ap_conv_iter,\n c_rad=ap_c_rad, pj=True)\n print('\\t\\t\\t\\t-Particles->APc for layer 1: ' + str(hold) + '->' + str(sim_lyr_1.get_num_particles()))\n sim_cfinder2 = ColumnsFinder(sim_lyr_1, ltomo_2, ltomo_3)\n sim_cfinder2.find_columns(ana_max_dist_v, ana_nn_2, ana_nn_3)\n sim_cfinder2.find_aln12(ana_max_dist_v, ana_nn_2)\n sim_cfinder2.find_aln13(ana_max_dist_v, ana_nn_3)\n tomos_nc_sims2[tkey].append(sim_cfinder2.get_num_columns())\n tomos_nc_sims212[tkey].append(sim_cfinder2.get_num_aln12())\n tomos_nc_sims213[tkey].append(sim_cfinder2.get_num_aln13())\n tomos_den_sims2[tkey].append(sim_cfinder2.get_den_columns())\n tomos_den_sims212[tkey].append(sim_cfinder2.get_den_aln12())\n tomos_den_sims213[tkey].append(sim_cfinder2.get_den_aln13())\n tomos_dent_sims2[tkey].append(float(sim_cfinder2.get_num_columns()) / float(sim_lyr_1.get_num_particles()))\n tomos_dent_sims212[tkey].append(float(sim_cfinder2.get_num_aln12()) / float(sim_lyr_1.get_num_particles()))\n tomos_dent_sims213[tkey].append(float(sim_cfinder2.get_num_aln13()) / float(sim_lyr_1.get_num_particles()))\n if vesicles[tkey] > 0:\n tomos_denv_sims2[tkey].append(float(sim_cfinder2.get_num_columns()) / float(vesicles[tkey]))\n tomos_denv_sims212[tkey].append(float(sim_cfinder2.get_num_aln12()) / float(vesicles[tkey]))\n tomos_denv_sims213[tkey].append(float(sim_cfinder2.get_num_aln13()) / float(vesicles[tkey]))\n\n out_wspace = out_dir + '/' + out_stem + '_wspace.pkl'\n print('\\tPickling computation workspace in: ' + out_wspace)\n wspace = (tomos_nc, tomos_den, tomos_denv, tomos_dent,\n tomos_nc12, tomos_den12, tomos_denv12, tomos_dent12,\n tomos_nc13, tomos_den13, tomos_denv13, tomos_dent13,\n tomos_nc_sims, tomos_den_sims, tomos_denv_sims, tomos_dent_sims,\n tomos_nc_sims12, tomos_den_sims12, tomos_denv_sims12, tomos_dent_sims12,\n tomos_nc_sims13, tomos_den_sims13, tomos_denv_sims13, tomos_dent_sims13,\n tomos_nc_sims2, tomos_den_sims2, tomos_denv_sims2, tomos_dent_sims2,\n tomos_nc_sims212, tomos_den_sims212, tomos_denv_sims212, tomos_dent_sims212,\n tomos_nc_sims213, tomos_den_sims213, tomos_denv_sims213, tomos_dent_sims213,\n vesicles, vols,\n tomos_np_1, tomos_np_2, tomos_np_3)\n with open(out_wspace, \"wb\") as fl:\n pickle.dump(wspace, fl)\n fl.close()\n\nelse:\n\n print('\\tLoading the workspace: ' + in_wspace)\n with open(in_wspace, 'r') as pkl:\n wspace = pickle.load(pkl)\n tomos_nc, tomos_den, tomos_denv, tomos_dent = wspace[0], wspace[1], wspace[2], wspace[3]\n tomos_nc12, tomos_den12, tomos_denv12, tomos_dent12 = wspace[4], wspace[5], wspace[6], wspace[7]\n tomos_nc13, tomos_den13, tomos_denv13, tomos_dent13 = wspace[8], wspace[9], wspace[10], wspace[11]\n tomos_nc_sims, tomos_den_sims, tomos_denv_sims, tomos_dent_sims = wspace[12], wspace[13], \\\n wspace[14], wspace[15]\n tomos_nc_sims12, tomos_den_sims12, tomos_denv_sims12, tomos_dent_sims12 = wspace[16], wspace[17], \\\n wspace[18], wspace[19]\n tomos_nc_sims13, tomos_den_sims13, tomos_denv_sims13, tomos_dent_sims13 = wspace[20], wspace[21], \\\n wspace[22], wspace[23]\n tomos_nc_sims2, tomos_den_sims2, tomos_denv_sims2, tomos_dent_sims2 = wspace[24], wspace[25], \\\n wspace[26], wspace[27]\n tomos_nc_sims212, tomos_den_sims212, tomos_denv_sims212, tomos_dent_sims212 = wspace[28], wspace[29], \\\n wspace[30], wspace[31]\n tomos_nc_sims213, tomos_den_sims213, tomos_denv_sims213, tomos_dent_sims213 = wspace[32], wspace[33], \\\n wspace[34], wspace[35]\n vesicles, vols = wspace[36], wspace[37]\n tomos_np_1, tomos_np_2, tomos_np_3 = wspace[38], wspace[39], wspace[40]\n\n\nprint('\\tTOMOGRAMS PLOTTING LOOP: ')\n\nprint('\\t\\t-Plotting the number of columns...')\nfor tkey, nc in zip(iter(tomos_nc.keys()), iter(tomos_nc.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Number of columns')\n plt.bar(0.8, nc, BAR_WIDTH, color='blue', linewidth=2)\n ic_low = np.percentile(tomos_nc_sims[tkey], p_per)\n ic_med = np.percentile(tomos_nc_sims[tkey], 50)\n ic_high = np.percentile(tomos_nc_sims[tkey], 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n ic_low2 = np.percentile(tomos_nc_sims2[tkey], p_per)\n ic_med2 = np.percentile(tomos_nc_sims2[tkey], 50)\n ic_high2 = np.percentile(tomos_nc_sims2[tkey], 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/col/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\n plt.close()\n\nfor tkey, nc in zip(iter(tomos_nc12.keys()), iter(tomos_nc12.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Number of alignments 1->2')\n plt.bar(0.8, nc, BAR_WIDTH, color='blue', linewidth=2)\n ic_low = np.percentile(tomos_nc_sims12[tkey], p_per)\n ic_med = np.percentile(tomos_nc_sims12[tkey], 50)\n ic_high = np.percentile(tomos_nc_sims12[tkey], 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n ic_low2 = np.percentile(tomos_nc_sims212[tkey], p_per)\n ic_med2 = np.percentile(tomos_nc_sims212[tkey], 50)\n ic_high2 = np.percentile(tomos_nc_sims212[tkey], 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln12/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\n plt.close()\n\nfor tkey, nc in zip(iter(tomos_nc13.keys()), iter(tomos_nc13.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Number of alignments 1->3')\n plt.bar(0.8, nc, BAR_WIDTH, color='blue', linewidth=2)\n ic_low = np.percentile(tomos_nc_sims13[tkey], p_per)\n ic_med = np.percentile(tomos_nc_sims13[tkey], 50)\n ic_high = np.percentile(tomos_nc_sims13[tkey], 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n ic_low2 = np.percentile(tomos_nc_sims213[tkey], p_per)\n ic_med2 = np.percentile(tomos_nc_sims213[tkey], 50)\n ic_high2 = np.percentile(tomos_nc_sims213[tkey], 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln13/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\n plt.close()\n\nprint('\\t\\t-Plotting columns density...')\nfor tkey, den in zip(iter(tomos_den.keys()), iter(tomos_den.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Columns density [column/nm$^3$]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, den, BAR_WIDTH, color='blue', linewidth=2)\n den_sims = np.asarray(tomos_den_sims[tkey])\n ic_low = np.percentile(den_sims, p_per)\n ic_med = np.percentile(den_sims, 50)\n ic_high = np.percentile(den_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n den_sims2 = np.asarray(tomos_den_sims2[tkey])\n ic_low2 = np.percentile(den_sims2, p_per)\n ic_med2 = np.percentile(den_sims2, 50)\n ic_high2 = np.percentile(den_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/col/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\n plt.close()\n\nfor tkey, den in zip(iter(tomos_den12.keys()), iter(tomos_den12.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Alignments 1->2 density [column/nm$^3$]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, den, BAR_WIDTH, color='blue', linewidth=2)\n den_sims = np.asarray(tomos_den_sims12[tkey])\n ic_low = np.percentile(den_sims, p_per)\n ic_med = np.percentile(den_sims, 50)\n ic_high = np.percentile(den_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n den_sims2 = np.asarray(tomos_den_sims212[tkey])\n ic_low2 = np.percentile(den_sims2, p_per)\n ic_med2 = np.percentile(den_sims2, 50)\n ic_high2 = np.percentile(den_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln12/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\n plt.close()\n\nfor tkey, den in zip(iter(tomos_den13.keys()), iter(tomos_den13.values())):\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Alignments 1->3 density [column/nm$^3$]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, den, BAR_WIDTH, color='blue', linewidth=2)\n den_sims = np.asarray(tomos_den_sims13[tkey])\n ic_low = np.percentile(den_sims, p_per)\n ic_med = np.percentile(den_sims, 50)\n ic_high = np.percentile(den_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n den_sims2 = np.asarray(tomos_den_sims213[tkey])\n ic_low2 = np.percentile(den_sims2, p_per)\n ic_med2 = np.percentile(den_sims2, 50)\n ic_high2 = np.percentile(den_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln13/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\n plt.close()\n\nprint('\\t\\t-Plotting columns density per synaptic vesicle...')\nfor tkey, denv in zip(iter(tomos_denv.keys()), iter(tomos_denv.values())):\n if len(tomos_denv_sims[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Columns density [column/sv]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, denv, BAR_WIDTH, color='blue', linewidth=2)\n denv_sims = np.asarray(tomos_denv_sims[tkey])\n ic_low = np.percentile(denv_sims, p_per)\n ic_med = np.percentile(denv_sims, 50)\n ic_high = np.percentile(denv_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n denv_sims2 = np.asarray(tomos_denv_sims2[tkey])\n ic_low2 = np.percentile(denv_sims2, p_per)\n ic_med2 = np.percentile(denv_sims2, 50)\n ic_high2 = np.percentile(denv_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/col/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\n plt.close()\n\nfor tkey, denv in zip(iter(tomos_denv12.keys()), iter(tomos_denv12.values())):\n if len(tomos_denv_sims12[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Aligment 1->2 density [column/sv]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, denv, BAR_WIDTH, color='blue', linewidth=2)\n denv_sims = np.asarray(tomos_denv_sims12[tkey])\n ic_low = np.percentile(denv_sims, p_per)\n ic_med = np.percentile(denv_sims, 50)\n ic_high = np.percentile(denv_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n denv_sims2 = np.asarray(tomos_denv_sims212[tkey])\n ic_low2 = np.percentile(denv_sims2, p_per)\n ic_med2 = np.percentile(denv_sims2, 50)\n ic_high2 = np.percentile(denv_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln12/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\n plt.close()\n\nfor tkey, denv in zip(iter(tomos_denv13.keys()), iter(tomos_denv13.values())):\n if len(tomos_denv_sims13[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Alignment 1->3 density [column/sv]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, denv, BAR_WIDTH, color='blue', linewidth=2)\n denv_sims = np.asarray(tomos_denv_sims13[tkey])\n ic_low = np.percentile(denv_sims, p_per)\n ic_med = np.percentile(denv_sims, 50)\n ic_high = np.percentile(denv_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n denv_sims2 = np.asarray(tomos_denv_sims213[tkey])\n ic_low2 = np.percentile(denv_sims2, p_per)\n ic_med2 = np.percentile(denv_sims2, 50)\n ic_high2 = np.percentile(denv_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln13/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\n plt.close()\n\nprint('\\t\\t-Plotting columns density per tether...')\nhigh_pvals, high_pvals2 = dict(), dict()\nfor tkey, dent in zip(iter(tomos_dent.keys()), iter(tomos_dent.values())):\n if len(tomos_dent_sims[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Columns density [column/tether]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, dent, BAR_WIDTH, color='blue', linewidth=2)\n dent_sims = np.asarray(tomos_dent_sims[tkey])\n ic_low = np.percentile(dent_sims, p_per)\n ic_med = np.percentile(dent_sims, 50)\n ic_high = np.percentile(dent_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n dent_sims2 = np.asarray(tomos_dent_sims2[tkey])\n ic_low2 = np.percentile(dent_sims2, p_per)\n ic_med2 = np.percentile(dent_sims2, 50)\n ic_high2 = np.percentile(dent_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/col/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\n plt.close()\n high_pvals[tkey] = compute_pval(dent, dent_sims)\n high_pvals2[tkey] = compute_pval(dent, dent_sims2)\n\nhigh_pvals12, high_pvals212 = dict(), dict()\nfor tkey, dent in zip(iter(tomos_dent12.keys()), iter(tomos_dent12.values())):\n if len(tomos_dent_sims12[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Alignment 1->2 density [column/tether]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, dent, BAR_WIDTH, color='blue', linewidth=2)\n dent_sims = np.asarray(tomos_dent_sims12[tkey])\n ic_low = np.percentile(dent_sims, p_per)\n ic_med = np.percentile(dent_sims, 50)\n ic_high = np.percentile(dent_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n dent_sims2 = np.asarray(tomos_dent_sims212[tkey])\n ic_low2 = np.percentile(dent_sims2, p_per)\n ic_med2 = np.percentile(dent_sims2, 50)\n ic_high2 = np.percentile(dent_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln12/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\n plt.close()\n high_pvals12[tkey] = compute_pval(dent, dent_sims)\n high_pvals212[tkey] = compute_pval(dent, dent_sims2)\n\nhigh_pvals13, high_pvals213 = dict(), dict()\nfor tkey, dent in zip(iter(tomos_dent13.keys()), iter(tomos_dent13.values())):\n if len(tomos_dent_sims13[tkey]) > 0:\n tkey_short = os.path.splitext(os.path.split(tkey)[1])[0]\n plt.figure()\n plt.ylabel('Alignment 1->3 density [column/tether]')\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.bar(0.8, dent, BAR_WIDTH, color='blue', linewidth=2)\n dent_sims = np.asarray(tomos_dent_sims13[tkey])\n ic_low = np.percentile(dent_sims, p_per)\n ic_med = np.percentile(dent_sims, 50)\n ic_high = np.percentile(dent_sims, 100-p_per)\n plt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n dent_sims2 = np.asarray(tomos_dent_sims213[tkey])\n ic_low2 = np.percentile(dent_sims2, p_per)\n ic_med2 = np.percentile(dent_sims2, 50)\n ic_high2 = np.percentile(dent_sims2, 100 - p_per)\n plt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\n plt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\n plt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\n plt.xlim(0.5, 3.5)\n plt.tight_layout()\n if fig_fmt is None:\n plt.show(block=True)\n else:\n hold_dir = out_tomos_dir + '/' + tkey_short + '/aln13/'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\n plt.close()\n high_pvals13[tkey] = compute_pval(dent, dent_sims)\n high_pvals213[tkey] = compute_pval(dent, dent_sims2)\n\nprint('\\t\\t-Plotting column density by categories...')\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Columns density [Col/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals, high_pvals2)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 2.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/coloc.png', dpi=300)\nplt.close()\n\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Alignments 1->2 density [Aln/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals12, high_pvals212)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 2.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/aln12.png', dpi=300)\nplt.close()\n\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Alignments 1->3 density [Aln/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals13, high_pvals213)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 2.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/aln13.png', dpi=300)\nplt.close()\n\nprint('\\t\\t-Plotting column density by categories (CTRL vs STIM)...')\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Columns density [Col/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals, high_pvals2)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n tkey_hold = os.path.split(tkey)[1].split('_')\n tkey_stem = tkey_hold[1] + '_' + tkey_hold[2]\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if tkey_stem in stim_stems:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side+'+', hold_pval])\n else:\n lst.append([hold_side+'+', hold_pval])\n else:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray', 'k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 4.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/coloc_ctrl_vs_stim.png', dpi=300)\nplt.close()\n\nprint('\\t\\t-Plotting alignment 1->2 density by categories (CTRL vs STIM)...')\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Alignment 1->2 density [Aln/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals12, high_pvals212)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n tkey_hold = os.path.split(tkey)[1].split('_')\n tkey_stem = tkey_hold[1] + '_' + tkey_hold[2]\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if tkey_stem in stim_stems:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side+'+', hold_pval])\n else:\n lst.append([hold_side+'+', hold_pval])\n else:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray', 'k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 4.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/aln12_ctrl_vs_stim.png', dpi=300)\nplt.close()\n\nprint('\\t\\t-Plotting alignment 1->3 density by categories (CTRL vs STIM)...')\nlst, cols = list(), ['side', 'p-value']\nplt.figure()\npd_pvals = None\nplt.title('Alignment 1->3 density [Aln/Tether]')\nfor hold_side, hold_pvals in zip(('SIMULATED', 'SIMULATED\\''), (high_pvals13, high_pvals213)):\n for tkey, hold_pval in zip(iter(hold_pvals.keys()), iter(hold_pvals.values())):\n tkey_hold = os.path.split(tkey)[1].split('_')\n tkey_stem = tkey_hold[1] + '_' + tkey_hold[2]\n if (hold_pval is not None) and np.isfinite(hold_pval):\n if tkey_stem in stim_stems:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side+'+', hold_pval])\n else:\n lst.append([hold_side+'+', hold_pval])\n else:\n if fig_weight_tet:\n for i in range(tomos_np_1[tkey]):\n lst.append([hold_side, hold_pval])\n else:\n lst.append([hold_side, hold_pval])\npd_pvals = pd.DataFrame(lst, columns=cols)\nsns.boxplot(x='side', y='p-value', data=pd_pvals, color='white')\nflatui = ['k', 'gray', 'k', 'gray']\nsns.set_palette(flatui)\nsns.swarmplot(x='side', y='p-value', data=pd_pvals, size=7)\nplt.ylim((0.5, 1.1))\nx_line = np.linspace(-0.5, 4.5, 10)\nplt.plot(x_line, .95*np.ones(shape=len(x_line)), 'k--', linewidth=2)\nplt.grid(True, alpha=0.5)\nplt.ylabel('p-value')\nplt.xlabel('')\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n plt.savefig(out_tomos_dir + '/aln13_ctrl_vs_stim.png', dpi=300)\nplt.close()\n\nprint('\\tTOTAL PLOTTING: ')\n\nout_lists_dir = out_stem_dir + '/lists'\nos.makedirs(out_lists_dir)\n\nprint('\\t\\t-Gathering tomogram simulations: ')\ntot_nc, tot_nc12, tot_nc13, tot_vol, tot_ves, tot_teth = 0, 0, 0, 0, 0, 0\nncs_sims, ncs_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_sims12, ncs_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_sims13, ncs_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_sims, den_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_sims12, den_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_sims13, den_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_sims, denv_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_sims12, denv_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_sims13, denv_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_sims, dent_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_sims12, dent_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_sims13, dent_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nfor tkey, nc_sim in zip(iter(tomos_nc_sims.keys()), iter(tomos_nc_sims.values())):\n for i in range(p_nsims):\n ncs_sims[i] += nc_sim[i]\n ncs_sims2[i] += tomos_nc_sims2[tkey][i]\n ncs_sims12[i] += tomos_nc_sims12[tkey][i]\n ncs_sims212[i] += tomos_nc_sims212[tkey][i]\n ncs_sims13[i] += tomos_nc_sims13[tkey][i]\n ncs_sims213[i] += tomos_nc_sims213[tkey][i]\n tot_vol += vols[tkey]\n tot_ves += vesicles[tkey]\n tot_teth += tomos_np_1[tkey]\n tot_nc += tomos_nc[tkey]\n tot_nc12 += tomos_nc12[tkey]\n tot_nc13 += tomos_nc13[tkey]\nfor i in range(p_nsims):\n if tot_vol > 0:\n den_sims[i], den_sims2[i] = ncs_sims[i] / tot_vol, ncs_sims2[i] / tot_vol\n den_sims12[i], den_sims212[i] = ncs_sims12[i] / tot_vol, ncs_sims212[i] / tot_vol\n den_sims13[i], den_sims213[i] = ncs_sims13[i] / tot_vol, ncs_sims213[i] / tot_vol\n if tot_ves > 0:\n denv_sims[i], denv_sims2[i] = ncs_sims[i] / tot_ves, ncs_sims2[i] / tot_ves\n denv_sims12[i], denv_sims212[i] = ncs_sims12[i] / tot_ves, ncs_sims212[i] / tot_ves\n denv_sims13[i], denv_sims213[i] = ncs_sims13[i] / tot_ves, ncs_sims213[i] / tot_ves\n if tot_teth > 0:\n dent_sims[i], dent_sims2[i] = ncs_sims[i] / tot_teth, ncs_sims2[i] / tot_teth\n dent_sims12[i], dent_sims212[i] = ncs_sims12[i] / tot_teth, ncs_sims212[i] / tot_teth\n dent_sims13[i], dent_sims213[i] = ncs_sims13[i] / tot_teth, ncs_sims213[i] / tot_teth\n\nprint('\\t\\t-Plotting the number of columns...')\nplt.figure()\nplt.ylabel('Number of columns')\n# plt.xlabel('Total columns in the dataset')\nplt.bar(0.8, tot_nc, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_sims, p_per)\nic_med = np.percentile(ncs_sims, 50)\nic_high = np.percentile(ncs_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_sims2, p_per)\nic_med2 = np.percentile(ncs_sims2, 50)\nic_high2 = np.percentile(ncs_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nplt.figure()\nplt.ylabel('Number of alignments 1->2')\n# plt.xlabel('Total columns in the dataset')\nplt.bar(0.8, tot_nc12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_sims12, p_per)\nic_med = np.percentile(ncs_sims12, 50)\nic_high = np.percentile(ncs_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_sims212, p_per)\nic_med2 = np.percentile(ncs_sims212, 50)\nic_high2 = np.percentile(ncs_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nplt.figure()\nplt.ylabel('Number of alignments 1->3')\n# plt.xlabel('Total columns in the dataset')\nplt.bar(0.8, tot_nc13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_sims13, p_per)\nic_med = np.percentile(ncs_sims13, 50)\nic_high = np.percentile(ncs_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_sims213, p_per)\nic_med2 = np.percentile(ncs_sims213, 50)\nic_high2 = np.percentile(ncs_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density..')\ntot_den = tot_nc / tot_vol\nplt.figure()\nplt.ylabel('Column density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n# plt.xlabel('Columns density by pre-syanptic membrane volume')\nplt.bar(0.8, tot_den, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_sims, p_per)\nic_med = np.percentile(den_sims, 50)\nic_high = np.percentile(den_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_sims2, p_per)\nic_med2 = np.percentile(den_sims2, 50)\nic_high2 = np.percentile(den_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\ntot_den12 = tot_nc12 / tot_vol\nplt.figure()\nplt.ylabel('Alignment 1->2 density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n# plt.xlabel('Columns density by pre-syanptic membrane volume')\nplt.bar(0.8, tot_den12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_sims12, p_per)\nic_med = np.percentile(den_sims12, 50)\nic_high = np.percentile(den_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_sims212, p_per)\nic_med2 = np.percentile(den_sims212, 50)\nic_high2 = np.percentile(den_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\ntot_den13 = tot_nc13 / tot_vol\nplt.figure()\nplt.ylabel('Alignment 1->3 density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n# plt.xlabel('Columns density by pre-syanptic membrane volume')\nplt.bar(0.8, tot_den13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_sims13, p_per)\nic_med = np.percentile(den_sims13, 50)\nic_high = np.percentile(den_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_sims213, p_per)\nic_med2 = np.percentile(den_sims213, 50)\nic_high2 = np.percentile(den_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density by synaptic vesicles..')\ntot_denv = tot_nc / tot_ves\nplt.figure()\nplt.ylabel('Column density [Col/SV]')\n# plt.xlabel('Column probability per synaptic vesicle')\nplt.bar(0.8, tot_denv, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_sims, p_per)\nic_med = np.percentile(denv_sims, 50)\nic_high = np.percentile(denv_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_sims2, p_per)\nic_med2 = np.percentile(denv_sims2, 50)\nic_high2 = np.percentile(denv_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\ntot_denv12 = tot_nc12 / tot_ves\nplt.figure()\nplt.ylabel('Alignment 1->2 density [Col/SV]')\n# plt.xlabel('Column probability per synaptic vesicle')\nplt.bar(0.8, tot_denv12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_sims12, p_per)\nic_med = np.percentile(denv_sims12, 50)\nic_high = np.percentile(denv_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_sims212, p_per)\nic_med2 = np.percentile(denv_sims212, 50)\nic_high2 = np.percentile(denv_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\ntot_denv13 = tot_nc13 / tot_ves\nplt.figure()\nplt.ylabel('Alignment 1->3 density [Col/SV]')\n# plt.xlabel('Column probability per synaptic vesicle')\nplt.bar(0.8, tot_denv13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_sims13, p_per)\nic_med = np.percentile(denv_sims13, 50)\nic_high = np.percentile(denv_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_sims213, p_per)\nic_med2 = np.percentile(denv_sims213, 50)\nic_high2 = np.percentile(denv_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density by tethers..')\ntot_dent = float(tot_nc) / tot_teth\nplt.figure()\nplt.ylabel('Column density [Col/Tether]')\n# plt.xlabel('Column probability per tether')\nplt.bar(0.8, tot_dent, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_sims, p_per)\nic_med = np.percentile(dent_sims, 50)\nic_high = np.percentile(dent_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_sims2, p_per)\nic_med2 = np.percentile(dent_sims2, 50)\nic_high2 = np.percentile(dent_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\ntot_dent12 = float(tot_nc12) / tot_teth\nplt.figure()\nplt.ylabel('Alignment 1->2 density [Col/Tether]')\n# plt.xlabel('Column probability per tether')\nplt.bar(0.8, tot_dent12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_sims12, p_per)\nic_med = np.percentile(dent_sims12, 50)\nic_high = np.percentile(dent_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_sims212, p_per)\nic_med2 = np.percentile(dent_sims212, 50)\nic_high2 = np.percentile(dent_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\ntot_dent13 = float(tot_nc13) / tot_teth\nplt.figure()\nplt.ylabel('Alignment 1->3 density [Col/Tether]')\n# plt.xlabel('Column probability per tether')\nplt.bar(0.8, tot_dent13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_sims13, p_per)\nic_med = np.percentile(dent_sims13, 50)\nic_high = np.percentile(dent_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_sims213, p_per)\nic_med2 = np.percentile(dent_sims213, 50)\nic_high2 = np.percentile(dent_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3), ('EXPERIMENTAL', 'SIMULATED', 'SIMULATED\\''))\nplt.xlim(0.5, 3.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_lists_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\nprint('\\tCTRL vs STIM PLOTTING: ')\n\nout_cs_dir = out_stem_dir + '/ctrl_vs_stim'\nos.makedirs(out_cs_dir)\n\nprint('\\t\\t-Gathering tomogram simulations: ')\ntot_ctrl_nc, tot_ctrl_nc12, tot_ctrl_nc13, tot_ctrl_vol, tot_ctrl_ves, tot_ctrl_teth = 0, 0, 0, 0, 0, 0\ntot_stim_nc, tot_stim_nc12, tot_stim_nc13, tot_stim_vol, tot_stim_ves, tot_stim_teth = 0, 0, 0, 0, 0, 0\nncs_ctrl_sims, ncs_stim_sims = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_ctrl_sims12, ncs_stim_sims12 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_ctrl_sims13, ncs_stim_sims13 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims, den_stim_sims = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims12, den_stim_sims12 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims13, den_stim_sims13 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims, denv_stim_sims = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims12, denv_stim_sims12 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims13, denv_stim_sims13 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims, dent_stim_sims = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims12, dent_stim_sims12 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims13, dent_stim_sims13 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_ctrl_sims2, ncs_stim_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_ctrl_sims212, ncs_stim_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nncs_ctrl_sims213, ncs_stim_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims2, den_stim_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims212, den_stim_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nden_ctrl_sims213, den_stim_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims2, denv_stim_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims212, denv_stim_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndenv_ctrl_sims213, denv_stim_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims2, dent_stim_sims2 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims212, dent_stim_sims212 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\ndent_ctrl_sims213, dent_stim_sims213 = np.zeros(shape=p_nsims, dtype=np.float), np.zeros(shape=p_nsims, dtype=np.float)\nfor tkey, nc_sim in zip(iter(tomos_nc_sims.keys()), iter(tomos_nc_sims.values())):\n tkey_hold = os.path.split(tkey)[1].split('_')\n tkey_stem = tkey_hold[1] + '_' + tkey_hold[2]\n if tkey_stem in ctrl_stems:\n for i in range(p_nsims):\n ncs_ctrl_sims[i] += nc_sim[i]\n ncs_ctrl_sims12[i] += tomos_nc_sims12[tkey][i]\n ncs_ctrl_sims13[i] += tomos_nc_sims13[tkey][i]\n ncs_ctrl_sims2[i] += tomos_nc_sims2[tkey][i]\n ncs_ctrl_sims212[i] += tomos_nc_sims212[tkey][i]\n ncs_ctrl_sims213[i] += tomos_nc_sims213[tkey][i]\n tot_ctrl_nc += tomos_nc[tkey]\n tot_ctrl_nc12 += tomos_nc12[tkey]\n tot_ctrl_nc13 += tomos_nc13[tkey]\n tot_ctrl_vol += vols[tkey]\n tot_ctrl_ves += vesicles[tkey]\n tot_ctrl_teth += tomos_np_1[tkey]\n elif tkey_stem in stim_stems:\n for i in range(p_nsims):\n ncs_stim_sims[i] += nc_sim[i]\n ncs_stim_sims12[i] += tomos_nc_sims12[tkey][i]\n ncs_stim_sims13[i] += tomos_nc_sims13[tkey][i]\n ncs_stim_sims2[i] += tomos_nc_sims2[tkey][i]\n ncs_stim_sims212[i] += tomos_nc_sims212[tkey][i]\n ncs_stim_sims213[i] += tomos_nc_sims213[tkey][i]\n tot_stim_nc += tomos_nc[tkey]\n tot_stim_nc12 += tomos_nc12[tkey]\n tot_stim_nc13 += tomos_nc13[tkey]\n tot_stim_vol += vols[tkey]\n tot_stim_ves += vesicles[tkey]\n tot_stim_teth += tomos_np_1[tkey]\nfor i in range(p_nsims):\n if tot_ctrl_vol > 0:\n den_ctrl_sims[i] = ncs_ctrl_sims[i] / tot_ctrl_vol\n den_ctrl_sims12[i] = ncs_ctrl_sims12[i] / tot_ctrl_vol\n den_ctrl_sims13[i] = ncs_ctrl_sims13[i] / tot_ctrl_vol\n den_ctrl_sims2[i] = ncs_ctrl_sims2[i] / tot_ctrl_vol\n den_ctrl_sims212[i] = ncs_ctrl_sims212[i] / tot_ctrl_vol\n den_ctrl_sims213[i] = ncs_ctrl_sims213[i] / tot_ctrl_vol\n if tot_ctrl_ves > 0:\n denv_ctrl_sims[i] = ncs_ctrl_sims[i] / tot_ctrl_ves\n denv_ctrl_sims12[i] = ncs_ctrl_sims12[i] / tot_ctrl_ves\n denv_ctrl_sims2[i] = ncs_ctrl_sims2[i] / tot_ctrl_ves\n denv_ctrl_sims212[i] = ncs_ctrl_sims212[i] / tot_ctrl_ves\n denv_ctrl_sims213[i] = ncs_ctrl_sims213[i] / tot_ctrl_ves\n if tot_ctrl_teth > 0:\n dent_ctrl_sims[i] = ncs_ctrl_sims[i] / tot_ctrl_teth\n dent_ctrl_sims12[i] = ncs_ctrl_sims12[i] / tot_ctrl_teth\n dent_ctrl_sims13[i] = ncs_ctrl_sims13[i] / tot_ctrl_teth\n dent_ctrl_sims2[i] = ncs_ctrl_sims2[i] / tot_ctrl_teth\n dent_ctrl_sims212[i] = ncs_ctrl_sims212[i] / tot_ctrl_teth\n dent_ctrl_sims213[i] = ncs_ctrl_sims213[i] / tot_ctrl_teth\n if tot_stim_vol > 0:\n den_stim_sims[i] = ncs_stim_sims[i] / tot_stim_vol\n den_stim_sims12[i] = ncs_stim_sims12[i] / tot_stim_vol\n den_stim_sims13[i] = ncs_stim_sims13[i] / tot_stim_vol\n den_stim_sims2[i] = ncs_stim_sims2[i] / tot_stim_vol\n den_stim_sims212[i] = ncs_stim_sims212[i] / tot_stim_vol\n den_stim_sims213[i] = ncs_stim_sims213[i] / tot_stim_vol\n if tot_stim_ves > 0:\n denv_stim_sims[i] = ncs_stim_sims[i] / tot_stim_ves\n denv_stim_sims12[i] = ncs_stim_sims12[i] / tot_stim_ves\n denv_stim_sims13[i] = ncs_stim_sims13[i] / tot_stim_ves\n denv_stim_sims2[i] = ncs_stim_sims2[i] / tot_stim_ves\n denv_stim_sims212[i] = ncs_stim_sims212[i] / tot_stim_ves\n denv_stim_sims213[i] = ncs_stim_sims213[i] / tot_stim_ves\n if tot_stim_teth > 0:\n dent_stim_sims[i] = ncs_stim_sims[i] / tot_stim_teth\n dent_stim_sims12[i] = ncs_stim_sims12[i] / tot_stim_teth\n dent_stim_sims13[i] = ncs_stim_sims13[i] / tot_stim_teth\n dent_stim_sims2[i] = ncs_stim_sims2[i] / tot_stim_teth\n dent_stim_sims212[i] = ncs_stim_sims212[i] / tot_stim_teth\n dent_stim_sims213[i] = ncs_stim_sims213[i] / tot_stim_teth\n\nprint('\\t\\t-Plotting the number of columns...')\nplt.figure()\nplt.ylabel('Number of columns')\nplt.bar(0.8, tot_ctrl_nc, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_ctrl_sims, p_per)\nic_med = np.percentile(ncs_ctrl_sims, 50)\nic_high = np.percentile(ncs_ctrl_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_ctrl_sims2, p_per)\nic_med2 = np.percentile(ncs_ctrl_sims2, 50)\nic_high2 = np.percentile(ncs_ctrl_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_nc, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_stim_sims, p_per)\nic_med = np.percentile(ncs_stim_sims, 50)\nic_high = np.percentile(ncs_stim_sims, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_stim_sims2, p_per)\nic_med2 = np.percentile(ncs_stim_sims2, 50)\nic_high2 = np.percentile(ncs_stim_sims2, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nplt.figure()\nplt.ylabel('Number of alignments 1->2')\nplt.bar(0.8, tot_ctrl_nc12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_ctrl_sims12, p_per)\nic_med = np.percentile(ncs_ctrl_sims12, 50)\nic_high = np.percentile(ncs_ctrl_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_ctrl_sims212, p_per)\nic_med2 = np.percentile(ncs_ctrl_sims212, 50)\nic_high2 = np.percentile(ncs_ctrl_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_nc12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_stim_sims12, p_per)\nic_med = np.percentile(ncs_stim_sims12, 50)\nic_high = np.percentile(ncs_stim_sims12, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_stim_sims212, p_per)\nic_med2 = np.percentile(ncs_stim_sims212, 50)\nic_high2 = np.percentile(ncs_stim_sims212, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nplt.figure()\nplt.ylabel('Number of alignments 1->3')\nplt.bar(0.8, tot_ctrl_nc13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_ctrl_sims13, p_per)\nic_med = np.percentile(ncs_ctrl_sims13, 50)\nic_high = np.percentile(ncs_ctrl_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_ctrl_sims213, p_per)\nic_med2 = np.percentile(ncs_ctrl_sims213, 50)\nic_high2 = np.percentile(ncs_ctrl_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_nc13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(ncs_stim_sims13, p_per)\nic_med = np.percentile(ncs_stim_sims13, 50)\nic_high = np.percentile(ncs_stim_sims13, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(ncs_stim_sims213, p_per)\nic_med2 = np.percentile(ncs_stim_sims213, 50)\nic_high2 = np.percentile(ncs_stim_sims213, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/nc.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density..')\ntot_ctrl_den, tot_stim_den = float(tot_ctrl_nc)/tot_ctrl_vol, float(tot_stim_nc)/tot_stim_vol\nplt.figure()\nplt.ylabel('Column density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\nplt.bar(0.8, tot_ctrl_den, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_ctrl_sims, p_per)\nic_med = np.percentile(den_ctrl_sims, 50)\nic_high = np.percentile(den_ctrl_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_ctrl_sims2, p_per)\nic_med2 = np.percentile(den_ctrl_sims2, 50)\nic_high2 = np.percentile(den_ctrl_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_den, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_stim_sims, p_per)\nic_med = np.percentile(den_stim_sims, 50)\nic_high = np.percentile(den_stim_sims, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_stim_sims2, p_per)\nic_med2 = np.percentile(den_stim_sims2, 50)\nic_high2 = np.percentile(den_stim_sims2, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\ntot_ctrl_den12, tot_stim_den12 = float(tot_ctrl_nc12)/tot_ctrl_vol, float(tot_stim_nc12)/tot_stim_vol\nplt.figure()\nplt.ylabel('Alignment 1->2 density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\nplt.bar(0.8, tot_ctrl_den12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_ctrl_sims12, p_per)\nic_med = np.percentile(den_ctrl_sims12, 50)\nic_high = np.percentile(den_ctrl_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_ctrl_sims212, p_per)\nic_med2 = np.percentile(den_ctrl_sims212, 50)\nic_high2 = np.percentile(den_ctrl_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_den12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_stim_sims12, p_per)\nic_med = np.percentile(den_stim_sims12, 50)\nic_high = np.percentile(den_stim_sims12, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_stim_sims212, p_per)\nic_med2 = np.percentile(den_stim_sims212, 50)\nic_high2 = np.percentile(den_stim_sims212, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\ntot_ctrl_den13, tot_stim_den13 = float(tot_ctrl_nc13)/tot_ctrl_vol, float(tot_stim_nc13)/tot_stim_vol\nplt.figure()\nplt.ylabel('Alignment 1->3 density [Col/nm$^3$]')\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\nplt.bar(0.8, tot_ctrl_den13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_ctrl_sims13, p_per)\nic_med = np.percentile(den_ctrl_sims13, 50)\nic_high = np.percentile(den_ctrl_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_ctrl_sims213, p_per)\nic_med2 = np.percentile(den_ctrl_sims213, 50)\nic_high2 = np.percentile(den_ctrl_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_den13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(den_stim_sims13, p_per)\nic_med = np.percentile(den_stim_sims13, 50)\nic_high = np.percentile(den_stim_sims13, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(den_stim_sims213, p_per)\nic_med2 = np.percentile(den_stim_sims213, 50)\nic_high2 = np.percentile(den_stim_sims213, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/den.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density by synaptic vesicles..')\ntot_ctrl_denv, tot_stim_denv = float(tot_ctrl_nc)/tot_ctrl_ves, float(tot_stim_nc)/tot_stim_ves\nplt.figure()\nplt.ylabel('Column density [Col/SV]')\nplt.bar(0.8, tot_ctrl_denv, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_ctrl_sims, p_per)\nic_med = np.percentile(denv_ctrl_sims, 50)\nic_high = np.percentile(denv_ctrl_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_ctrl_sims2, p_per)\nic_med2 = np.percentile(denv_ctrl_sims2, 50)\nic_high2 = np.percentile(denv_ctrl_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_denv, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_stim_sims, p_per)\nic_med = np.percentile(denv_stim_sims, 50)\nic_high = np.percentile(denv_stim_sims, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_stim_sims2, p_per)\nic_med2 = np.percentile(denv_stim_sims2, 50)\nic_high2 = np.percentile(denv_stim_sims2, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\ntot_ctrl_denv12, tot_stim_denv12 = float(tot_ctrl_nc12)/tot_ctrl_ves, float(tot_stim_nc12)/tot_stim_ves\nplt.figure()\nplt.ylabel('Alignments 1->2 density [Col/SV]')\nplt.bar(0.8, tot_ctrl_denv12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_ctrl_sims12, p_per)\nic_med = np.percentile(denv_ctrl_sims12, 50)\nic_high = np.percentile(denv_ctrl_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_ctrl_sims212, p_per)\nic_med2 = np.percentile(denv_ctrl_sims212, 50)\nic_high2 = np.percentile(denv_ctrl_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_denv12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_stim_sims12, p_per)\nic_med = np.percentile(denv_stim_sims12, 50)\nic_high = np.percentile(denv_stim_sims12, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_stim_sims212, p_per)\nic_med2 = np.percentile(denv_stim_sims212, 50)\nic_high2 = np.percentile(denv_stim_sims212, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\ntot_ctrl_denv13, tot_stim_denv13 = float(tot_ctrl_nc13)/tot_ctrl_ves, float(tot_stim_nc13)/tot_stim_ves\nplt.figure()\nplt.ylabel('Alignments 1->3 density [Col/SV]')\nplt.bar(0.8, tot_ctrl_denv13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_ctrl_sims13, p_per)\nic_med = np.percentile(denv_ctrl_sims13, 50)\nic_high = np.percentile(denv_ctrl_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_ctrl_sims213, p_per)\nic_med2 = np.percentile(denv_ctrl_sims213, 50)\nic_high2 = np.percentile(denv_ctrl_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_denv13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(denv_stim_sims13, p_per)\nic_med = np.percentile(denv_stim_sims13, 50)\nic_high = np.percentile(denv_stim_sims13, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(denv_stim_sims213, p_per)\nic_med2 = np.percentile(denv_stim_sims213, 50)\nic_high2 = np.percentile(denv_stim_sims213, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/denv.png')\nplt.close()\n\nprint('\\t\\t-Plotting columns density by tethers..')\ntot_ctrl_dent, tot_stim_dent = float(tot_ctrl_nc)/tot_ctrl_teth, float(tot_stim_nc)/tot_stim_teth\nplt.figure()\nplt.ylabel('Column density [Col/Tether]')\nplt.bar(0.8, tot_ctrl_dent, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_ctrl_sims, p_per)\nic_med = np.percentile(dent_ctrl_sims, 50)\nic_high = np.percentile(dent_ctrl_sims, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_ctrl_sims2, p_per)\nic_med2 = np.percentile(dent_ctrl_sims2, 50)\nic_high2 = np.percentile(dent_ctrl_sims2, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_dent, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_stim_sims, p_per)\nic_med = np.percentile(dent_stim_sims, 50)\nic_high = np.percentile(dent_stim_sims, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_stim_sims2, p_per)\nic_med2 = np.percentile(dent_stim_sims2, 50)\nic_high2 = np.percentile(dent_stim_sims2, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/col'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\ntot_ctrl_dent12, tot_stim_dent12 = float(tot_ctrl_nc12)/tot_ctrl_teth, float(tot_stim_nc12)/tot_stim_teth\nplt.figure()\nplt.ylabel('Alignments 1->2 density [Col/Tether]')\nplt.bar(0.8, tot_ctrl_dent12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_ctrl_sims12, p_per)\nic_med = np.percentile(dent_ctrl_sims12, 50)\nic_high = np.percentile(dent_ctrl_sims12, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_ctrl_sims212, p_per)\nic_med2 = np.percentile(dent_ctrl_sims212, 50)\nic_high2 = np.percentile(dent_ctrl_sims212, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_dent12, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_stim_sims12, p_per)\nic_med = np.percentile(dent_stim_sims12, 50)\nic_high = np.percentile(dent_stim_sims12, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_stim_sims212, p_per)\nic_med2 = np.percentile(dent_stim_sims212, 50)\nic_high2 = np.percentile(dent_stim_sims212, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln12'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\ntot_ctrl_dent13, tot_stim_dent13 = float(tot_ctrl_nc13)/tot_ctrl_teth, float(tot_stim_nc13)/tot_stim_teth\nplt.figure()\nplt.ylabel('Alignments 1->3 density [Col/Tether]')\nplt.bar(0.8, tot_ctrl_dent13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_ctrl_sims13, p_per)\nic_med = np.percentile(dent_ctrl_sims13, 50)\nic_high = np.percentile(dent_ctrl_sims13, 100-p_per)\nplt.bar(1.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(2, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_ctrl_sims213, p_per)\nic_med2 = np.percentile(dent_ctrl_sims213, 50)\nic_high2 = np.percentile(dent_ctrl_sims213, 100-p_per)\nplt.bar(2.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(3, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.bar(4.8, tot_stim_dent13, BAR_WIDTH, color='blue', linewidth=2)\nic_low = np.percentile(dent_stim_sims13, p_per)\nic_med = np.percentile(dent_stim_sims13, 50)\nic_high = np.percentile(dent_stim_sims13, 100-p_per)\nplt.bar(5.8, ic_med, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(6, ic_med, yerr=np.asarray([[ic_med - ic_low, ic_high - ic_med], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nic_low2 = np.percentile(dent_stim_sims213, p_per)\nic_med2 = np.percentile(dent_stim_sims213, 50)\nic_high2 = np.percentile(dent_stim_sims213, 100-p_per)\nplt.bar(6.8, ic_med2, BAR_WIDTH, color='gray', linewidth=2)\nplt.errorbar(7, ic_med2, yerr=np.asarray([[ic_med2 - ic_low2, ic_high2 - ic_med2], ]).reshape(2, 1),\n ecolor='k', elinewidth=4, capthick=4, capsize=8)\nplt.xticks((1, 2, 3, 5, 6, 7), ('EXP', 'SIM', 'SIM\\'', 'EXP+', 'SIM+', 'SIM\\'+'))\nplt.xlim(0.5, 7.5)\nplt.tight_layout()\nif fig_fmt is None:\n plt.show(block=True)\nelse:\n hold_dir = out_cs_dir + '/aln13'\n if not os.path.exists(hold_dir):\n os.makedirs(hold_dir)\n plt.savefig(hold_dir + '/dent.png')\nplt.close()\n\nprint('\\t\\t-Printing results: ')\nprint('\\n')\nprint('\\t\\t\\t+Number of columns found: ' + str(tot_nc))\nprint('\\t\\t\\t+Column density per pre-synaptic membrane volume: ' + str(tot_den))\nprint('\\t\\t\\t+Column density per synaptic vesicle: ' + str(tot_denv))\nprint('\\t\\t\\t+Column density per tether: ' + str(tot_dent))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_dent, dent_sims)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_dent, dent_sims2)))\nprint('\\t\\t\\t+Tether per synaptic vesicle: ' + str(float(tot_teth) / float(tot_ves)))\nprint('')\nprint('\\t\\t\\t+Number of columns found for CTRL: ' + str(tot_ctrl_nc))\nprint('\\t\\t\\t+Column density per pre-synaptic membrane volume: ' + str(tot_ctrl_den))\nprint('\\t\\t\\t+Column density per synaptic vesicle: ' + str(tot_ctrl_denv))\nprint('\\t\\t\\t+Column density per tether: ' + str(tot_ctrl_dent))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_ctrl_dent, dent_ctrl_sims)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_ctrl_dent, dent_ctrl_sims2)))\nprint('\\t\\t\\t+Tether per synaptic vesicle: ' + str(float(tot_ctrl_teth) / float(tot_ctrl_ves)))\nprint('')\nprint('\\t\\t\\t+Number of columns found for STIM: ' + str(tot_stim_nc))\nprint('\\t\\t\\t+Column density per pre-synaptic membrane volume: ' + str(tot_stim_den))\nprint('\\t\\t\\t+Column density per synaptic vesicle: ' + str(tot_stim_denv))\nprint('\\t\\t\\t+Column density per tether: ' + str(tot_stim_dent))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_stim_dent, dent_stim_sims)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_stim_dent, dent_stim_sims2)))\nprint('\\t\\t\\t+Tether per synaptic vesicle: ' + str(float(tot_stim_teth) / float(tot_stim_ves)))\nprint('\\n')\nprint('\\t\\t\\t+Number of alignments 1->2 found: ' + str(tot_nc12))\nprint('\\t\\t\\t+Alignment 1->2 density per pre-synaptic membrane volume: ' + str(tot_den12))\nprint('\\t\\t\\t+Alignment 1->2 density per synaptic vesicle: ' + str(tot_denv12))\nprint('\\t\\t\\t+Column density per tether: ' + str(tot_dent12))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_dent12, dent_sims12)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_dent12, dent_sims212)))\nprint('')\nprint('\\t\\t\\t+Number of alignments 1->2 found for CTRL: ' + str(tot_ctrl_nc12))\nprint('\\t\\t\\t+Alignment 1->2 density per pre-synaptic membrane volume: ' + str(tot_ctrl_den12))\nprint('\\t\\t\\t+Alignment 1->2 density per synaptic vesicle: ' + str(tot_ctrl_denv12))\nprint('\\t\\t\\t+Alignment 1->2 density per tether: ' + str(tot_ctrl_dent12))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_ctrl_dent12, dent_ctrl_sims12)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_ctrl_dent12, dent_ctrl_sims212)))\nprint('')\nprint('\\t\\t\\t+Number of alignments 1->2 found for STIM: ' + str(tot_stim_nc12))\nprint('\\t\\t\\t+Alignment 1->2 density per pre-synaptic membrane volume: ' + str(tot_stim_den12))\nprint('\\t\\t\\t+Alignment 1->2 density per synaptic vesicle: ' + str(tot_stim_denv12))\nprint('\\t\\t\\t+Alignment 1->2 density per tether: ' + str(tot_stim_dent12))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_stim_dent12, dent_stim_sims12)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_stim_dent12, dent_stim_sims212)))\nprint('\\n')\nprint('\\t\\t\\t+Number of alignments 1->3 found: ' + str(tot_nc13))\nprint('\\t\\t\\t+Alignment 1->3 density per pre-synaptic membrane volume: ' + str(tot_den13))\nprint('\\t\\t\\t+Alignment 1->3 density per synaptic vesicle: ' + str(tot_denv13))\nprint('\\t\\t\\t+Column density per tether: ' + str(tot_dent13))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_dent13, dent_sims13)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_dent13, dent_sims213)))\nprint('')\nprint('\\t\\t\\t+Number of alignments 1->3 found for CTRL: ' + str(tot_ctrl_nc13))\nprint('\\t\\t\\t+Alignment 1->3 density per pre-synaptic membrane volume: ' + str(tot_ctrl_den13))\nprint('\\t\\t\\t+Alignment 1->3 density per synaptic vesicle: ' + str(tot_ctrl_denv13))\nprint('\\t\\t\\t+Alignment 1->3 density per tether: ' + str(tot_ctrl_dent13))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_ctrl_dent13, dent_ctrl_sims13)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_ctrl_dent13, dent_ctrl_sims213)))\nprint('')\nprint('\\t\\t\\t+Number of alignments 1->3 found for STIM: ' + str(tot_stim_nc13))\nprint('\\t\\t\\t+Alignment 1->3 density per pre-synaptic membrane volume: ' + str(tot_stim_den13))\nprint('\\t\\t\\t+Alignment 1->3 density per synaptic vesicle: ' + str(tot_stim_denv13))\nprint('\\t\\t\\t+Alignment 1->3 density per tether: ' + str(tot_stim_dent13))\nprint('\\t\\t\\t\\t*P-value (SIMULATED): ' + str(compute_pval(tot_stim_dent13, dent_stim_sims13)))\nprint('\\t\\t\\t\\t*P-value (SIMULATED\\'): ' + str(compute_pval(tot_stim_dent13, dent_stim_sims213)))\nprint('')\nprint('Successfully terminated. (' + time.strftime(\"%c\") + ')')\n", "\"\"\"\n\n Script for extracting an analyzing a GraphMCF with a segmented membrane\n\n Input: - A STAR file with a list of (sub-)tomograms to process:\n\t \t+ Density map tomogram\n \t+ Segmentation tomogram\n - Graph input parameters\n\n Output: - A STAR file with the (sub-)tomograms and their correspoing graphs\n (MbGraphMCF object)\n - Additional files for visualization\n\n\"\"\"\n\n__author__ = 'Antonio Martinez-Sanchez'\n\n# ################ Package import\n\nimport time\nimport pyseg as ps\nimport scipy as sp\nimport os\nimport numpy as np\n\ntry:\n import pickle as pickle\nexcept:\n import pickle\n\n########## Global variables\n\n# Membrane segmentation: 1-mb, 2-cito, 3-ext\nSEG_MB = 1\nSEG_MB_IN = 2\nSEG_MB_OUT = 3\nSEG_TAG = '_seg'\n\n########################################################################################\n# INPUT PARAMETERS\n########################################################################################\n\n####### Input data\n\nROOT_PATH = '../../../..' # Data path\n\n# Input STAR file with segmentations\nin_star = ROOT_PATH + '/data/tutorials/synth_sumb/segs/test_1_seg.star'\n\n####### Output data\n\noutput_dir = ROOT_PATH + '/data/tutorials/synth_sumb/graphs'\n\n####### GraphMCF perameter\n\nres = 1.048 # nm/pix\ns_sig = 0.8 # 1.5\nv_den = 0.0035 # 0.005 # 0.0025 # nm^3\nve_ratio = 4 # 2\nmax_len = 20 # 15 # 30 # nm\n\n####### Advanced parameters\n\n# nsig = 0.01\ncsig = 0.01\nang_rot = None\nang_tilt = None\nnstd = 10 # 3\nsmooth = 3\nmb_dst_off = 0. # nm\nDILATE_NITER = 2 # pix\ndo_clahe = False # True\n\n####### Graph density thresholds\n\nv_prop = None # ps.globals.STR_FIELD_VALUE # In None topological simplification\ne_prop = ps.globals.STR_FIELD_VALUE # ps.globals.STR_FIELD_VALUE_EQ # ps.globals.STR_VERT_DST\nv_mode = None # 'low'\ne_mode = 'low'\nprop_topo = ps.globals.STR_FIELD_VALUE # ps.globals.STR_FIELD_VALUE_EQ # None is ps.globals.STR_FIELD_VALUE\n\n########################################################################################\n# MAIN ROUTINE\n########################################################################################\n\n# Print initial message\nprint('Extracting GraphMCF and NetFilament objects from tomograms')\nprint('\\tAuthor: ' + __author__)\nprint('\\tDate: ' + time.strftime(\"%c\") + '\\n')\nprint('Options:')\n# print '\\tDisPerSe persistence threshold (nsig): ' + str(nsig)\nprint('\\tSTAR file with the segmentations: ' + str(in_star))\nprint('\\tDisPerSe persistence threshold (csig): ' + str(csig))\nif ang_rot is not None:\n print('Missing wedge edge compensation (rot, tilt): (' + str(ang_rot) + ', ' + str(ang_tilt) + ')')\nprint('\\tSigma for gaussian pre-processing: ' + str(s_sig))\nprint('\\tSigma for contrast enhancement: ' + str(nstd))\nprint('\\tSkeleton smoothing factor: ' + str(smooth))\nprint('\\tData resolution: ' + str(res) + ' nm/pixel')\nprint('\\tMask offset: ' + str(mb_dst_off) + ' nm')\nprint('\\tOutput directory: ' + output_dir)\nprint('Graph density thresholds:')\nif v_prop is None:\n print('\\tTarget vertex density (membrane) ' + str(v_den) + ' vertex/nm^3 for topological simplification')\nelse:\n print('\\tTarget vertex density (membrane) ' + str(\n v_den) + ' vertex/nm^3 for property ' + v_prop + ' with mode ' + v_mode)\nprint('\\tTarget edge/vertex ratio (non membrane) ' + str(ve_ratio) + ' for property ' + e_prop + ' with mode ' + e_mode)\nif do_clahe:\n print('\\t-Computing CLAHE.')\nprint('')\n\nprint('Paring input star file...')\nstar = ps.sub.Star()\nstar.load(in_star)\nin_seg_l = star.get_column_data('_psSegImage')\nin_tomo_l = star.get_column_data('_rlnImageName')\nstar.add_column('_psGhMCFPickle')\n\n# Loop for processing the input data\nprint('Running main loop: ')\nfor (row, input_seg, input_tomo) in zip(list(range(star.get_nrows())), in_seg_l, in_tomo_l):\n\n print('\\tSub-volume to process found: ' + input_tomo)\n print('\\tComputing paths for ' + input_tomo + ' ...')\n path, stem_tomo = os.path.split(input_tomo)\n stem_pkl, _ = os.path.splitext(stem_tomo)\n input_file = output_dir + '/' + stem_pkl + '_g' + str(s_sig) + '.fits'\n _, stem = os.path.split(input_file)\n stem, _ = os.path.splitext(stem)\n\n print('\\tLoading input data: ' + stem_tomo)\n tomo = ps.disperse_io.load_tomo(input_tomo).astype(np.float32)\n segh = ps.disperse_io.load_tomo(input_seg)\n\n print('\\tComputing distance, mask and segmentation tomograms...')\n tomod = ps.disperse_io.seg_dist_trans(segh == SEG_MB) * res\n maskh = np.ones(shape=segh.shape, dtype=np.int)\n maskh[DILATE_NITER:-DILATE_NITER, DILATE_NITER:-DILATE_NITER, DILATE_NITER:-DILATE_NITER] = 0\n mask = np.asarray(tomod > (max_len + mb_dst_off + 2 * DILATE_NITER * res), dtype=np.int)\n maskh += mask\n maskh += (segh == 0)\n mask = np.asarray(maskh > 0, dtype=np.float32)\n # input_msk = output_dir + '/' + stem + '_mask.mrc'\n # ps.disperse_io.save_numpy(mask, input_msk)\n input_msk = output_dir + '/' + stem + '_mask.fits'\n ps.disperse_io.save_numpy(mask.transpose(), input_msk)\n mask_den = np.asarray(tomod <= mb_dst_off, dtype=np.bool)\n # input_msk = output_dir + '/' + stem + '_mb_mask.mrc'\n # ps.disperse_io.save_numpy(mask_den, input_msk)\n\n print('\\tSmoothing input tomogram (s=' + str(s_sig) + ')...')\n density = sp.ndimage.filters.gaussian_filter(tomo, s_sig)\n density = ps.globals.cont_en_std(density, nstd=nstd, lb=0, ub=1)\n ps.disperse_io.save_numpy(tomo, output_dir + '/' + stem_pkl + '.vti')\n ps.disperse_io.save_numpy(density.transpose(), input_file)\n ps.disperse_io.save_numpy(density, output_dir + '/' + stem + '.vti')\n\n print('\\tInitializing DisPerSe...')\n work_dir = output_dir + '/disperse'\n disperse = ps.disperse_io.DisPerSe(input_file, work_dir)\n try:\n disperse.clean_work_dir()\n # except ps.pexceptions.PySegInputWarning as e:\n # print e.get_message()\n except Warning:\n print('Jol!!!')\n\n # Manifolds for descending fields with the inverted image\n disperse.set_manifolds('J0a')\n # Down skeleton\n disperse.set_dump_arcs(-1)\n # disperse.set_nsig_cut(nsig)\n rcut = round(density[mask_den].std() * csig, 4)\n print('\\tPersistence cut thereshold set to: ' + str(rcut) + ' grey level')\n disperse.set_cut(rcut)\n disperse.set_mask(input_msk)\n disperse.set_smooth(smooth)\n\n print('\\tRunning DisPerSe...')\n disperse.mse(no_cut=False, inv=False)\n skel = disperse.get_skel()\n manifolds = disperse.get_manifolds(no_cut=False, inv=False)\n\n # Build the GraphMCF for the membrane\n print('\\tBuilding MCF graph...')\n graph = ps.mb.MbGraphMCF(skel, manifolds, density, segh)\n graph.set_resolution(res)\n graph.build_from_skel(basic_props=False)\n graph.filter_self_edges()\n graph.filter_repeated_edges()\n\n print('\\tFiltering nodes close to mask border...')\n mask = sp.ndimage.morphology.binary_dilation(mask, iterations=DILATE_NITER)\n for v in graph.get_vertices_list():\n x, y, z = graph.get_vertex_coords(v)\n if mask[int(round(x)), int(round(y)), int(round(z))]:\n graph.remove_vertex(v)\n print('\\tBuilding geometry...')\n graph.build_vertex_geometry()\n\n if do_clahe:\n print('\\tCLAHE on filed_value_inv property...')\n graph.compute_edges_length(ps.globals.SGT_EDGE_LENGTH, 1, 1, 1, False)\n graph.clahe_field_value(max_geo_dist=50, N=256, clip_f=100., s_max=4.)\n\n print('\\tComputing vertices and edges properties...')\n graph.compute_vertices_dst()\n graph.compute_edge_filamentness()\n graph.add_prop_inv(prop_topo, edg=True)\n graph.compute_edge_affinity()\n\n print('\\tApplying general thresholds...')\n if ang_rot is not None:\n print('\\tDeleting edges in MW area...')\n graph.filter_mw_edges(ang_rot, ang_tilt)\n\n print('\\tComputing graph global statistics (before simplification)...')\n nvv, nev, nepv = graph.compute_global_stat(mask=mask_den)\n print('\\t\\t-Vertex density: ' + str(round(nvv, 5)) + ' nm^3')\n print('\\t\\t-Edge density: ' + str(round(nev, 5)) + ' nm^3')\n print('\\t\\t-Edge/Vertex ratio: ' + str(round(nepv, 5)))\n\n print('\\tGraph density simplification for vertices...')\n if prop_topo != ps.globals.STR_FIELD_VALUE:\n print('\\t\\tProperty used: ' + prop_topo)\n graph.set_pair_prop(prop_topo)\n try:\n graph.graph_density_simp_ref(mask=np.asarray(mask_den, dtype=np.int), v_den=v_den,\n v_prop=v_prop, v_mode=v_mode)\n except ps.pexceptions.PySegInputWarning as e:\n print('WARNING: graph density simplification failed:')\n print('\\t-' + e.get_message())\n\n print('\\tGraph density simplification for edges in the membrane...')\n nvv, nev, nepv = graph.compute_global_stat(mask=mask_den)\n if nepv > ve_ratio:\n e_den = nvv * ve_ratio\n hold_e_prop = e_prop\n graph.graph_density_simp_ref(mask=np.asarray(mask_den, dtype=np.int), e_den=e_den,\n e_prop=hold_e_prop, e_mode=e_mode, fit=True)\n\n print('\\tComputing graph global statistics (after simplification)...')\n nvv, _, _ = graph.compute_global_stat(mask=mask_den)\n _, nev_mb, nepv_mb = graph.compute_global_stat(mask=mask_den)\n print('\\t\\t-Vertex density (membrane): ' + str(round(nvv, 5)) + ' nm^3')\n print('\\t\\t-Edge density (membrane):' + str(round(nev_mb, 5)) + ' nm^3')\n print('\\t\\t-Edge/Vertex ratio (membrane): ' + str(round(nepv_mb, 5)))\n print('\\tComputing graph properties (2)...')\n graph.compute_mb_geo(update=True)\n graph.compute_mb_eu_dst()\n graph.compute_edge_curvatures()\n graph.compute_edges_length(ps.globals.SGT_EDGE_LENGTH, 1, 1, 1, False)\n graph.compute_vertices_dst()\n graph.compute_edge_filamentness()\n graph.compute_edge_affinity()\n\n print('\\tSaving intermediate graphs...')\n ps.disperse_io.save_vtp(graph.get_vtp(av_mode=True, edges=True),\n output_dir + '/' + stem + '_edges.vtp')\n ps.disperse_io.save_vtp(graph.get_vtp(av_mode=False, edges=True),\n output_dir + '/' + stem + '_edges_2.vtp')\n # ps.disperse_io.save_vtp(graph.get_scheme_vtp(nodes=True, edges=True),\n # output_dir + '/' + stem + '_sch.vtp')\n\n out_pkl = output_dir + '/' + stem_pkl + '.pkl'\n print('\\tPickling the graph as: ' + out_pkl)\n graph.pickle(out_pkl)\n star.set_element('_psGhMCFPickle', row, out_pkl)\n\nout_star = output_dir + '/' + os.path.splitext(os.path.split(in_star)[1])[0] + '_mb_graph.star'\nprint('\\tStoring output STAR file in: ' + out_star)\nstar.store(out_star)\n\nprint('Terminated. (' + time.strftime(\"%c\") + ')')\n", "'''\nClasses for representing tomograms with segmentations\n\n'''\n\n\nimport os\nimport copy\nimport numpy as np\nimport scipy as sp\nfrom shutil import rmtree\nfrom .utils import *\nfrom pyorg import pexceptions, sub, disperse_io\nfrom pyorg.globals.utils import unpickle_obj\nfrom pyorg import globals as gl\ntry:\n import pickle as pickle\nexcept:\n import pickle\n\n__author__ = 'Antonio Martinez-Sanchez'\n\n##### Global variables\n\nNM3_TO_UM3 = 1e-9\n\n# GLOBAL FUNCTIONS\n\n# Clean an directory contents (directory is preserved)\n# dir: directory path\ndef clean_dir(dir):\n for root, dirs, files in os.walk(dir):\n for f in files:\n os.unlink(os.path.join(root, f))\n for d in dirs:\n rmtree(os.path.join(root, d))\n\n# PARALLEL PROCESSES\n\n\n# CLASSES\n\n############################################################################\n# Class for a Segmentation: set of voxel in a tomogram\n#\nclass Segmentation(object):\n\n def __init__(self, tomo, lbl):\n \"\"\"\n :param tomo: tomogram which contains the segmentation\n :param lbl: label for the segmentation\n \"\"\"\n\n # Input parsing\n self.__ids = np.where(tomo == lbl)\n self.__vcount = len(self.__ids[0])\n assert self.__vcount > 0\n self.__lbl = lbl\n\n # Pre-compute bounds for accelerate computations\n self.__bounds = np.zeros(shape=6, dtype=np.float32)\n self.__update_bounds()\n\n #### Set/Get functionality\n\n def get_ids(self):\n return self.__ids\n\n def get_label(self):\n return self.__lbl\n\n def get_voxels_count(self):\n \"\"\"\n :return: the number of voxel in the segmentation\n \"\"\"\n return self.__vcount\n\n def get_bounds(self):\n \"\"\"\n :return: surface bounds (x_min, x_max, y_min, y_max, z_min, z_max) as array\n \"\"\"\n return self.__bounds\n\n #### External functionality\n\n def bound_in_bounds(self, bounds):\n \"\"\"\n Check if the object's bound are at least partially in another bound\n :param bounds: input bound\n :return:\n \"\"\"\n x_over, y_over, z_over = True, True, True\n if (self.__bounds[0] > bounds[1]) or (self.__bounds[1] < bounds[0]):\n x_over = False\n if (self.__bounds[2] > bounds[3]) or (self.__bounds[3] < bounds[2]):\n y_over = False\n if (self.__bounds[4] > bounds[5]) or (self.__bounds[5] < bounds[4]):\n y_over = False\n return x_over and y_over and z_over\n\n def point_in_bounds(self, point):\n \"\"\"\n Check if a point within filament's bounds\n :param point: point to check\n :return:\n \"\"\"\n x_over, y_over, z_over = True, True, True\n if (self.__bounds[0] > point[0]) or (self.__bounds[1] < point[0]):\n x_over = False\n if (self.__bounds[2] > point[1]) or (self.__bounds[3] < point[1]):\n y_over = False\n if (self.__bounds[4] > point[2]) or (self.__bounds[5] < point[2]):\n y_over = False\n return x_over and y_over and z_over\n\n def pickle(self, fname):\n \"\"\"\n VTK attributes requires a special treatment during pickling\n :param fname: file name ended with .pkl\n :return:\n \"\"\"\n\n # Dump pickable objects and store the file names of the unpickable objects\n stem, ext = os.path.splitext(fname)\n self.__vtp_fname = stem + '_curve.vtp'\n pkl_f = open(fname, 'w')\n try:\n pickle.dump(self, pkl_f)\n finally:\n pkl_f.close()\n\n # INTERNAL FUNCTIONALITY AREA\n\n def __update_bounds(self):\n self.__bounds[0], self.__bounds[1] = self.__ids[0].min(), self.__ids[0].max()\n self.__bounds[2], self.__bounds[3] = self.__ids[1].min(), self.__ids[1].max()\n self.__bounds[4], self.__bounds[5] = self.__ids[2].min(), self.__ids[2].max()\n\n\n############################################################################\n# Class for a OMSegmentation: oriented membrane segmentation.\n# Contains two segmentations, one with the membrane the other with the lumen\n#\nclass OMSegmentation(object):\n\n def __init__(self, tomo_mb, tomo_lm, lbl):\n \"\"\"\n :param tomo_mb: tomogram with the membrane (None is allowed)\n :param tomo_lm: tomogram with the lumen\n :param lbl:\n \"\"\"\n\n # Input parsing\n self.__ids_lm = np.where(tomo_lm == lbl)\n self.__vcount_lm = len(self.__ids_lm[0])\n self.__lbl = lbl\n assert self.__vcount_lm > 0\n if tomo_mb is None:\n self.__ids_mb = self.__ids_lm\n self.__vcount_mb = self.__vcount_lm\n else:\n self.__ids_mb = np.where(tomo_mb == lbl)\n self.__vcount_mb = len(self.__ids_mb[0])\n assert self.__vcount_mb > 0\n\n # Pre-compute bounds for accelerate computations\n self.__bounds = np.zeros(shape=6, dtype=np.float32)\n self.__update_bounds()\n\n #### Set/Get functionality\n\n def get_label(self):\n \"\"\"\n :return: an integer label\n \"\"\"\n return self.__lbl\n\n def get_ids(self, mode='lm'):\n \"\"\"\n :param mode: 'mb' or 'lumen' ids\n :return: segmented voxel indices an array with 4 dimension (N,X,Y,Z)\n \"\"\"\n assert (mode == 'mb') or (mode == 'lm')\n if mode == 'mb':\n return self.__ids_mb\n elif mode == 'lm':\n return self.__ids_lm\n\n def get_voxels_count(self, mode='mb'):\n \"\"\"\n :param mode: to count 'mb' or 'lumen' voxels\n :return: the number of voxel in the segmentation\n \"\"\"\n assert (mode == 'mb') or (mode == 'lm')\n if mode == 'mb':\n return self.__vcount_mb\n elif mode == 'lm':\n return self.__vcount_lm\n\n def get_bounds(self):\n \"\"\"\n :return: surface bounds (x_min, x_max, y_min, y_max, z_min, z_max) as array\n \"\"\"\n return self.__bounds\n\n #### External functionality\n\n def bound_in_bounds(self, bounds):\n \"\"\"\n Check if the object's bound are at least partially in another bound\n :param bounds: input bound\n :return:\n \"\"\"\n hold_bounds = self.__bounds\n x_over, y_over, z_over = True, True, True\n if (hold_bounds[0] > bounds[1]) or (hold_bounds[1] < bounds[0]):\n x_over = False\n if (hold_bounds[2] > bounds[3]) or (hold_bounds[3] < bounds[2]):\n y_over = False\n if (hold_bounds[4] > bounds[5]) or (hold_bounds[5] < bounds[4]):\n y_over = False\n return x_over and y_over and z_over\n\n def point_in_bounds(self, point):\n \"\"\"\n Check if a point within filament's bounds\n :param point: point to check\n :return:\n \"\"\"\n hold_bounds = self.__bounds\n x_over, y_over, z_over = True, True, True\n if (hold_bounds[0] > point[0]) or (hold_bounds[1] < point[0]):\n x_over = False\n if (hold_bounds[2] > point[1]) or (hold_bounds[3] < point[1]):\n y_over = False\n if (hold_bounds[4] > point[2]) or (hold_bounds[5] < point[2]):\n y_over = False\n return x_over and y_over and z_over\n\n def pickle(self, fname):\n \"\"\"\n VTK attributes requires a special treatment during pickling\n :param fname: file name ended with .pkl\n :return:\n \"\"\"\n\n # Dump pickable objects and store the file names of the unpickable objects\n stem, ext = os.path.splitext(fname)\n self.__vtp_fname = stem + '_curve.vtp'\n pkl_f = open(fname, 'w')\n try:\n pickle.dump(self, pkl_f)\n finally:\n pkl_f.close()\n\n # INTERNAL FUNCTIONALITY AREA\n\n def __update_bounds(self):\n bounds_mb, bounds_lm = np.zeros(shape=6, dtype=np.float32), np.zeros(shape=6, dtype=np.float32)\n bounds_mb[0], bounds_mb[1] = self.__ids_mb[0].min(), self.__ids_mb[0].max()\n bounds_mb[2], bounds_mb[3] = self.__ids_mb[1].min(), self.__ids_mb[1].max()\n bounds_mb[4], bounds_mb[5] = self.__ids_mb[2].min(), self.__ids_mb[2].max()\n bounds_lm[0], bounds_lm[1] = self.__ids_lm[0].min(), self.__ids_lm[0].max()\n bounds_lm[2], bounds_lm[3] = self.__ids_lm[1].min(), self.__ids_lm[1].max()\n bounds_lm[4], bounds_lm[5] = self.__ids_lm[2].min(), self.__ids_lm[2].max()\n if bounds_mb[0] < bounds_lm[0]:\n self.__bounds[0] = bounds_mb[0]\n else:\n self.__bounds[0] = bounds_lm[0]\n if bounds_mb[1] < bounds_lm[1]:\n self.__bounds[1] = bounds_mb[1]\n else:\n self.__bounds[1] = bounds_lm[1]\n if bounds_mb[2] < bounds_lm[2]:\n self.__bounds[2] = bounds_mb[2]\n else:\n self.__bounds[2] = bounds_lm[2]\n if bounds_mb[3] < bounds_lm[3]:\n self.__bounds[3] = bounds_mb[3]\n else:\n self.__bounds[3] = bounds_lm[3]\n if bounds_mb[4] < bounds_lm[4]:\n self.__bounds[4] = bounds_mb[4]\n else:\n self.__bounds[4] = bounds_lm[4]\n if bounds_mb[5] < bounds_lm[5]:\n self.__bounds[5] = bounds_mb[5]\n else:\n self.__bounds[5] = bounds_lm[5]\n\n\n############################################################################\n# Class for tomograms with oriented membrane segmentations\n#\nclass TomoOMSegmentations(object):\n\n def __init__(self, name, voi_mb=None, voi_lm=None, max_dst=0, res=1):\n \"\"\"\n :param name: name to identify the tomogram\n :param voi_mb: if None (default) the membrane tomogram is loaded from tomo_fname, otherwise this is actually\n the input tomogram\n :param voi_lm: if None (default) the lumen tomogram is loaded from tomo_fname, otherwise this is actually\n the input tomogram\n :param max_dst: maximum distance to lumen border for membrane segmentation (in segmentation pixels)\n :param res: input value\n \"\"\"\n\n # Input parsing\n if not isinstance(name, str):\n error_msg = 'Input is not a string.'\n raise pexceptions.PySegInputError(expr='__init__ (TomoOMSegmentations)', msg=error_msg)\n if (voi_mb is not None) and (not isinstance(voi_mb, np.ndarray)):\n error_msg = 'Input VOI for membranes must be an numpy.ndarray.'\n raise pexceptions.PySegInputError(expr='__init__ (TomoOMSegmentations)', msg=error_msg)\n if (voi_lm is not None) and (not isinstance(voi_lm, np.ndarray)):\n error_msg = 'Input VOI for lumen must be an numpy.ndarray.'\n raise pexceptions.PySegInputError(expr='__init__ (TomoOMSegmentations)', msg=error_msg)\n self.__name = name\n self.__segs = list()\n\n # Create the lumen's label field\n if voi_mb.shape != voi_lm.shape:\n error_msg = 'Input tomograms for membranes and lumen must have the same sizes.'\n raise pexceptions.PySegInputError(expr='__init__ (TomoOMSegmentations)', msg=error_msg)\n self.__lbl_voi_lm, nlbls = sp.ndimage.label(voi_lm, structure=np.ones(shape=(3, 3, 3)))\n lbls_lm = list(range(1, nlbls+1))\n # disperse_io.save_numpy(self.__lbl_voi_lm, '/fs/pool/pool-ruben/antonio/filaments/ltomos_omsegs/test/hold_lm.mrc')\n hold_lm = sp.ndimage.morphology.binary_dilation(voi_lm > 0)\n dst_field_lm, dst_ids_lm = sp.ndimage.morphology.distance_transform_edt(hold_lm, return_distances=True,\n return_indices=True)\n # hold_lm = sp.ndimage.morphology.binary_dilation(voi_lm == 0)\n # dst_field_inv_lm, dst_ids_inv_lm = sp.ndimage.morphology.distance_transform_edt(hold_lm, return_distances=True,\n # return_indices=True)\n\n # Set lumen labels to membrane segmentation\n mb_ids = np.where(voi_mb)\n self.__lbl_voi_mb = np.zeros(shape=voi_mb.shape, dtype=np.int32)\n for x, y, z in zip(mb_ids[0], mb_ids[1], mb_ids[2]):\n hold_dst = dst_field_lm[x, y, z]\n if (hold_dst > 0) and (hold_dst <= max_dst):\n x_idx, y_idx, z_idx = dst_ids_lm[:, x, y, z]\n x_l = x_idx - 2\n if x_l <= 0:\n x_l = 0\n x_h = x_idx + 3\n if x_h >= self.__lbl_voi_mb.shape[0]:\n x_h = self.__lbl_voi_mb.shape[0]\n y_l = y_idx - 2\n if y_l <= 0:\n y_l = 0\n y_h = y_idx + 3\n if y_h >= self.__lbl_voi_mb.shape[1]:\n y_h = self.__lbl_voi_mb.shape[1]\n z_l = z_idx - 2\n if z_l <= 0:\n z_l = 0\n z_h = z_idx + 3\n if z_h >= self.__lbl_voi_mb.shape[2]:\n z_h = self.__lbl_voi_mb.shape[2]\n hold_lbls_lm = self.__lbl_voi_lm[x_l:x_h, y_l:y_h, z_l:z_h]\n try:\n hold_lbl_lm = np.argmax(np.bincount(hold_lbls_lm[hold_lbls_lm > 0]))\n self.__lbl_voi_mb[x, y, z] = hold_lbl_lm\n except ValueError:\n pass # print 'jol 1'\n # else:\n # hold_dst_inv = dst_field_inv_lm[x, y, z]\n # if (hold_dst_inv > 0) and (hold_dst_inv <= max_dst):\n # x_idx, y_idx, z_idx = dst_ids_inv_lm[:, x, y, z]\n # x_l = x_idx - 2\n # if x_l <= 0:\n # x_l = 0\n # x_h = x_idx + 3\n # if x_h >= self.__lbl_voi_mb.shape[0]:\n # x_h = self.__lbl_voi_mb.shape[0]\n # y_l = y_idx - 2\n # if y_l <= 0:\n # y_l = 0\n # y_h = y_idx + 3\n # if y_h >= self.__lbl_voi_mb.shape[1]:\n # y_h = self.__lbl_voi_mb.shape[1]\n # z_l = z_idx - 2\n # if z_l <= 0:\n # z_l = 0\n # z_h = z_idx + 3\n # if z_h >= self.__lbl_voi_mb.shape[2]:\n # z_h = self.__lbl_voi_mb.shape[2]\n # hold_lbls_lm = self.__lbl_voi_lm[x_l:x_h, y_l:y_h, z_l:z_h]\n # try:\n # hold_lbl_lm = np.argmax(np.bincount(hold_lbls_lm[hold_lbls_lm > 0]))\n # self.__lbl_voi_mb[x, y, z] = hold_lbl_lm\n # except ValueError:\n # pass # print 'Jol 2'\n # else:\n # pass # print 'Jol 3'\n\n # Create the segmentations\n for lbl_lm in lbls_lm:\n try:\n self.__segs.append(OMSegmentation(self.__lbl_voi_mb, self.__lbl_voi_lm, lbl_lm))\n except AssertionError:\n continue\n\n # Pixel size settings\n self.set_resolution(res)\n\n # GET/SET AREA\n\n def set_resolution(self, res):\n \"\"\"\n Set resolution in nm/pixel\n :param res: input value\n :return:\n \"\"\"\n assert res > 0\n self.__res = res\n self.__res_3 = self.__res * self.__res * self.__res\n\n def get_voi(self, mode='mb'):\n \"\"\"\n Get the tomograms with the segmentations VOI\n :param mode: 'mb' membrane, 'lm' lumen, 'mb-lm' membrane and lumen fused\n :return: a binary ndarray\n \"\"\"\n if mode == 'mb':\n return self.__lbl_voi_mb > 0\n elif mode == 'lm':\n return self.__lbl_voi_lm > 0\n elif mode == 'mb-lm':\n return (self.__voi_mb + self.__voi_lm) > 0\n else:\n error_msg = 'Input mode not valid: ' + str(mode)\n raise pexceptions.PySegInputError(expr='get_voi (TomoOMSegmentations)', msg=error_msg)\n\n def get_lbl_voi(self, mode='mb'):\n \"\"\"\n Get the labeled tomograms with the segmentations\n :param mode: 'mb' membrane, 'lm' lumen\n :return: an ndarray with the segmentations labeled\n \"\"\"\n if mode == 'mb':\n return self.__lbl_voi_mb\n elif mode == 'lm':\n return self.__lbl_voi_lm\n else:\n error_msg = 'Input mode not valid: ' + str(mode)\n raise pexceptions.PySegInputError(expr='get_voi (TomoOMSegmentations)', msg=error_msg)\n\n def get_tomo_name(self):\n return self.__name\n\n def get_segmentations(self):\n return self.__segs\n\n def get_num_segmentations(self):\n return len(self.__segs)\n\n def get_tomo_vol(self):\n \"\"\"\n Compute the volume of the whole tomogram (um**3)\n :return: a float value\n \"\"\"\n return np.asarray(self.__lbl_voi_mb.shape, dtype=np.float).prod() \\\n * self.__res * self.__res * self.__res * NM3_TO_UM3\n\n # EXTERNAL FUNCTIONALITY AREA\n\n def delete_segmentation(self, seg_ids):\n \"\"\"\n Remove segmentations from the list\n :param seg_ids: integer ids of the segmentations (their position in the current list of segmentations)\n :return: None\n \"\"\"\n # Loop for keeping survivors\n hold_segs = list()\n for i in range(len(self.__segs)):\n if not i in seg_ids:\n hold_segs.append(self.__segs[i])\n\n # Updating the list of segmentations\n self.__segs = hold_segs\n\n def pickle(self, fname):\n \"\"\"\n :param fname: file name ended with .pkl\n :return:\n \"\"\"\n pkl_f = open(fname, 'w')\n try:\n pickle.dump(self, pkl_f)\n finally:\n pkl_f.close()\n\n def compute_voi_volume(self, mode='mb'):\n \"\"\"\n Compute voi volume in voxels\n :param mode: 'mb' membrane, 'lm' lumen, 'mb-lm' membrane and lumen fused\n :return: the volume (um**3) for each organelle\n \"\"\"\n if mode == 'mb':\n return self.__voi_mb.sum() * self.__res_3 * NM3_TO_UM3\n elif mode == 'lm':\n return self.__voi_lm.sum() * self.__res_3 * NM3_TO_UM3\n elif mode == 'mb-lm':\n return (self.__voi_mb.sum() + self.__voi_lm.sum()) * self.__res_3 * NM3_TO_UM3\n else:\n error_msg = 'Input mode not valid: ' + str(mode)\n raise pexceptions.PySegInputError(expr='compute_voi_volume (TomoOMSegmentations)', msg=error_msg)\n\n def compute_seg_volumes(self, mode='mb'):\n \"\"\"\n Compute the volumes for each segmentation\n :param mode: 'mb' membrane, 'lm' lumen\n :return: an array with the volume (um**3) for each organelle\n \"\"\"\n vols = np.zeros(shape=len(self.__segs), dtype=np.float32)\n for i, seg in enumerate(self.__segs):\n vols[i] = seg.get_voxels_count(mode) * self.__res * self.__res * self.__res * NM3_TO_UM3\n return vols\n\n def compute_om_seg_dsts(self):\n \"\"\"\n Computes the distance among the different oriented membrane segmentations\n :return: a 3D array (tomogram segmemntation) where each voxels encodes the distance to the closes membrane\n segmentation, background pixels are set to zero.\n \"\"\"\n\n # Initialization\n dsts_field = np.zeros(shape=self.__lbl_voi_lm.shape, dtype=np.float32)\n\n # Loop for segmentations\n for seg in self.__segs:\n hold_lbl_voi = (self.__lbl_voi_lm == seg.get_label()) + (self.__lbl_voi_lm == 0)\n hold_dsts = sp.ndimage.morphology.distance_transform_edt(hold_lbl_voi, return_distances=True,\n return_indices=False)\n mb_ids = self.__lbl_voi_mb == seg.get_label()\n dsts_field[mb_ids] = hold_dsts[mb_ids]\n\n return dsts_field * self.__res\n\n # INTERNAL FUNCTIONALITY AREA\n\n\n############################################################################\n# Class for a list of tomograms with oriented membrane segmentations\n#\nclass ListTomoOMSegmentations(object):\n\n def __init__(self):\n self.__tomos = dict()\n # For pickling\n self.__pkls = None\n self.__res = 1\n\n # EXTERNAL FUNCTIONALITY\n\n def set_resolution(self, res):\n \"\"\"\n Set resolution in nm/pixel\n :param res: input value\n :return:\n \"\"\"\n for tomo in self.__tomos.values():\n tomo.set_resolution(res)\n self.__res = res\n\n def get_tomos(self):\n return self.__tomos\n\n def get_num_segmentations(self):\n total = 0\n for tomo in self.__tomos.values():\n total += tomo.get_num_filaments()\n return total\n\n def get_num_segmentations_dict(self):\n nsegs = dict()\n for key, tomo in zip(iter(self.__tomos.keys()), iter(self.__tomos.values())):\n nsegs[key] = tomo.get_num_segmentations()\n return nsegs\n\n def get_volumes_dict(self):\n vols = dict()\n for key, tomo in zip(iter(self.__tomos.keys()), iter(self.__tomos.values())):\n vols[key] = tomo.compute_voi_volume()\n return vols\n\n def get_tomo_name_list(self):\n return list(self.__tomos.keys())\n\n def get_tomo_list(self):\n return list(self.__tomos.values())\n\n def get_tomo_by_key(self, key):\n return self.__tomos[key]\n\n def add_tomo(self, tomo_fils):\n \"\"\"\n :param tomo_fils: TomoFilaments object to add to the list\n :return:\n \"\"\"\n # Input parsing\n tomo_fname = tomo_fils.get_tomo_fname()\n if tomo_fname in self.get_tomo_name_list():\n print('WARNING: tomo_surf (ListTomoOMSegmentations): tomogram ' + tomo_fname + ' was already inserted.')\n return\n # Adding the tomogram to the list and dictionaries\n self.__tomos[tomo_fname] = tomo_fils\n\n def del_tomo(self, tomo_key):\n \"\"\"\n Delete a TomoSurface entry in the list\n :param tomo_key: TomoFilament key\n :return:\n \"\"\"\n del self.__tomos[tomo_key]\n\n def insert_tomo(self, name, voi_mb=None, voi_lm=None, max_dst=0):\n \"\"\"\n :param name: name to identify the tomogram\n :param voi_mb: if None (default) the membrane tomogram is loaded from tomo_fname, otherwise this is actually\n the input tomogram\n :param voi_lm: if None (default) the lumen tomogram is loaded from tomo_fname, otherwise this is actually\n the input tomogram\n :param max_dst: maximum distance for membrane pixles to border inside the lumen (in segmentation pixels)\n :param lbls_lm: lists of labels with the lumen segmentations\n \"\"\"\n self.__tomos[name] = TomoOMSegmentations(name, voi_mb=voi_mb, voi_lm=voi_lm, max_dst=max_dst)\n\n def store_stars(self, out_stem, out_dir):\n \"\"\"\n Store the list of tomograms in STAR file and also the STAR files for every tomogram\n :param out_stem: string stem used for storing the STAR file for TomoOMSegmentation objects\n :param out_dir: output directory\n :return:\n \"\"\"\n\n # STAR file for the tomograms\n tomos_star = sub.Star()\n tomos_star.add_column('_omTomoSegmentation')\n\n # Tomograms loop\n for i, tomo_fname in enumerate(self.__tomos.keys()):\n\n # Pickling the tomogram\n tomo_dir = out_dir + '/tomo_' + str(i)\n if not os.path.exists(tomo_dir):\n os.makedirs(tomo_dir)\n tomo_stem = os.path.splitext(os.path.split(tomo_fname)[1])[0]\n pkl_file = tomo_dir + '/' + tomo_stem + '_tom.pkl'\n self.__tomos[tomo_fname].pickle(pkl_file)\n\n # Adding a new enter\n kwargs = {'_omTomoSegmentation': pkl_file}\n tomos_star.add_row(**kwargs)\n\n # Storing the tomogram STAR file\n tomos_star.store(out_dir + '/' + out_stem + '_toml.star')\n\n def store_segmentations(self, out_dir, mode='mb'):\n \"\"\"\n Store the filaments in a vtkPolyData per tomogram\n :param out_dir: output directory\n :param mode: 'mb' membrane, 'lm' lumen, 'mb-lm' membrane and lumen fused\n :return:\n \"\"\"\n # Tomograms loop\n for i, tomo_fname in enumerate(self.__tomos.keys()):\n\n tomo_stem = os.path.splitext(os.path.split(tomo_fname)[1])[0]\n\n # Storing\n disperse_io.save_numpy(self.__tomos[tomo_fname].gen_seg_tomo(mode=mode),\n out_dir + '/' + tomo_stem + '_oms.mrc')\n\n\n # fname: file name ended with .pkl\n def pickle(self, fname):\n # Pickling\n pkl_f = open(fname, 'w')\n try:\n pickle.dump(self, pkl_f)\n finally:\n pkl_f.close()\n\n def filter_by_segmentations_num(self, min_num_seg=1):\n \"\"\"\n Delete for list the tomogram with low segmentations\n :param min_num_segs: minimum number of particles, below the tomogram is deleted (default 1)\n :return:\n \"\"\"\n hold_dict = dict()\n for key, tomo in zip(iter(self.__tomos.keys()), iter(self.__tomos.values())):\n # print key + ': ' + str(tomo.get_num_filaments())\n if tomo.get_num_segmentations() >= min_num_seg:\n hold_dict[key] = tomo\n self.__tomos = hold_dict\n\n def clean_low_pouplated_tomos(self, n_keep):\n \"\"\"\n Clean tomogram with a low amount of particles\n :param n_keep: number of tomograms to, the one with the highest amount of particles\n :return:\n \"\"\"\n if (n_keep is None) or (n_keep < 0) or (n_keep >= len(list(self.__tomos.keys()))):\n return\n # Sorting loop\n n_segs = dict()\n for key, tomo in zip(iter(self.__tomos.keys()), iter(self.__tomos.values())):\n n_segs[key] = tomo.get_num_segmentations()\n pargs_sort = np.argsort(np.asarray(list(n_segs.values())))[::-1]\n keys = list(n_segs.keys())\n # Cleaning loop\n hold_dict = dict()\n for parg in pargs_sort[:n_keep]:\n key = keys[parg]\n hold_dict[key] = self.__tomos[key]\n self.__tomos = hold_dict\n\n def segmentations_by_tomos(self):\n \"\"\"\n :return: return a dictionary with the num of filaments by tomos\n \"\"\"\n keys = self.get_tomo_fname_list()\n segs = dict.fromkeys(keys)\n for key in keys:\n segs[key] = self.__tomos[key].get_num_segmentations()\n return segs\n\n def to_tomos_star(self, out_dir):\n \"\"\"\n Generates a STAR file with TomoOMSegmentations pickles\n :param out_dir: output directory for the pickles\n :return: a STAR file\n \"\"\"\n\n # Initialization\n star_tomo = sub.Star()\n star_tomo.add_column('_psPickleFile')\n\n # Tomograms loop\n for tomo in self.get_tomo_list():\n tkey = os.path.splitext(os.path.split(tomo.get_tomo_fname())[1])[0]\n out_pkl = out_dir + '/' + tkey + '_tp.pkl'\n tomo.pickle(out_pkl)\n # Insert the pickled tomo into the star file\n star_tomo.set_column_data('_psPickleFile', out_pkl)\n\n return star_tomo\n\n # INTERNAL FUNCTIONALITY AREA\n\n############################################################################\n# Class for a set of list tomograms with embedded filaments\n#\nclass SetListTomoOMSegmentations(object):\n\n def __init__(self):\n self.__lists = dict()\n\n # EXTERNAL FUNCTIONALITY\n\n def get_lists(self):\n return self.__lists\n\n def get_lists_by_key(self, key):\n return self.__lists[key]\n\n def get_key_from_short_key(self, short_key):\n for lkey in self.__lists.keys():\n fkey = os.path.split(lkey)[1]\n hold_key_idx = fkey.index('_')\n hold_key = fkey[:hold_key_idx]\n if short_key == hold_key:\n return lkey\n\n def get_lists_by_short_key(self, key):\n for lkey, list in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n if self.get_key_from_short_key(lkey) == key:\n return list\n\n def get_tomos_name(self):\n hold_list = list()\n for ltomos in list(self.get_lists().values()):\n hold_list += ltomos.get_tomo_name_list()\n return list(set(hold_list))\n\n def add_list_tomos(self, ltomos, list_name):\n \"\"\"\n Add a new ListTomoOMSegmentations to the set\n :param ltomos: input ListTomoOMSegmentations object\n :param list_name: string for naming the list\n :return:\n \"\"\"\n # Input parsing (compatible with older versions)\n if ltomos.__class__.__name__ != 'ListTomoOMSegmentations':\n error_msg = 'WARNING: add_tomo (SetListTomoOMSegmentations): ltomos input must be ListTomoParticles object.'\n raise pexceptions.PySegInputError(expr='add_tomo (SetListTomoOMSegmentations)', msg=error_msg)\n # Adding the list to the dictionary\n self.__lists[str(list_name)] = ltomos\n\n def get_set_tomos(self):\n \"\"\"\n :return: return a set with all tomos in all list\n \"\"\"\n tomos_l = list()\n for key, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n for tomo in ltomos.get_tomo_list():\n tomos_l.append(tomo.get_tomo_fname())\n return set(tomos_l)\n\n def segmentations_by_list(self):\n \"\"\"\n :return: Return a dictionary with the number of filaments by list\n \"\"\"\n segs = dict()\n for key, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n segs[key] = ltomos.get_num_segmentations()\n return segs\n\n def segmentations_by_tomos(self):\n \"\"\"\n :return: Return a dictionary with the number of filaments by tomogram\n \"\"\"\n segs = dict()\n for key_l, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n for tomo in ltomos.get_tomo_list():\n try:\n segs[tomo.get_tomo_fname()] += tomo.get_num_segmentations()\n except KeyError:\n segs[tomo.get_tomo_fname()] = tomo.get_num_segmentations()\n return segs\n\n def proportions_by_tomos(self):\n \"\"\"\n :return: Return a dictionary with the proportions for every tomogram\n \"\"\"\n segs = dict()\n for key_l, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n for tomo in ltomos.get_tomo_list():\n key_t = tomo.get_tomo_name()\n try:\n segs[key_t].append(tomo.get_num_segmentations())\n except KeyError:\n segs[key_t] = list()\n segs[key_t].append(tomo.get_num_segmentations())\n return segs\n\n def proportions_by_list(self):\n \"\"\"\n :return: Return a dictionary with the proportions for every tomogram\n \"\"\"\n # Initialization\n segs_list, segs_tomo = dict.fromkeys(list(self.__lists.keys())), dict.fromkeys(self.get_set_tomos())\n for key_t in segs_tomo.keys():\n segs_tomo[key_t] = 0\n for key_l in segs_list.keys():\n segs_list[key_l] = np.zeros(shape=len(list(segs_tomo.keys())))\n # Particles loop\n for key_l, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n for i, key_t in enumerate(segs_tomo.keys()):\n tomo = ltomos.get_tomo_by_key(key_t)\n hold_fils = tomo.get_num_segmentations()\n segs_tomo[key_t] += hold_fils\n segs_list[key_l][i] += hold_fils\n # Proportions loop\n for key_l in segs_list.keys():\n for i, tomo_nfils in enumerate(segs_tomo.values()):\n if tomo_nfils > 0:\n segs_list[key_l][i] /= tomo_nfils\n else:\n segs_list[key_l][i] = 0.\n return segs_list\n\n def pickle_tomo_star(self, out_star, out_dir_pkl):\n \"\"\"\n Generates a STAR file with the ListTomoOMSegmentations and pickes their TomoOMSegmentations\n :param out_star: output STAR file\n :param out_dir_pkl: output directory for the pickles\n :return: a STAR file\n \"\"\"\n\n # Initialization\n star_list = sub.Star()\n star_list.add_column('_psPickleFile')\n\n # Tomograms loop\n for lname, ltomo in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n lkey = os.path.splitext(os.path.split(lname)[1])[0]\n out_star, out_list_dir = out_dir_pkl + '/' + lkey + '_tf.star', out_dir_pkl + '/' + lkey + '_tf'\n clean_dir(out_list_dir)\n list_star = ltomo.to_tomo_star(out_list_dir)\n list_star.store(out_star)\n # Insert the pickled tomo into the star file\n star_list.set_column_data('_psPickleFile', out_star)\n\n star_list.store(out_star)\n\n def filter_by_segmentations_num_tomos(self, min_num_segs=1):\n \"\"\"\n Delete those tomograms with a number of filaments lower than an input value for any list\n :param min_num_segmentations: a number or a dict, the allows to specify different minimum number for each layer\n :return:\n \"\"\"\n\n # Computing total particles per tomogram loop\n if isinstance(min_num_segs, dict):\n tomos_dict = dict().fromkeys(self.get_set_tomos(), 0)\n for lkey, ltomos in zip(iter(self.__lists.keys()), iter(self.__lists.values())):\n hold_min = min_num_segs[lkey]\n for tomo in ltomos.get_tomo_list():\n if tomo.get_num_segmentations() >= hold_min:\n tomos_dict[tomo.get_tomo_fname()] += 1\n tomos_del = dict().fromkeys(self.get_set_tomos(), False)\n for key in tomos_dict.keys():\n if tomos_dict[key] < len(list(min_num_segs.keys())):\n tomos_del[key] = True\n else:\n tomos_del = dict().fromkeys(self.get_set_tomos(), False)\n for tkey in list(tomos_del.keys()):\n for ltomos in self.__lists.values():\n try:\n tomo = ltomos.get_tomo_by_key(tkey)\n except KeyError:\n continue\n if tomo.get_num_segmentations() < min_num_segs:\n tomos_del[tkey] = True\n\n # Deleting loop\n for ltomos in self.__lists.values():\n for tkey in list(tomos_del.keys()):\n if tomos_del[tkey]:\n try:\n ltomos.del_tomo(tkey)\n except KeyError:\n continue\n\n def filter_by_segmentations_num(self, min_num_segs=1):\n \"\"\"\n Delete for list the tomogram with low particles (considering all lists)\n :param min_num_segs: minimum number of particles, below that the tomogram is deleted (default 1)\n :return:\n \"\"\"\n\n # Computing total particles per tomogram loop\n hold_dict = dict()\n for ltomos in self.__lists.values():\n for tomo in ltomos.get_tomo_list():\n tkey, n_parts = tomo.get_tomo_fname(), tomo.get_num_segmentations()\n try:\n hold_dict[tkey] += n_parts\n except KeyError:\n hold_dict[tkey] = n_parts\n\n # Deleting loop\n for tkey, n_parts in zip(iter(hold_dict.keys()), iter(hold_dict.values())):\n if n_parts < min_num_segs:\n for ltomos in self.__lists.values():\n ltomos.del_tomo(tkey)\n", "\"\"\"\n\n Generate a synthetic set of microsomes with different membrane bound proteins\n\n Input: - Data set parameters:\n + Number of tomograms (one microsome each)\n + Tomogram size\n + Resolution (pixel size)\n + SNR range\n + Missing wedge (semi-angle in degrees or input file)\n + binning factor for segmentation an particle picking\n - Microsome parameters:\n + Membrane thickness (in nm)\n + Density model for each protein type inserted\n + Averaged number of particles per microsome and per model\n + Model for protein insertion, available: CSRV, SRPV, 2CCSRV\n\n Output: - Tomograms generated with one microsome each:\n + Full resolution\n + Binned counterpart\n - A STAR file pairing the originals and the binned tomograms\n\n\"\"\"\n\n################# Package import\n\nimport os\nimport sys\nimport time\nimport numpy as np\nimport scipy as sp\nimport multiprocessing as mp\nfrom pyorg import disperse_io, sub, spatial\nfrom pyorg.globals import *\n\n###### Global variables\n\n__author__ = 'Antonio Martinez-Sanchez'\n\n########################################################################################\n# PARAMETERS\n########################################################################################\n\nROOT_PATH = ''\n\n# Output directory\nout_dir = ROOT_PATH + ''\nout_stem = ''\n\n# Tomogram settings\ntm_nt = 10 # tomograms\ntm_size = (800, 800, 400) # pixels\ntm_res = 0.262 # nm/pixel\ntm_snr_rg = (0.01, 0.05)\ntm_wedge = 30 # semi-angle in degrees or input file\ntm_bin = 2\n\n# Microsome parameters\nmc_mbt = 5 # nm\nmc_mbs = 1.5 # nm\nmc_ip_min_dst = 15 # nm\n# By default 1st model has clusters randomly distributed of radius mc_1st_crad and 2nd clusters of size 2*mc_3rd_crad,\n# 3rd is CSRV distributed, 4th particles are 2CCSRV placed at an averaged distance of mc_4th_dst,\nmc_1st_crad = 50 # nm\nmc_c_jump_prob = 0.1\nmc_4th_dst = 20 # nm\nmc_in_models = ('', '', '', '', '', '', '', '')\nmc_avg_nparts = (20, 20, 20, 50, 50, 50, 30, 30)\nmc_3sg_nparts = 5\nmc_zh = 0\n\n########################################################################################\n# ADDITIONAL ROUTINES\n########################################################################################\n\n\ndef gen_mask_msome(shape, rad1, rad2):\n \"\"\"\n Generates a microsome mask\n :param shape: 3-tuple for the output tomogram\n :param rad1: radius 1 for the microsome\n :param rad2: radius 2 for the microsome\n :return: the generated microme\n \"\"\"\n dx, dy, dz = float(shape[0]), float(shape[1]), float(shape[2])\n dx2, dy2, dz2 = math.floor(.5 * dx), math.floor(.5 * dy), math.floor(.5 * dz)\n x_l, y_l, z_l = -dx2, -dy2, -dz2\n x_h, y_h, z_h = -dx2 + dx, -dy2 + dy, -dz2 + dz\n X, Y, Z = np.meshgrid(np.arange(x_l, x_h), np.arange(y_l, y_h), np.arange(z_l, z_h), indexing='xy')\n R = X*X + Y*Y + Z*Z\n return (R >= (rad1*rad1)) & (R <= (rad2*rad2))\n\n\ndef add_dmb_msome(tomo, rad, res, mb_t, mb_s):\n \"\"\"\n Add a double Gaussian layered membrane of a microsome to a tomogram\n :param tomo: tomogram where the membrane is added\n :param rad: microsome radius\n :param res: tomograms resolution (nm/px)\n :param mb_t: membrane thickness in nm\n :param mb_s: Gaussian sigma for each layer in nm\n :return: None\n \"\"\"\n\n # Input parsing\n t_v, s_v, rad_v = .5 * (mb_t / res), mb_s / res, rad / res\n rad1, rad2 = rad_v - t_v, rad_v + t_v\n g_cte = 2 * s_v * s_v\n s_v_2 = .5 * s_v\n g_cte_2 = 2 * s_v_2 * s_v_2\n\n # Getting membrane gray intensity from input tomogram\n tomo_bin = tomo > 0\n tomo_vals = tomo(tomo_bin)\n tomo_mn = tomo_vals.mean()\n\n # Generating the bilayer\n dx, dy, dz = float(tomo.shape[0]), float(tomo.shape[1]), float(tomo.shape[2])\n dx2, dy2, dz2 = math.floor(.5 * dx), math.floor(.5 * dy), math.floor(.5 * dz)\n x_l, y_l, z_l = -dx2, -dy2, -dz2\n x_h, y_h, z_h = -dx2 + dx, -dy2 + dy, -dz2 + dz\n X, Y, Z = np.meshgrid(np.arange(x_l, x_h), np.arange(y_l, y_h), np.arange(z_l, z_h), indexing='xy')\n R = np.sqrt(X * X + Y * Y + Z * Z)\n G_u = tomo_mn * np.exp(-(R-rad1)**2 / g_cte)\n G_l = tomo_mn * np.exp(-(R-rad2)**2 / g_cte)\n\n # Creating the softmaks for the model structure\n BW = sp.ndimage.morphology.distance_transform_edt(np.invert(tomo_bin))\n Ss = 1. - np.exp(-(BW * BW) / g_cte_2)\n G_u = G_u * Ss\n G_l = G_l * Ss\n\n # Merge the structure and the membrane\n tomo += (G_u + G_l)\n\n\ndef gen_ccsrv_msome(shape, n_parts, mic_rad, c_rad, min_ip_dst, c_jump_prob):\n \"\"\"\n Generates a list of 3D coordinates and rotations distributed in cluster randomly placed on a microsome\n :param shape: tomogram shape\n :param n_parts: number of particles to try to generate\n :param mic_rad: microsome radius\n :param c_rad: cluster radius\n :param min_ip_dst: minimum interparticle distance\n :param c_jump_prob: probabilty to create a new cluster evaluated each time a particle is addded [0, 1]\n :return: two lists; coordinates and rotations\n \"\"\"\n\n # Initialization\n count = 0\n min_ip_dst_2 = float(min_ip_dst)**2\n locs, rots = list(), list()\n mic_cent = .5 * np.asarray(shape, dtype=np.float)\n mic_rad_f = float(mic_rad)\n max_n_tries = np.prod(np.asarray(shape, dtype=np.int))\n\n # Generate all possible the uniformly distributed particle seeds at 2x pixel precision\n n_seeds = 8. * np.pi * mic_rad * mic_rad\n if n_seeds < npart:\n n_seeds = npart\n hold_seeds = np.random.randn(n_seeds, 3)\n norm = mic_rad_f / np.linalg.norm(hold_seeds)\n hold_seeds *= norm\n hold_seeds += mic_cent\n seeds = list()\n for p_cent in hold_seeds:\n # Check that the particle is within the tomogram\n if (p_cent[0] >= 0) and (p_cent[0] < shape[0]) \\\n and (p_cent[1] >= 0) and (p_cent[1] < shape[1]) \\\n and (p_cent[2] >= 0) and (p_cent[2] < shape[2]):\n seeds.append(p_cent)\n\n # Loop for clusters\n mic_end, n_try = False, 0\n while not mic_end:\n\n # Generating the cluster center (random sampling on S^2)\n c_cent = np.random.randn(1, 3)[0]\n norm = mic_rad_f / np.linalg.norm(c_cent)\n c_cent *= norm\n c_cent += mic_cent\n\n # Sort seeds by distance to cluster center\n dsts = geo_point_dst_sphere(c_cent, seeds, mic_cent, mic_rad)\n\n # Loop for particles likely within the cluster radius\n c_end = False\n while not c_end:\n rnd_val = np.random.random()\n if (rnd_val > c_jump_prob) and (n_try <= max_n_tries):\n rnd_dst = math.fabs(np.random.normal(0, c_rad))\n idx = (np.abs(dsts - rnd_dst)).argmin()\n c_part = seeds[idx]\n # Check that the new particle does not overlap with other already inserted\n hold_dst = c_part - np.asarray(locs, dtype=np.float)\n if np.sum(hold_dst*hold_dst, axis=1) >= min_ip_dst_2:\n locs.append(c_part)\n tilt, psi = vect_to_zrelion(c_part - mic_cent, mode='active')[1:]\n rots.append((360.*np.random.rand()-180., tilt, psi))\n count += 1\n else:\n c_end = True\n\n # Ensure termination\n n_try += 1\n if (n_try > max_n_tries) or (count >= n_parts):\n mic_end = True\n\n return locs, rots\n\n\ndef gen_2ccsrv_msome(locs, rots, shape, n_parts, mic_rad, avg_dst, min_ip_dst):\n \"\"\"\n Generates a list of 3D coordinates and rotations distributed in correlation with some reference inputs\n :param locs, rots: referece input lists with localizations and rotation\n :param shape: tomogram shape\n :param n_parts: number of particles to try to generate\n :param mic_rad: microsome radius\n :param avg_dst: averaged distance to the reference pattern nearest particle\n :param min_ip_dst: minimum interparticle distance\n :param c_jump_prob: probabilty to create a new cluster evaluated each time a particle is addded [0, 1]\n :return: two output lists; coordinates and rotations\n \"\"\"\n\n # Initialization\n count = 0\n min_ip_dst_2 = float(min_ip_dst) ** 2\n locs_out, rots_out = list(), list()\n mic_cent = .5 * np.asarray(shape, dtype=np.float)\n mic_rad_f = float(mic_rad)\n max_n_tries = np.prod(np.asarray(shape, dtype=np.int))\n locs_a, rots_a = np.asarray(locs, dtype=np.float), np.asarray(rots, dtype=np.float)\n\n # Generate all possible the uniformly distributed particle seeds at 2x pixel precision\n n_seeds = 8. * np.pi * mic_rad * mic_rad\n if n_seeds < npart:\n n_seeds = npart\n hold_seeds = np.random.randn(n_seeds, 3)\n norm = mic_rad_f / np.linalg.norm(hold_seeds)\n hold_seeds *= norm\n hold_seeds += mic_cent\n seeds = list()\n for p_cent in hold_seeds:\n # Check that the particle is within the tomogram\n if (p_cent[0] >= 0) and (p_cent[0] < shape[0]) \\\n and (p_cent[1] >= 0) and (p_cent[1] < shape[1]) \\\n and (p_cent[2] >= 0) and (p_cent[2] < shape[2]):\n seeds.append(p_cent)\n\n # Loop for particles\n mic_end, n_try = False, 0\n p_end = False\n while not p_end:\n rnd_idx = np.random.randint(0, len(seeds))\n c_cent = seeds[rnd_idx]\n rnd_dst = math.fabs(np.random.normal(0, avg_dst))\n dsts = geo_point_dst_sphere(c_cent, seeds, mic_cent, mic_rad)\n idx = (np.abs(dsts - rnd_dst)).argmin()\n p_cent = seeds[idx]\n # Check that the new particle does not overlap with other already inserted\n hold_dst = p_cent - locs_a\n if np.sum(hold_dst * hold_dst, axis=1) >= min_ip_dst_2:\n locs_out.append(p_cent)\n tilt, psi = vect_to_zrelion(p_cent - mic_cent, mode='active')[1:]\n rots_out.append((360. * np.random.rand() - 180., tilt, psi))\n count += 1\n\n # Ensure termination\n n_try += 1\n if (n_try > max_n_tries) or (count >= n_parts):\n p_end = True\n\n return locs_out, rots_out\n\n\ndef gen_csrv_msome(shape, n_parts, mic_rad, min_ip_dst):\n \"\"\"\n Generates a list of 3D coordinates and rotations a CSRV pattern\n :param shape: tomogram shape\n :param n_parts: number of particles to try to generate\n :param mic_rad: microsome radius\n :param min_ip_dst: minimum interparticle distance\n :param c_jump_prob: probabilty to create a new cluster evaluated each time a particle is addded [0, 1]\n :return: two output lists; coordinates and rotations\n \"\"\"\n\n # Initialization\n count = 0\n min_ip_dst_2 = float(min_ip_dst) ** 2\n locs, rots = list(), list()\n mic_cent = .5 * np.asarray(shape, dtype=np.float)\n mic_rad_f = float(mic_rad)\n max_n_tries = np.prod(np.asarray(shape, dtype=np.int))\n\n # Loop for particles\n mic_end, n_try = False, 0\n p_end = False\n while not p_end:\n p_cent = np.random.randn(1, 3)[0]\n norm = mic_rad_f / np.linalg.norm(p_cent)\n p_cent *= norm\n p_cent += mic_cent\n # Check that the particle is within the tomogram\n if (p_cent[0] >= 0) and (p_cent[0] < shape[0]) \\\n and (p_cent[1] >= 0) and (p_cent[1] < shape[1]) \\\n and (p_cent[2] >= 0) and (p_cent[2] < shape[2]):\n if len(locs) > 0:\n # Check that the new particle does not overlap with other already inserted\n hold_dst = p_cent - np.asarray(locs, dtype=np.float)\n if np.sum(hold_dst * hold_dst, axis=1) >= min_ip_dst_2:\n locs.append(p_cent)\n tilt, psi = vect_to_zrelion(p_cent - mic_cent, mode='active')[1:]\n rots.append((360. * np.random.rand() - 180., tilt, psi))\n count += 1\n else:\n locs.append(p_cent)\n tilt, psi = vect_to_zrelion(p_cent - mic_cent, mode='active')[1:]\n rots.append((360. * np.random.rand() - 180., tilt, psi))\n count += 1\n\n # Ensure termination\n n_try += 1\n if (n_try > max_n_tries) or (count >= n_parts):\n p_end = True\n\n return locs, rots\n\n########################################################################################\n# MAIN ROUTINE\n########################################################################################\n\n########## Printing the initial message\n\nprint('Generate synthetic microsomes.')\nprint('\\tAuthor: ' + __author__)\nprint('\\tDate: ' + time.strftime(\"%c\") + '\\n')\nprint('Options:')\nprint('\\tOutput directory: ' + str(out_dir))\nprint('\\tOuput stem: ' + str(out_stem))\nprint('\\tTomograms settings:')\nprint('\\t\\t-Number of tomograms: ' + str(tm_nt))\nprint('\\t\\t-Tomogram size: ' + str(tm_size) + ' px')\nprint('\\t\\t-Resolution: ' + str(tm_res) + ' nm/px')\nprint('\\t\\t-SNR range: ' + str(tm_snr_rg))\nprint('\\t\\t-Missing wedge semi-angle: ' + str(tm_wedge) + ' deg')\nprint('\\t\\t-Binning factor: ' + str(tm_bin))\nprint('\\tMicrosome settings:')\nprint('\\t\\t-Membrane thickness: ' + str(mc_mbt) + ' nm')\nprint('\\t\\t-Membrane layer sigma: ' + str(mc_mbs) + ' nm')\nprint('\\t\\t-Minimum iter-particles distance: ' + str(mc_ip_min_dst) + ' nm')\nprint('\\t\\t-Clusters radius for 1st pattern: ' + str(mc_1st_crad) + ' nm')\nprint('\\t\\t-Clusters radius for 2nd pattern: ' + str(2*mc_1st_crad) + ' nm')\nprint('\\t\\t-Averaged ditance to the 3rd pattern particles for the 4th pattern particles: ' + str(mc_4th_dst) + ' nm')\nprint('\\t\\t-Input files with the density models: ' + str(mc_in_models))\nprint('\\t\\t-Averaged (normal distribution) number of particles per model and microsome: ' + str(mc_avg_nparts))\nprint('\\t\\t-Maximum deviation (3sg for Gaussian): ' + str(mc_3sg_nparts))\nprint('\\t\\t-Subvolumes center height: ' + str(mc_zh))\nprint('')\n\n########### Input parsing\n\n######### Process\n\n# Initialization of global variables\nmax_svol_dim = 0\nsvol_refs = dict()\nnparts, snrs = np.zeros(shape=(tm_nt, len(mc_avg_nparts)), dtype=np.int), np.zeros(shape=tm_nt, dtype=np.float)\nfor i in range(tm_nt):\n snrs[i] = (tm_snr_rg[1] - tm_snr_rg[0]) * np.random.random() + tm_snr_rg[0]\n for j, avg_parts in enumerate(mc_avg_nparts):\n hold_nparts = np.random.normal(avg_parts, mc_3sg_nparts)\n if hold_nparts < 0:\n hold_nparts = 0\n nparts[i, j] = hold_nparts\nhold_ref_0 = disperse_io.load_tomo(mc_in_models[0])\nfor in_model in mc_in_models:\n hold_ref = disperse_io.load_tomo(in_model)\n if hold_ref_0.shape != hold_ref.shape:\n print('ERROR: All input density subvolume models must have the same size.')\n print('Terminated. (' + time.strftime(\"%c\") + ')')\n sys.exit(-1)\n svol_refs[mc_in_models] = hold_ref\nmax_tm_size, max_svol_dim = max(tm_size[0:1]), max(hold_ref_0.shape[0:1])\nmic_rad = .75 * max_tm_size\nif (mic_rad + max_svol_dim) > max_tm_size:\n mic_rad = max_tm_size - max_svol_dim\ncent_v = .5*np.asarray(hold_ref_0.shape, dtype=np.float) - np.asarray((0, 0, mc_zh), dtype=np.float)\nmc_ip_min_dst_v, mc_1st_crad_v, mc_4th_dst_v = float(mc_ip_min_dst)/tm_res, float(mc_1st_crad)/tm_res, \\\n float(mc_4th_dst)/tm_res\n\nprint('Main routine: ')\n\nprint('\\tLoop for microsomes: ')\ncols = list()\nfor i in range(tm_nt):\n\n snr = snrs[i]\n print('\\t\\t-Generating microsome ' + str(i) + ' with SNR=' + snr + ':')\n tomo = np.zeros(shape=tm_size, dtype=np.float16)\n\n print('\\t\\t\\t+Adding the particles: ')\n hold_locs, hold_angs = None, None\n for j, key in enumerate(svol_refs.keys()):\n svol_ref = svol_refs[key]\n npart = nparts[i, j]\n if j == 0:\n locs, angs = gen_ccsrv_msome(tm_size, npart, mic_rad, mc_1st_crad_v, mc_ip_min_dst_v, mc_c_jump_prob)\n elif j == 1:\n locs, angs = gen_ccsrv_msome(tm_size, npart, mic_rad, 2*mc_1st_crad_v, mc_ip_min_dst_v, mc_c_jump_prob)\n elif j == 3:\n locs, angs = gen_2ccsrv_msome(hold_locs, hold_angs, npart, mic_rad, hold_locs, hold_angs)\n else:\n locs, angs = gen_csrv_msome(npart, mic_rad)\n for loc, ang in zip(locs, angs):\n svol = tomo_rot(svol_ref, ang, conv='relion', active=True, deg=True, center=(0, 0, mc_zh))\n point = loc + cent_v\n tomo = spatial.over_sub_tomo(tomo, point, svol, np.max)\n if j == 2:\n hold_locs, hold_angs = locs, angs\n print('\\t\\t\\t\\t* Particles inserted: ' + str(len(locs)) + ' of ' + str(npart))\n\n print('\\t\\t\\t+Adding the membrane...')\n add_dmb_msome(tomo, mic_rad, tm_res, mc_mbt, mc_mbs)\n\n print('\\t\\t\\t+Adding the distortions...')\n mc_rad1, mc_rad2 = mic_rad - mc_zh, mic_rad + max_svol_dim - mc_zh\n mask = gen_mask_msome(tm_size, mc_rad1, mc_rad2)\n mn = tomo[mask].mean()\n sg_bg = mn / snr\n tomo += np.random.normal(mn, sg_bg, size=tm_size)\n tomo = lin_map(tomo, tomo.max(), tomo.min())\n tomo = add_mw(tomo, 0, tm_wedge)\n\n out_tomo = out_dir + '/' + out_stem + '_ + tomo_mic_' + str(i) + '.mrc'\n print('\\t\\t\\t+Saving the microsome as: ' + out_tomo)\n disperse_io.save_numpy(tomo, out_tomo)\n out_tomo_bin = out_dir + '/' + out_stem + '_ + tomo_mic_bin_' + str(i) + '.mrc'\n print('\\t\\t\\t+Saving the ' + str(tm_bin) + ' binned microsome as: ' + out_tomo_bin)\n tomo_bin = tomo\n for i in range(bin):\n tomo_bin = tomo_binning(tomo_bin)\n disperse_io.save_numpy(tomo_bin, out_tomo)\n cols.append((out_tomo, out_tomo_bin))\n\nout_star = out_dir + '/' + out_stem + '.star'\nprint('\\tStoring output STAR file in: ' + out_star)\nstar_tomos = sub.Star()\nstar_tomos.add_column('_rlnMicrographName')\nstar_tomos.add_column('_rlnImageName')\nfor col in cols:\n row = {'_rlnMicrographName':col[0], '_rlnImageName':col[1]}\n star_tomos.add_row(**row)\nstar_tomos.store(out_star)\n\nprint('Successfully terminated. (' + time.strftime(\"%c\") + ')')\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "numpy.log10", "numpy.exp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.sum", "numpy.loadtxt", "matplotlib.pyplot.ylabel" ], [ "matplotlib.pyplot.legend", "numpy.asarray", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.plot", "matplotlib.pyplot.tight_layout", "numpy.arange", "matplotlib.pyplot.close", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "numpy.median", "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.percentile", "matplotlib.pyplot.xlim", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ], [ "numpy.testing.assert_equal" ], [ "numpy.testing.assert_almost_equal", "numpy.array", "scipy.stats.chi2.sf", "numpy.testing.assert_equal" ], [ "numpy.square", "numpy.abs", "numpy.nonzero", "numpy.asarray", "numpy.ma.masked_array", "scipy.ndimage.generate_binary_structure", "scipy.ndimage.center_of_mass", "scipy.ndimage.distance_transform_edt", "numpy.add.reduce", "numpy.cos", "numpy.sin", "numpy.concatenate", "scipy.ndimage.maximum", "numpy.arctan2", "scipy.ndimage.binary_dilation", "numpy.array", "numpy.zeros", "scipy.ndimage.minimum_position" ], [ "numpy.linspace", "numpy.asarray", "pandas.DataFrame", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.close", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ticklabel_format", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.isfinite", "numpy.percentile", "matplotlib.pyplot.xlim", "matplotlib.pyplot.grid", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ], [ "numpy.asarray", "scipy.ndimage.morphology.binary_dilation", "scipy.ndimage.filters.gaussian_filter", "numpy.ones" ], [ "scipy.ndimage.morphology.binary_dilation", "numpy.asarray", "numpy.ones", "numpy.bincount", "numpy.where", "numpy.zeros", "scipy.ndimage.morphology.distance_transform_edt" ], [ "numpy.random.random", "numpy.sqrt", "numpy.invert", "numpy.abs", "numpy.asarray", "numpy.arange", "numpy.linalg.norm", "numpy.random.normal", "numpy.random.randn", "numpy.random.rand", "numpy.exp", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] }, { "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": [] }, { "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": [] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
a868111817/language-model-playground
[ "daecd4e39bbf8128b04aa236ad1d31cd22c3c1d9" ]
[ "test/lmp/model/_lstm/conftest.py" ]
[ "r\"\"\"Setup fixtures for testing :py:class:`lmp.model.LSTMModel`.\"\"\"\n\nimport pytest\nimport torch\n\nfrom lmp.model import LSTMModel\nfrom lmp.tknzr import BaseTknzr\n\n\[email protected]\ndef lstm_model(\n tknzr: BaseTknzr,\n d_emb: int,\n d_hid: int,\n n_hid_lyr: int,\n n_pre_hid_lyr: int,\n n_post_hid_lyr: int,\n p_emb: float,\n p_hid: float,\n) -> LSTMModel:\n r\"\"\"Example ``LSTMModel`` instance.\"\"\"\n return LSTMModel(\n d_emb=d_emb,\n d_hid=d_hid,\n n_hid_lyr=n_hid_lyr,\n n_pre_hid_lyr=n_pre_hid_lyr,\n n_post_hid_lyr=n_post_hid_lyr,\n p_emb=p_emb,\n p_hid=p_hid,\n tknzr=tknzr,\n )\n\n\[email protected]\ndef batch_prev_tkids(lstm_model: LSTMModel) -> torch.Tensor:\n r\"\"\"Example input batch of token ids.\"\"\"\n # Shape: (2, 3).\n return torch.randint(\n low=0,\n high=lstm_model.emb.num_embeddings,\n size=(2, 3),\n )\n\n\[email protected]\ndef batch_next_tkids(\n lstm_model: LSTMModel,\n batch_prev_tkids: torch.Tensor,\n) -> torch.Tensor:\n r\"\"\"Example target batch of token ids.\"\"\"\n # Same shape as `batch_prev_tkids`.\n return torch.cat(\n [\n batch_prev_tkids[..., :-1],\n torch.randint(\n low=0,\n high=lstm_model.emb.num_embeddings,\n size=(batch_prev_tkids.shape[0], 1),\n ),\n ],\n dim=1,\n )\n" ]
[ [ "torch.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hust-cec-2021/ma2bea
[ "196f8de33cc4902bd9cb1fdd5400e41f9c275b55" ]
[ "code/visualization/ucb.py" ]
[ "import os\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_args():\n # create argument parser\n parser = argparse.ArgumentParser()\n # parameter for problem\n parser.add_argument('--seed', type=int, default=1)\n parser.add_argument('--benchmark_id', type=int, default=0)\n parser.add_argument('--rmp', type=float, default=0.3)\n # parse args\n args = parser.parse_args()\n # add other args\n return args\n\nROOT = '../../result'\n\ndef load(args):\n folder = os.path.join(ROOT, '{}/{}_{}'.format(args.benchmark_id, args.algorithm, args.rmp))\n Fitness = []\n for name in os.listdir(folder):\n path = os.path.join(folder, name)\n if 'ucb' in name:\n y = np.load(path)\n Fitness.append(y)\n return np.array(Fitness)\n\ndef get_label(args):\n return '{}_{}'.format(args.algorithm, args.benchmark_id)\n\ndef plot(Fitness, args):\n cs = [\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'r', 'r', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'r', 'b', 'b', 'b', 'b', 'b'],\n ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],\n ]\n\n label = get_label(args)\n Fitness = Fitness[:, :, args.source]\n mean_fitness = np.mean(Fitness, axis=0)\n i = 0\n for target in range(mean_fitness.shape[1]):\n if target != args.source:\n plt.plot(mean_fitness[:, target], label='T{}'.format(target+1), color=cs[args.source][i], linewidth=0.3)\n plt.ylabel('UCB value')\n i += 1\n\ndef main():\n # get args\n args = get_args()\n\n # plot each algorithm\n args.algorithm = 'MTO'\n Fitness = load(args)\n for source in range(10):\n args.source = source\n plot(Fitness, args)\n\n plt.legend()\n plt.ylim((0, 2))\n plt.savefig('plot/ucb/{}.eps'.format(source + 1), dpi=300)\n plt.savefig('plot/ucb/{}.png'.format(source + 1), dpi=300)\n plt.clf()\n plt.cla()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.ylim", "matplotlib.pyplot.cla", "matplotlib.pyplot.clf", "numpy.mean", "numpy.load", "numpy.array", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
allisontam/chemprop
[ "87ac151c68d8a200d564b064103c4f514e29f6bd" ]
[ "chemprop/train/run_training.py" ]
[ "from argparse import Namespace\nimport csv\nfrom logging import Logger\nimport os\nfrom pprint import pformat\nfrom typing import List\n\nimport numpy as np\nfrom tensorboardX import SummaryWriter\nimport torch\nfrom tqdm import trange\nimport pickle\nfrom torch.optim.lr_scheduler import ExponentialLR\n\nfrom .evaluate import evaluate, evaluate_predictions\nfrom .predict import predict, save_predictions\nfrom .train import train\nfrom chemprop.data import StandardScaler\nfrom chemprop.data.utils import flip_data, get_class_sizes, get_data, get_task_names, split_data, split_loocv\nfrom chemprop.models import build_model\nfrom chemprop.nn_utils import param_count\nfrom chemprop.utils import build_optimizer, build_lr_scheduler, get_loss_func, get_metric_func, load_checkpoint,\\\n makedirs, save_checkpoint\n\n\ndef run_training(args: Namespace, logger: Logger = None) -> List[float]:\n \"\"\"\n Trains a model and returns test scores on the model checkpoint with the highest validation score.\n\n :param args: Arguments.\n :param logger: Logger.\n :return: A list of ensemble scores for each task.\n \"\"\"\n if logger is not None:\n debug, info = logger.debug, logger.info\n else:\n debug = info = print\n\n # Set GPU\n if args.gpu is not None:\n torch.cuda.set_device(args.gpu)\n\n # Print args\n debug(pformat(vars(args)))\n\n # Get data\n debug('Loading data')\n args.task_names = get_task_names(args.data_path, args.data_format)\n data = get_data(path=args.data_path, args=args, logger=logger)\n args.num_tasks = data.num_tasks()\n args.features_size = data.features_size()\n debug(f'Number of tasks = {args.num_tasks}')\n\n # Split data\n debug(f'Splitting data with seed {args.seed}')\n if args.separate_test_path:\n test_data = get_data(path=args.separate_test_path, args=args, features_path=args.separate_test_features_path, logger=logger)\n if args.separate_val_path:\n val_data = get_data(path=args.separate_val_path, args=args, features_path=args.separate_val_features_path, logger=logger)\n\n if args.separate_val_path and args.separate_test_path:\n train_data = data\n elif args.separate_val_path:\n train_data, _, test_data = split_data(data=data, split_type=args.split_type, sizes=(0.8, 0.0, 0.2), seed=args.seed, args=args, logger=logger)\n elif args.separate_test_path:\n train_data, val_data, _ = split_data(data=data, split_type=args.split_type, sizes=(0.8, 0.2, 0.0), seed=args.seed, args=args, logger=logger)\n elif args.split_type == 'loocv':\n train_data, val_data, test_data = split_loocv(data=data, args=args, logger=logger)\n else:\n train_data, val_data, test_data = split_data(data=data, split_type=args.split_type, sizes=args.split_sizes, seed=args.seed, args=args, logger=logger)\n\n if args.dataset_type == 'classification':\n class_sizes = get_class_sizes(test_data)\n debug('Class sizes in test set')\n for i, task_class_sizes in enumerate(class_sizes):\n debug(f'{args.task_names[i]} '\n f'{\", \".join(f\"{cls}: {size * 100:.2f}%\" for cls, size in enumerate(task_class_sizes))}')\n if not args.train_all and task_class_sizes == 0: # TODO: only works for just 1 property prediction task\n debug('Moved to next epoch due to homogenous targets in test set.')\n return [float('nan')]\n\n if args.save_smiles_splits:\n with open(args.data_path, 'r') as f:\n reader = csv.reader(f)\n header = next(reader)\n\n lines_by_smiles = {}\n indices_by_smiles = {}\n for i, line in enumerate(reader):\n smiles = (line[0], line[1])\n lines_by_smiles[smiles] = line\n indices_by_smiles[smiles] = i\n\n all_split_indices = []\n for dataset, name in [(train_data, 'train'), (val_data, 'val'), (test_data, 'test')]:\n with open(os.path.join(args.save_dir, name + '_smiles.csv'), 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['smiles'])\n for smiles in dataset.smiles():\n writer.writerow([smiles])\n with open(os.path.join(args.save_dir, name + '_full.csv'), 'w') as f:\n writer = csv.writer(f)\n writer.writerow(header)\n for smiles in dataset.smiles():\n writer.writerow(lines_by_smiles[smiles])\n split_indices = []\n for smiles in dataset.smiles():\n split_indices.append(indices_by_smiles[smiles])\n split_indices = sorted(split_indices)\n all_split_indices.append(split_indices)\n with open(os.path.join(args.save_dir, 'split_indices.pckl'), 'wb') as f:\n pickle.dump(all_split_indices, f)\n\n if args.symmetric:\n train_data = flip_data(train_data)\n\n if args.features_scaling:\n drug_scaler, cmpd_scaler = train_data.normalize_features(replace_nan_token=0)\n val_data.normalize_features(drug_scaler, cmpd_scaler)\n test_data.normalize_features(drug_scaler, cmpd_scaler)\n else:\n drug_scaler, cmpd_scaler = None, None\n\n args.train_data_size = len(train_data)\n \n debug(f'Total size = {len(data):,} | '\n f'train size = {len(train_data):,} | val size = {len(val_data):,} | test size = {len(test_data):,}')\n\n # Initialize scaler and scale training targets by subtracting mean and dividing standard deviation (regression only)\n if args.dataset_type == 'regression':\n debug('Fitting scaler')\n train_smiles, train_targets = train_data.smiles(), train_data.targets()\n scaler = StandardScaler().fit(train_targets)\n scaled_targets = scaler.transform(train_targets).tolist()\n train_data.set_targets(scaled_targets)\n else:\n scaler = None\n\n # Get loss and metric functions\n loss_func = get_loss_func(args)\n metric_func = get_metric_func(metric=args.metric)\n\n # Set up test set evaluation\n test_smiles, test_targets = test_data.smiles(), test_data.targets()\n if args.dataset_type == 'multiclass':\n sum_test_preds = np.zeros((len(test_smiles), args.num_tasks, args.multiclass_num_classes))\n else:\n sum_test_preds = np.zeros((len(test_smiles), args.num_tasks))\n\n # Train ensemble of models\n for model_idx in range(args.ensemble_size):\n # Tensorboard writer\n save_dir = os.path.join(args.save_dir, f'model_{model_idx}')\n makedirs(save_dir)\n try:\n writer = SummaryWriter(log_dir=save_dir)\n except:\n writer = SummaryWriter(logdir=save_dir)\n # Load/build model\n if args.checkpoint_paths is not None:\n debug(f'Loading model {model_idx} from {args.checkpoint_paths[model_idx]}')\n model = load_checkpoint(args.checkpoint_paths[model_idx], current_args=args, logger=logger)\n else:\n debug(f'Building model {model_idx}')\n model = build_model(args)\n\n debug(model)\n debug(f'Number of parameters = {param_count(model):,}')\n if args.cuda:\n debug('Moving model to cuda')\n model = model.cuda()\n\n # Ensure that model is saved in correct location for evaluation if 0 epochs\n save_checkpoint(os.path.join(save_dir, 'model.pt'), model, scaler, drug_scaler, cmpd_scaler, args)\n\n # Optimizers\n optimizer = build_optimizer(model, args)\n\n # Learning rate schedulers\n scheduler = build_lr_scheduler(optimizer, args)\n\n # Run training\n best_score = float('inf') if args.minimize_score else -float('inf')\n best_epoch, n_iter = 0, 0\n for epoch in trange(args.epochs):\n debug(f'Epoch {epoch}')\n\n n_iter = train(\n model=model,\n data=train_data,\n loss_func=loss_func,\n optimizer=optimizer,\n scheduler=scheduler,\n args=args,\n n_iter=n_iter,\n logger=logger,\n writer=writer\n )\n if isinstance(scheduler, ExponentialLR):\n scheduler.step()\n val_scores, val_loss = evaluate(\n model=model,\n data=val_data,\n loss_func=loss_func,\n num_tasks=args.num_tasks,\n metric_func=metric_func,\n batch_size=args.batch_size,\n dataset_type=args.dataset_type,\n scaler=scaler,\n logger=logger\n )\n\n # Average validation score\n avg_val_score = np.nanmean(val_scores)\n debug(f'Validation {args.metric} = {avg_val_score:.6f}')\n writer.add_scalar(f'validation_{args.metric}', avg_val_score, n_iter)\n\n debug(f'Validation loss = {val_loss:.6f}')\n writer.add_scalar(f'validation_loss', val_loss, n_iter)\n\n if args.show_individual_scores:\n # Individual validation scores\n for task_name, val_score in zip(args.task_names, val_scores):\n debug(f'Validation {task_name} {args.metric} = {val_score:.6f}')\n writer.add_scalar(f'validation_{task_name}_{args.metric}', val_score, n_iter)\n\n # Save model checkpoint if improved validation score\n if args.minimize_score and avg_val_score < best_score or \\\n not args.minimize_score and avg_val_score > best_score:\n best_score, best_epoch = avg_val_score, epoch\n save_checkpoint(os.path.join(save_dir, 'model.pt'), model, scaler, drug_scaler, cmpd_scaler, args)\n\n # Evaluate on test set using model with best validation score\n info(f'Model {model_idx} best validation {args.metric} = {best_score:.6f} on epoch {best_epoch}')\n model = load_checkpoint(os.path.join(save_dir, 'model.pt'), cuda=args.cuda, logger=logger)\n\n test_preds = predict(\n model=model,\n data=test_data,\n batch_size=args.batch_size,\n scaler=scaler\n )\n if args.save_preds:\n val_preds = predict(model=model, data=val_data, batch_size=args.batch_size, scaler=scaler)\n train_preds = predict(model=model, data=train_data, batch_size=args.batch_size, scaler=scaler)\n save_predictions(save_dir, train_data, val_data, test_data, \\\n train_preds, val_preds, test_preds, args.task_names, scaler)\n\n test_scores = evaluate_predictions(\n preds=test_preds,\n targets=test_targets,\n num_tasks=args.num_tasks,\n metric_func=metric_func,\n dataset_type=args.dataset_type,\n logger=logger\n )\n\n if len(test_preds) != 0:\n sum_test_preds += np.array(test_preds)\n\n # Average test score\n avg_test_score = np.nanmean(test_scores)\n info(f'Model {model_idx} test {args.metric} = {avg_test_score:.6f}')\n writer.add_scalar(f'test_{args.metric}', avg_test_score, 0)\n\n if args.show_individual_scores:\n # Individual test scores\n for task_name, test_score in zip(args.task_names, test_scores):\n info(f'Model {model_idx} test {task_name} {args.metric} = {test_score:.6f}')\n writer.add_scalar(f'test_{task_name}_{args.metric}', test_score, n_iter)\n\n # Evaluate ensemble on test set\n avg_test_preds = (sum_test_preds / args.ensemble_size).tolist()\n\n ensemble_scores = evaluate_predictions(\n preds=avg_test_preds,\n targets=test_targets,\n num_tasks=args.num_tasks,\n metric_func=metric_func,\n dataset_type=args.dataset_type,\n logger=logger\n )\n\n # Average ensemble score\n avg_ensemble_test_score = np.nanmean(ensemble_scores)\n info(f'Ensemble test {args.metric} = {avg_ensemble_test_score:.6f}')\n writer.add_scalar(f'ensemble_test_{args.metric}', avg_ensemble_test_score, 0)\n\n # Individual ensemble scores\n if args.show_individual_scores:\n for task_name, ensemble_score in zip(args.task_names, ensemble_scores):\n info(f'Ensemble test {task_name} {args.metric} = {ensemble_score:.6f}')\n\n return ensemble_scores\n" ]
[ [ "numpy.array", "numpy.nanmean", "torch.cuda.set_device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Lube-Project/ProgettoLube
[ "901ac307b68486d8289105c159ca702318bea5b0", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338", "cbf33971e2c2e865783ec1a2302625539186a338" ]
[ "ProgettoLube/WebInspector/venv/Lib/site-packages/skimage/color/tests/test_adapt_rgb.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow_estimator/python/estimator/canned/v1/linear_testing_utils_v1.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/keras/api/_v1/keras/mixed_precision/__init__.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/skimage/restoration/_denoise.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/ops/gen_debug_ops.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/ops/gen_ragged_conversion_ops.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/keras/api/_v1/keras/applications/inception_v3/__init__.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/_api/v2/compat/v2/compat/v1/__init__.py", "ProgettoLube/WebInspector/ImageSimilarity.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/skimage/morphology/_skeletonize.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/skimage/feature/corner.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow_estimator/python/estimator/head/head_utils.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/keras/api/_v1/keras/applications/inception_resnet_v2/__init__.py", "ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/python/ops/gen_count_ops.py" ]
[ "from functools import partial\n\nimport numpy as np\n\nfrom skimage import img_as_float, img_as_uint\nfrom skimage import color, data, filters\nfrom skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value\n\n# Down-sample image for quicker testing.\nCOLOR_IMAGE = data.astronaut()[::5, ::6]\nGRAY_IMAGE = data.camera()[::5, ::5]\n\nSIGMA = 3\nsmooth = partial(filters.gaussian, sigma=SIGMA)\nassert_allclose = partial(np.testing.assert_allclose, atol=1e-8)\n\n\n@adapt_rgb(each_channel)\ndef edges_each(image):\n return filters.sobel(image)\n\n\n@adapt_rgb(each_channel)\ndef smooth_each(image, sigma):\n return filters.gaussian(image, sigma)\n\n\n@adapt_rgb(each_channel)\ndef mask_each(image, mask):\n result = image.copy()\n result[mask] = 0\n return result\n\n\n@adapt_rgb(hsv_value)\ndef edges_hsv(image):\n return filters.sobel(image)\n\n\n@adapt_rgb(hsv_value)\ndef smooth_hsv(image, sigma):\n return filters.gaussian(image, sigma)\n\n\n@adapt_rgb(hsv_value)\ndef edges_hsv_uint(image):\n return img_as_uint(filters.sobel(image))\n\n\ndef test_gray_scale_image():\n # We don't need to test both `hsv_value` and `each_channel` since\n # `adapt_rgb` is handling gray-scale inputs.\n assert_allclose(edges_each(GRAY_IMAGE), filters.sobel(GRAY_IMAGE))\n\n\ndef test_each_channel():\n filtered = edges_each(COLOR_IMAGE)\n for i, channel in enumerate(np.rollaxis(filtered, axis=-1)):\n expected = img_as_float(filters.sobel(COLOR_IMAGE[:, :, i]))\n assert_allclose(channel, expected)\n\n\ndef test_each_channel_with_filter_argument():\n filtered = smooth_each(COLOR_IMAGE, SIGMA)\n for i, channel in enumerate(np.rollaxis(filtered, axis=-1)):\n assert_allclose(channel, smooth(COLOR_IMAGE[:, :, i]))\n\n\ndef test_each_channel_with_asymmetric_kernel():\n mask = np.triu(np.ones(COLOR_IMAGE.shape[:2], dtype=np.bool_))\n mask_each(COLOR_IMAGE, mask)\n\n\ndef test_hsv_value():\n filtered = edges_hsv(COLOR_IMAGE)\n value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2]\n assert_allclose(color.rgb2hsv(filtered)[:, :, 2], filters.sobel(value))\n\n\ndef test_hsv_value_with_filter_argument():\n filtered = smooth_hsv(COLOR_IMAGE, SIGMA)\n value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2]\n assert_allclose(color.rgb2hsv(filtered)[:, :, 2], smooth(value))\n\n\ndef test_hsv_value_with_non_float_output():\n # Since `rgb2hsv` returns a float image and the result of the filtered\n # result is inserted into the HSV image, we want to make sure there isn't\n # a dtype mismatch.\n filtered = edges_hsv_uint(COLOR_IMAGE)\n filtered_value = color.rgb2hsv(filtered)[:, :, 2]\n value = color.rgb2hsv(COLOR_IMAGE)[:, :, 2]\n # Reduce tolerance because dtype conversion.\n assert_allclose(filtered_value, filters.sobel(value), rtol=1e-5, atol=1e-5)\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utils for testing linear estimators.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport six\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.core.example import feature_pb2\nfrom tensorflow.python.feature_column import feature_column\nfrom tensorflow.python.feature_column import feature_column_v2\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variables as variables_lib\nfrom tensorflow_estimator.python.estimator import estimator\nfrom tensorflow_estimator.python.estimator import run_config\nfrom tensorflow_estimator.python.estimator.canned import linear\nfrom tensorflow_estimator.python.estimator.canned import metric_keys\nfrom tensorflow_estimator.python.estimator.export import export\nfrom tensorflow_estimator.python.estimator.inputs import numpy_io\nfrom tensorflow_estimator.python.estimator.inputs import pandas_io\n\ntry:\n # pylint: disable=g-import-not-at-top\n import pandas as pd\n HAS_PANDAS = True\nexcept IOError:\n # Pandas writes a temporary file during import. If it fails, don't use pandas.\n HAS_PANDAS = False\nexcept ImportError:\n HAS_PANDAS = False\n\n# pylint rules which are disabled by default for test files.\n# pylint: disable=invalid-name,protected-access,missing-docstring\n\n# Names of variables created by model.\nAGE_WEIGHT_NAME = 'linear/linear_model/age/weights'\nHEIGHT_WEIGHT_NAME = 'linear/linear_model/height/weights'\nOCCUPATION_WEIGHT_NAME = 'linear/linear_model/occupation/weights'\nBIAS_NAME = 'linear/linear_model/bias_weights'\nLANGUAGE_WEIGHT_NAME = 'linear/linear_model/language/weights'\n\n# This is so that we can easily switch between feature_column and\n# feature_column_v2 for testing.\nfeature_column.numeric_column = feature_column._numeric_column\nfeature_column.categorical_column_with_hash_bucket = feature_column._categorical_column_with_hash_bucket # pylint: disable=line-too-long\nfeature_column.categorical_column_with_vocabulary_list = feature_column._categorical_column_with_vocabulary_list # pylint: disable=line-too-long\nfeature_column.categorical_column_with_vocabulary_file = feature_column._categorical_column_with_vocabulary_file # pylint: disable=line-too-long\nfeature_column.embedding_column = feature_column._embedding_column\n\n\ndef assert_close(expected, actual, rtol=1e-04, name='assert_close'):\n with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope:\n expected = ops.convert_to_tensor(expected, name='expected')\n actual = ops.convert_to_tensor(actual, name='actual')\n rdiff = tf.math.abs(expected - actual, 'diff') / tf.math.abs(expected)\n rtol = ops.convert_to_tensor(rtol, name='rtol')\n return tf.compat.v1.debugging.assert_less(\n rdiff,\n rtol,\n data=('Condition expected =~ actual did not hold element-wise:'\n 'expected = ', expected, 'actual = ', actual, 'rdiff = ', rdiff,\n 'rtol = ', rtol,),\n name=scope)\n\n\ndef save_variables_to_ckpt(model_dir):\n init_all_op = [tf.compat.v1.initializers.global_variables()]\n with tf.compat.v1.Session() as sess:\n sess.run(init_all_op)\n tf.compat.v1.train.Saver().save(sess, os.path.join(model_dir, 'model.ckpt'))\n\n\ndef queue_parsed_features(feature_map):\n tensors_to_enqueue = []\n keys = []\n for key, tensor in six.iteritems(feature_map):\n keys.append(key)\n tensors_to_enqueue.append(tensor)\n queue_dtypes = [x.dtype for x in tensors_to_enqueue]\n input_queue = tf.queue.FIFOQueue(capacity=100, dtypes=queue_dtypes)\n tf.compat.v1.train.queue_runner.add_queue_runner(\n tf.compat.v1.train.queue_runner.QueueRunner(\n input_queue, [input_queue.enqueue(tensors_to_enqueue)]))\n dequeued_tensors = input_queue.dequeue()\n return {keys[i]: dequeued_tensors[i] for i in range(len(dequeued_tensors))}\n\n\ndef sorted_key_dict(unsorted_dict):\n return {k: unsorted_dict[k] for k in sorted(unsorted_dict)}\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-1.0 * x))\n\n\nclass CheckPartitionerVarHook(tf.compat.v1.train.SessionRunHook):\n \"\"\"A `SessionRunHook` to check a partitioned variable.\"\"\"\n\n def __init__(self, test_case, var_name, var_dim, partitions):\n self._test_case = test_case\n self._var_name = var_name\n self._var_dim = var_dim\n self._partitions = partitions\n\n def begin(self):\n with tf.compat.v1.variable_scope(\n tf.compat.v1.get_variable_scope()) as scope:\n scope.reuse_variables()\n partitioned_weight = tf.compat.v1.get_variable(\n self._var_name, shape=(self._var_dim, 1))\n self._test_case.assertTrue(\n isinstance(partitioned_weight, variables_lib.PartitionedVariable))\n for part in partitioned_weight:\n self._test_case.assertEqual(self._var_dim // self._partitions,\n part.get_shape()[0])\n\n\nclass BaseLinearRegressorPartitionerTest(object):\n\n def __init__(self, linear_regressor_fn, fc_lib=feature_column):\n self._linear_regressor_fn = linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def testPartitioner(self):\n x_dim = 64\n partitions = 4\n\n def _partitioner(shape, dtype):\n del dtype # unused; required by Fn signature.\n # Only partition the embedding tensor.\n return [partitions, 1] if shape[0] == x_dim else [1]\n\n regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.categorical_column_with_hash_bucket(\n 'language', hash_bucket_size=x_dim),),\n partitioner=_partitioner,\n model_dir=self._model_dir)\n\n def _input_fn():\n return {\n 'language':\n tf.sparse.SparseTensor(\n values=['english', 'spanish'],\n indices=[[0, 0], [0, 1]],\n dense_shape=[1, 2])\n }, [[10.]]\n\n hook = CheckPartitionerVarHook(self, LANGUAGE_WEIGHT_NAME, x_dim,\n partitions)\n regressor.train(input_fn=_input_fn, steps=1, hooks=[hook])\n\n def testDefaultPartitionerWithMultiplePsReplicas(self):\n partitions = 2\n # This results in weights larger than the default partition size of 64M,\n # so partitioned weights are created (each weight uses 4 bytes).\n x_dim = 32 << 20\n\n class FakeRunConfig(run_config.RunConfig):\n\n @property\n def num_ps_replicas(self):\n return partitions\n\n # Mock the device setter as ps is not available on test machines.\n with tf.compat.v1.test.mock.patch.object(\n estimator,\n '_get_replica_device_setter',\n return_value=lambda _: '/cpu:0'):\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.categorical_column_with_hash_bucket(\n 'language', hash_bucket_size=x_dim),),\n config=FakeRunConfig(),\n model_dir=self._model_dir)\n\n def _input_fn():\n return {\n 'language':\n tf.sparse.SparseTensor(\n values=['english', 'spanish'],\n indices=[[0, 0], [0, 1]],\n dense_shape=[1, 2])\n }, [[10.]]\n\n hook = CheckPartitionerVarHook(self, LANGUAGE_WEIGHT_NAME, x_dim,\n partitions)\n linear_regressor.train(input_fn=_input_fn, steps=1, hooks=[hook])\n\n\n# TODO(b/36813849): Add tests with dynamic shape inputs using placeholders.\nclass BaseLinearRegressorEvaluationTest(object):\n\n def __init__(self, linear_regressor_fn, fc_lib=feature_column):\n self._linear_regressor_fn = linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def test_evaluation_for_simple_data(self):\n with tf.Graph().as_default():\n tf.Variable([[11.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([2.0], name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir)\n eval_metrics = linear_regressor.evaluate(\n input_fn=lambda: ({\n 'age': ((1,),)\n }, ((10.,),)), steps=1)\n\n # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. Loss is 3**2 = 9.\n self.assertDictEqual(\n {\n metric_keys.MetricKeys.LOSS: 9.,\n metric_keys.MetricKeys.LOSS_MEAN: 9.,\n metric_keys.MetricKeys.PREDICTION_MEAN: 13.,\n metric_keys.MetricKeys.LABEL_MEAN: 10.,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100\n }, eval_metrics)\n\n def test_evaluation_batch(self):\n \"\"\"Tests evaluation for batch_size==2.\"\"\"\n with tf.Graph().as_default():\n tf.Variable([[11.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([2.0], name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir)\n eval_metrics = linear_regressor.evaluate(\n input_fn=lambda: ({\n 'age': ((1,), (1,))\n }, ((10.,), (10.,))), steps=1)\n\n # Logit is (1. * 11.0 + 2.0) = 13, while label is 10.\n # Loss per example is 3**2 = 9.\n # Training loss is the sum over batch = 9 + 9 = 18\n # Average loss is the average over batch = 9\n self.assertDictEqual(\n {\n metric_keys.MetricKeys.LOSS: 18.,\n metric_keys.MetricKeys.LOSS_MEAN: 9.,\n metric_keys.MetricKeys.PREDICTION_MEAN: 13.,\n metric_keys.MetricKeys.LABEL_MEAN: 10.,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100\n }, eval_metrics)\n\n def test_evaluation_weights(self):\n \"\"\"Tests evaluation with weights.\"\"\"\n with tf.Graph().as_default():\n tf.Variable([[11.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([2.0], name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n def _input_fn():\n features = {'age': ((1,), (1,)), 'weights': ((1.,), (2.,))}\n labels = ((10.,), (10.,))\n return features, labels\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n weight_column='weights',\n model_dir=self._model_dir)\n eval_metrics = linear_regressor.evaluate(input_fn=_input_fn, steps=1)\n\n # Logit is (1. * 11.0 + 2.0) = 13, while label is 10.\n # Loss per example is 3**2 = 9.\n # Training loss is the weighted sum over batch = 9 + 2*9 = 27\n # average loss is the weighted average = 9 + 2*9 / (1 + 2) = 9\n self.assertDictEqual(\n {\n metric_keys.MetricKeys.LOSS: 27.,\n metric_keys.MetricKeys.LOSS_MEAN: 9.,\n metric_keys.MetricKeys.PREDICTION_MEAN: 13.,\n metric_keys.MetricKeys.LABEL_MEAN: 10.,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100\n }, eval_metrics)\n\n def test_evaluation_for_multi_dimensions(self):\n x_dim = 3\n label_dim = 2\n with tf.Graph().as_default():\n tf.Variable([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([7.0, 8.0], name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age', shape=(x_dim,)),),\n label_dimension=label_dim,\n model_dir=self._model_dir)\n input_fn = numpy_io.numpy_input_fn(\n x={\n 'age': np.array([[2., 4., 5.]]),\n },\n y=np.array([[46., 58.]]),\n batch_size=1,\n num_epochs=None,\n shuffle=False)\n eval_metrics = linear_regressor.evaluate(input_fn=input_fn, steps=1)\n\n self.assertItemsEqual(\n (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN,\n metric_keys.MetricKeys.PREDICTION_MEAN,\n metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP),\n eval_metrics.keys())\n\n # Logit is\n # [2., 4., 5.] * [1.0, 2.0] + [7.0, 8.0] = [39, 50] + [7.0, 8.0]\n # [3.0, 4.0]\n # [5.0, 6.0]\n # which is [46, 58]\n self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS])\n\n def test_evaluation_for_multiple_feature_columns(self):\n with tf.Graph().as_default():\n tf.Variable([[10.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME)\n tf.Variable([5.0], name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n batch_size = 2\n feature_columns = [\n self._fc_lib.numeric_column('age'),\n self._fc_lib.numeric_column('height')\n ]\n input_fn = numpy_io.numpy_input_fn(\n x={\n 'age': np.array([20, 40]),\n 'height': np.array([4, 8])\n },\n y=np.array([[213.], [421.]]),\n batch_size=batch_size,\n num_epochs=None,\n shuffle=False)\n\n est = self._linear_regressor_fn(\n feature_columns=feature_columns, model_dir=self._model_dir)\n\n eval_metrics = est.evaluate(input_fn=input_fn, steps=1)\n self.assertItemsEqual(\n (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN,\n metric_keys.MetricKeys.PREDICTION_MEAN,\n metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP),\n eval_metrics.keys())\n\n # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] =\n # [213.0, 421.0], while label is [213., 421.]. Loss = 0.\n self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS])\n\n def test_evaluation_for_multiple_feature_columns_mix(self):\n with tf.Graph().as_default():\n tf.Variable([[10.0]], name=AGE_WEIGHT_NAME)\n tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME)\n tf.Variable([5.0], name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n batch_size = 2\n feature_columns = [\n feature_column.numeric_column('age'),\n tf.feature_column.numeric_column('height')\n ]\n\n def _input_fn():\n features_ds = tf.compat.v1.data.Dataset.from_tensor_slices({\n 'age': np.array([20, 40]),\n 'height': np.array([4, 8])\n })\n labels_ds = tf.compat.v1.data.Dataset.from_tensor_slices(\n np.array([[213.], [421.]]))\n return (tf.compat.v1.data.Dataset.zip(\n (features_ds, labels_ds)).batch(batch_size).repeat(None))\n\n est = self._linear_regressor_fn(\n feature_columns=feature_columns, model_dir=self._model_dir)\n\n eval_metrics = est.evaluate(input_fn=_input_fn, steps=1)\n self.assertItemsEqual(\n (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN,\n metric_keys.MetricKeys.PREDICTION_MEAN,\n metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP),\n eval_metrics.keys())\n\n # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] =\n # [213.0, 421.0], while label is [213., 421.]. Loss = 0.\n self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS])\n\n\nclass BaseLinearRegressorPredictTest(object):\n\n def __init__(self, linear_regressor_fn, fc_lib=feature_column):\n self._linear_regressor_fn = linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def test_1d(self):\n \"\"\"Tests predict when all variables are one-dimensional.\"\"\"\n with tf.Graph().as_default():\n tf.Variable([[10.]], name='linear/linear_model/x/weights')\n tf.Variable([.2], name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('x'),),\n model_dir=self._model_dir)\n\n predict_input_fn = numpy_io.numpy_input_fn(\n x={'x': np.array([[2.]])},\n y=None,\n batch_size=1,\n num_epochs=1,\n shuffle=False)\n predictions = linear_regressor.predict(input_fn=predict_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n # x * weight + bias = 2. * 10. + .2 = 20.2\n self.assertAllClose([[20.2]], predicted_scores)\n\n def testMultiDim(self):\n \"\"\"Tests predict when all variables are multi-dimenstional.\"\"\"\n batch_size = 2\n label_dimension = 3\n x_dim = 4\n feature_columns = (self._fc_lib.numeric_column('x', shape=(x_dim,)),)\n with tf.Graph().as_default():\n tf.Variable( # shape=[x_dim, label_dimension]\n [[1., 2., 3.], [2., 3., 4.], [3., 4., 5.], [4., 5., 6.]],\n name='linear/linear_model/x/weights')\n tf.Variable( # shape=[label_dimension]\n [.2, .4, .6], name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n model_dir=self._model_dir)\n\n predict_input_fn = numpy_io.numpy_input_fn(\n # x shape=[batch_size, x_dim]\n x={'x': np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])},\n y=None,\n batch_size=batch_size,\n num_epochs=1,\n shuffle=False)\n predictions = linear_regressor.predict(input_fn=predict_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n # score = x * weight + bias, shape=[batch_size, label_dimension]\n self.assertAllClose([[30.2, 40.4, 50.6], [70.2, 96.4, 122.6]],\n predicted_scores)\n\n def testTwoFeatureColumns(self):\n \"\"\"Tests predict with two feature columns.\"\"\"\n with tf.Graph().as_default():\n tf.Variable([[10.]], name='linear/linear_model/x0/weights')\n tf.Variable([[20.]], name='linear/linear_model/x1/weights')\n tf.Variable([.2], name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('x0'),\n self._fc_lib.numeric_column('x1')),\n model_dir=self._model_dir)\n\n predict_input_fn = numpy_io.numpy_input_fn(\n x={\n 'x0': np.array([[2.]]),\n 'x1': np.array([[3.]])\n },\n y=None,\n batch_size=1,\n num_epochs=1,\n shuffle=False)\n predictions = linear_regressor.predict(input_fn=predict_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2\n self.assertAllClose([[80.2]], predicted_scores)\n\n def testTwoFeatureColumnsMix(self):\n \"\"\"Tests predict with two feature columns.\"\"\"\n with tf.Graph().as_default():\n tf.Variable([[10.]], name='linear/linear_model/x0/weights')\n tf.Variable([[20.]], name='linear/linear_model/x1/weights')\n tf.Variable([.2], name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(feature_column.numeric_column('x0'),\n tf.feature_column.numeric_column('x1')),\n model_dir=self._model_dir)\n\n def _predict_input_fn():\n return tf.compat.v1.data.Dataset.from_tensor_slices({\n 'x0': np.array([[2.]]),\n 'x1': np.array([[3.]])\n }).batch(1)\n\n predictions = linear_regressor.predict(input_fn=_predict_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2\n self.assertAllClose([[80.2]], predicted_scores)\n\n def testSparseCombiner(self):\n w_a = 2.0\n w_b = 3.0\n w_c = 5.0\n bias = 5.0\n with tf.Graph().as_default():\n tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME)\n tf.Variable([bias], name=BIAS_NAME)\n tf.Variable(\n 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n def _input_fn():\n return tf.compat.v1.data.Dataset.from_tensors({\n 'language':\n tf.sparse.SparseTensor(\n values=['a', 'c', 'b', 'c'],\n indices=[[0, 0], [0, 1], [1, 0], [1, 1]],\n dense_shape=[2, 2]),\n })\n\n feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list(\n 'language', vocabulary_list=['a', 'b', 'c']),)\n\n # Check prediction for each sparse_combiner.\n # With sparse_combiner = 'sum', we have\n # logits_1 = w_a + w_c + bias\n # = 2.0 + 5.0 + 5.0 = 12.0\n # logits_2 = w_b + w_c + bias\n # = 3.0 + 5.0 + 5.0 = 13.0\n linear_regressor = self._linear_regressor_fn(\n feature_columns=feature_columns, model_dir=self._model_dir)\n predictions = linear_regressor.predict(input_fn=_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n self.assertAllClose([[12.0], [13.0]], predicted_scores)\n\n # With sparse_combiner = 'mean', we have\n # logits_1 = 1/2 * (w_a + w_c) + bias\n # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5\n # logits_2 = 1/2 * (w_b + w_c) + bias\n # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0\n linear_regressor = self._linear_regressor_fn(\n feature_columns=feature_columns,\n model_dir=self._model_dir,\n sparse_combiner='mean')\n predictions = linear_regressor.predict(input_fn=_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n self.assertAllClose([[8.5], [9.0]], predicted_scores)\n\n # With sparse_combiner = 'sqrtn', we have\n # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias\n # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974\n # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias\n # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685\n linear_regressor = self._linear_regressor_fn(\n feature_columns=feature_columns,\n model_dir=self._model_dir,\n sparse_combiner='sqrtn')\n predictions = linear_regressor.predict(input_fn=_input_fn)\n predicted_scores = list([x['predictions'] for x in predictions])\n self.assertAllClose([[9.94974], [10.65685]], predicted_scores)\n\n\nclass BaseLinearRegressorIntegrationTest(object):\n\n def __init__(self, linear_regressor_fn, fc_lib=feature_column):\n self._linear_regressor_fn = linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def _test_complete_flow(self, train_input_fn, eval_input_fn, predict_input_fn,\n input_dimension, label_dimension, prediction_length):\n feature_columns = [\n self._fc_lib.numeric_column('x', shape=(input_dimension,))\n ]\n est = self._linear_regressor_fn(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n model_dir=self._model_dir)\n\n # TRAIN\n # learn y = x\n est.train(train_input_fn, steps=200)\n\n # EVALUTE\n scores = est.evaluate(eval_input_fn)\n self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP])\n self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores))\n\n # PREDICT\n predictions = np.array(\n [x['predictions'] for x in est.predict(predict_input_fn)])\n self.assertAllEqual((prediction_length, label_dimension), predictions.shape)\n\n # EXPORT\n feature_spec = tf.compat.v1.feature_column.make_parse_example_spec(\n feature_columns)\n serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn(\n feature_spec)\n export_dir = est.export_saved_model(tempfile.mkdtemp(),\n serving_input_receiver_fn)\n self.assertTrue(tf.compat.v1.gfile.Exists(export_dir))\n\n def test_numpy_input_fn(self):\n \"\"\"Tests complete flow with numpy_input_fn.\"\"\"\n label_dimension = 2\n input_dimension = label_dimension\n batch_size = 10\n prediction_length = batch_size\n data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32)\n data = data.reshape(batch_size, label_dimension)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=data,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n eval_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=data,\n batch_size=batch_size,\n num_epochs=1,\n shuffle=False)\n predict_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=None,\n batch_size=batch_size,\n num_epochs=1,\n shuffle=False)\n\n self._test_complete_flow(\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=input_dimension,\n label_dimension=label_dimension,\n prediction_length=prediction_length)\n\n def test_pandas_input_fn(self):\n \"\"\"Tests complete flow with pandas_input_fn.\"\"\"\n if not HAS_PANDAS:\n return\n\n # Pandas DataFrame natually supports 1 dim data only.\n label_dimension = 1\n input_dimension = label_dimension\n batch_size = 10\n data = np.array([1., 2., 3., 4.], dtype=np.float32)\n x = pd.DataFrame({'x': data})\n y = pd.Series(data)\n prediction_length = 4\n\n train_input_fn = pandas_io.pandas_input_fn(\n x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True)\n eval_input_fn = pandas_io.pandas_input_fn(\n x=x, y=y, batch_size=batch_size, shuffle=False)\n predict_input_fn = pandas_io.pandas_input_fn(\n x=x, batch_size=batch_size, shuffle=False)\n\n self._test_complete_flow(\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=input_dimension,\n label_dimension=label_dimension,\n prediction_length=prediction_length)\n\n def test_input_fn_from_parse_example(self):\n \"\"\"Tests complete flow with input_fn constructed from parse_example.\"\"\"\n label_dimension = 2\n input_dimension = label_dimension\n batch_size = 10\n prediction_length = batch_size\n data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32)\n data = data.reshape(batch_size, label_dimension)\n\n serialized_examples = []\n for datum in data:\n example = example_pb2.Example(\n features=feature_pb2.Features(\n feature={\n 'x':\n feature_pb2.Feature(\n float_list=feature_pb2.FloatList(value=datum)),\n 'y':\n feature_pb2.Feature(\n float_list=feature_pb2.FloatList(\n value=datum[:label_dimension])),\n }))\n serialized_examples.append(example.SerializeToString())\n\n feature_spec = {\n 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32),\n 'y': tf.io.FixedLenFeature([label_dimension], tf.dtypes.float32),\n }\n\n def _train_input_fn():\n feature_map = tf.compat.v1.io.parse_example(serialized_examples,\n feature_spec)\n features = queue_parsed_features(feature_map)\n labels = features.pop('y')\n return features, labels\n\n def _eval_input_fn():\n feature_map = tf.compat.v1.io.parse_example(\n tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1),\n feature_spec)\n features = queue_parsed_features(feature_map)\n labels = features.pop('y')\n return features, labels\n\n def _predict_input_fn():\n feature_map = tf.compat.v1.io.parse_example(\n tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1),\n feature_spec)\n features = queue_parsed_features(feature_map)\n features.pop('y')\n return features, None\n\n self._test_complete_flow(\n train_input_fn=_train_input_fn,\n eval_input_fn=_eval_input_fn,\n predict_input_fn=_predict_input_fn,\n input_dimension=input_dimension,\n label_dimension=label_dimension,\n prediction_length=prediction_length)\n\n\nclass BaseLinearRegressorTrainingTest(object):\n\n def __init__(self, linear_regressor_fn, fc_lib=feature_column):\n self._linear_regressor_fn = linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def _mock_optimizer(self, expected_loss=None):\n expected_var_names = [\n '%s/part_0:0' % AGE_WEIGHT_NAME,\n '%s/part_0:0' % BIAS_NAME\n ]\n\n def _minimize(loss, global_step=None, var_list=None):\n trainable_vars = var_list or tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES)\n self.assertItemsEqual(expected_var_names,\n [var.name for var in trainable_vars])\n\n # Verify loss. We can't check the value directly, so we add an assert op.\n self.assertEquals(0, loss.shape.ndims)\n if expected_loss is None:\n if global_step is not None:\n return tf.compat.v1.assign_add(global_step, 1).op\n return tf.no_op()\n assert_loss = assert_close(\n tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32),\n loss,\n name='assert_loss')\n with tf.control_dependencies((assert_loss,)):\n if global_step is not None:\n return tf.compat.v1.assign_add(global_step, 1).op\n return tf.no_op()\n\n mock_optimizer = tf.compat.v1.test.mock.NonCallableMock(\n spec=tf.compat.v1.train.Optimizer,\n wraps=tf.compat.v1.train.Optimizer(\n use_locking=False, name='my_optimizer'))\n mock_optimizer.minimize = tf.compat.v1.test.mock.MagicMock(wraps=_minimize)\n\n # NOTE: Estimator.params performs a deepcopy, which wreaks havoc with mocks.\n # So, return mock_optimizer itself for deepcopy.\n mock_optimizer.__deepcopy__ = lambda _: mock_optimizer\n return mock_optimizer\n\n def _assert_checkpoint(self,\n expected_global_step,\n expected_age_weight=None,\n expected_bias=None):\n shapes = {\n name: shape\n for (name, shape) in tf.train.list_variables(self._model_dir)\n }\n\n self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP])\n self.assertEqual(\n expected_global_step,\n tf.train.load_variable(self._model_dir,\n tf.compat.v1.GraphKeys.GLOBAL_STEP))\n\n self.assertEqual([1, 1], shapes[AGE_WEIGHT_NAME])\n if expected_age_weight is not None:\n self.assertEqual(expected_age_weight,\n tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME))\n\n self.assertEqual([1], shapes[BIAS_NAME])\n if expected_bias is not None:\n self.assertEqual(expected_bias,\n tf.train.load_variable(self._model_dir, BIAS_NAME))\n\n def testFromScratchWithDefaultOptimizer(self):\n # Create LinearRegressor.\n label = 5.\n age = 17\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir)\n\n # Train for a few steps, and validate final checkpoint.\n num_steps = 10\n linear_regressor.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self._assert_checkpoint(num_steps)\n\n def testTrainWithOneDimLabel(self):\n label_dimension = 1\n batch_size = 20\n feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))]\n est = self._linear_regressor_fn(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n model_dir=self._model_dir)\n data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32)\n self.assertEqual((batch_size,), data_rank_1.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={'age': data_rank_1},\n y=data_rank_1,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(200)\n\n def testTrainWithOneDimWeight(self):\n label_dimension = 1\n batch_size = 20\n feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))]\n est = self._linear_regressor_fn(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n weight_column='w',\n model_dir=self._model_dir)\n\n data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32)\n self.assertEqual((batch_size,), data_rank_1.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={\n 'age': data_rank_1,\n 'w': data_rank_1\n },\n y=data_rank_1,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(200)\n\n def testFromScratch(self):\n # Create LinearRegressor.\n label = 5.\n age = 17\n # loss = (logits - label)^2 = (0 - 5.)^2 = 25.\n mock_optimizer = self._mock_optimizer(expected_loss=25.)\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir,\n optimizer=mock_optimizer)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n linear_regressor.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n expected_global_step=num_steps,\n expected_age_weight=0.,\n expected_bias=0.)\n\n def testFromCheckpoint(self):\n # Create initial checkpoint.\n age_weight = 10.0\n bias = 5.0\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME)\n tf.Variable([bias], name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n # logits = age * age_weight + bias = 17 * 10. + 5. = 175\n # loss = (logits - label)^2 = (175 - 5)^2 = 28900\n mock_optimizer = self._mock_optimizer(expected_loss=28900.)\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir,\n optimizer=mock_optimizer)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n linear_regressor.train(\n input_fn=lambda: ({\n 'age': ((17,),)\n }, ((5.,),)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n expected_global_step=initial_global_step + num_steps,\n expected_age_weight=age_weight,\n expected_bias=bias)\n\n def testFromCheckpointMultiBatch(self):\n # Create initial checkpoint.\n age_weight = 10.0\n bias = 5.0\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME)\n tf.Variable([bias], name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n # logits = age * age_weight + bias\n # logits[0] = 17 * 10. + 5. = 175\n # logits[1] = 15 * 10. + 5. = 155\n # loss = sum(logits - label)^2 = (175 - 5)^2 + (155 - 3)^2 = 52004\n mock_optimizer = self._mock_optimizer(expected_loss=52004.)\n linear_regressor = self._linear_regressor_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n model_dir=self._model_dir,\n optimizer=mock_optimizer)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n linear_regressor.train(\n input_fn=lambda: ({\n 'age': ((17,), (15,))\n }, ((5.,), (3.,))),\n steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n expected_global_step=initial_global_step + num_steps,\n expected_age_weight=age_weight,\n expected_bias=bias)\n\n\nclass BaseLinearClassifierTrainingTest(object):\n\n def __init__(self, linear_classifier_fn, fc_lib=feature_column):\n self._linear_classifier_fn = linear_classifier_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n shutil.rmtree(self._model_dir)\n\n def _mock_optimizer(self, expected_loss=None):\n expected_var_names = [\n '%s/part_0:0' % AGE_WEIGHT_NAME,\n '%s/part_0:0' % BIAS_NAME\n ]\n\n def _minimize(loss, global_step):\n trainable_vars = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES)\n self.assertItemsEqual(expected_var_names,\n [var.name for var in trainable_vars])\n\n # Verify loss. We can't check the value directly, so we add an assert op.\n self.assertEquals(0, loss.shape.ndims)\n if expected_loss is None:\n return tf.compat.v1.assign_add(global_step, 1).op\n assert_loss = assert_close(\n tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32),\n loss,\n name='assert_loss')\n with tf.control_dependencies((assert_loss,)):\n return tf.compat.v1.assign_add(global_step, 1).op\n\n mock_optimizer = tf.compat.v1.test.mock.NonCallableMock(\n spec=tf.compat.v1.train.Optimizer,\n wraps=tf.compat.v1.train.Optimizer(\n use_locking=False, name='my_optimizer'))\n mock_optimizer.minimize = tf.compat.v1.test.mock.MagicMock(wraps=_minimize)\n\n # NOTE: Estimator.params performs a deepcopy, which wreaks havoc with mocks.\n # So, return mock_optimizer itself for deepcopy.\n mock_optimizer.__deepcopy__ = lambda _: mock_optimizer\n return mock_optimizer\n\n def _assert_checkpoint(self,\n n_classes,\n expected_global_step,\n expected_age_weight=None,\n expected_bias=None):\n logits_dimension = n_classes if n_classes > 2 else 1\n\n shapes = {\n name: shape\n for (name, shape) in tf.train.list_variables(self._model_dir)\n }\n\n self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP])\n self.assertEqual(\n expected_global_step,\n tf.train.load_variable(self._model_dir,\n tf.compat.v1.GraphKeys.GLOBAL_STEP))\n\n self.assertEqual([1, logits_dimension], shapes[AGE_WEIGHT_NAME])\n if expected_age_weight is not None:\n self.assertAllEqual(\n expected_age_weight,\n tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME))\n\n self.assertEqual([logits_dimension], shapes[BIAS_NAME])\n if expected_bias is not None:\n self.assertAllEqual(expected_bias,\n tf.train.load_variable(self._model_dir, BIAS_NAME))\n\n def _testFromScratchWithDefaultOptimizer(self, n_classes):\n label = 0\n age = 17\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n model_dir=self._model_dir)\n\n # Train for a few steps, and validate final checkpoint.\n num_steps = 10\n est.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self._assert_checkpoint(n_classes, num_steps)\n\n def testBinaryClassesFromScratchWithDefaultOptimizer(self):\n self._testFromScratchWithDefaultOptimizer(n_classes=2)\n\n def testMultiClassesFromScratchWithDefaultOptimizer(self):\n self._testFromScratchWithDefaultOptimizer(n_classes=4)\n\n def _testTrainWithTwoDimsLabel(self, n_classes):\n batch_size = 20\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n model_dir=self._model_dir)\n data_rank_1 = np.array([0, 1])\n data_rank_2 = np.array([[0], [1]])\n self.assertEqual((2,), data_rank_1.shape)\n self.assertEqual((2, 1), data_rank_2.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={'age': data_rank_1},\n y=data_rank_2,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(n_classes, 200)\n\n def testBinaryClassesTrainWithTwoDimsLabel(self):\n self._testTrainWithTwoDimsLabel(n_classes=2)\n\n def testMultiClassesTrainWithTwoDimsLabel(self):\n self._testTrainWithTwoDimsLabel(n_classes=4)\n\n def _testTrainWithOneDimLabel(self, n_classes):\n batch_size = 20\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n model_dir=self._model_dir)\n data_rank_1 = np.array([0, 1])\n self.assertEqual((2,), data_rank_1.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={'age': data_rank_1},\n y=data_rank_1,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(n_classes, 200)\n\n def testBinaryClassesTrainWithOneDimLabel(self):\n self._testTrainWithOneDimLabel(n_classes=2)\n\n def testMultiClassesTrainWithOneDimLabel(self):\n self._testTrainWithOneDimLabel(n_classes=4)\n\n def _testTrainWithTwoDimsWeight(self, n_classes):\n batch_size = 20\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n weight_column='w',\n n_classes=n_classes,\n model_dir=self._model_dir)\n data_rank_1 = np.array([0, 1])\n data_rank_2 = np.array([[0], [1]])\n self.assertEqual((2,), data_rank_1.shape)\n self.assertEqual((2, 1), data_rank_2.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={\n 'age': data_rank_1,\n 'w': data_rank_2\n },\n y=data_rank_1,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(n_classes, 200)\n\n def testBinaryClassesTrainWithTwoDimsWeight(self):\n self._testTrainWithTwoDimsWeight(n_classes=2)\n\n def testMultiClassesTrainWithTwoDimsWeight(self):\n self._testTrainWithTwoDimsWeight(n_classes=4)\n\n def _testTrainWithOneDimWeight(self, n_classes):\n batch_size = 20\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n weight_column='w',\n n_classes=n_classes,\n model_dir=self._model_dir)\n data_rank_1 = np.array([0, 1])\n self.assertEqual((2,), data_rank_1.shape)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={\n 'age': data_rank_1,\n 'w': data_rank_1\n },\n y=data_rank_1,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n est.train(train_input_fn, steps=200)\n self._assert_checkpoint(n_classes, 200)\n\n def testBinaryClassesTrainWithOneDimWeight(self):\n self._testTrainWithOneDimWeight(n_classes=2)\n\n def testMultiClassesTrainWithOneDimWeight(self):\n self._testTrainWithOneDimWeight(n_classes=4)\n\n def _testFromScratch(self, n_classes):\n label = 1\n age = 17\n # For binary classifier:\n # loss = sigmoid_cross_entropy(logits, label) where logits=0 (weights are\n # all zero initially) and label = 1 so,\n # loss = 1 * -log ( sigmoid(logits) ) = 0.69315\n # For multi class classifier:\n # loss = cross_entropy(logits, label) where logits are all 0s (weights are\n # all zero initially) and label = 1 so,\n # loss = 1 * -log ( 1.0 / n_classes )\n # For this particular test case, as logits are same, the formular\n # 1 * -log ( 1.0 / n_classes ) covers both binary and multi class cases.\n mock_optimizer = self._mock_optimizer(\n expected_loss=(-1 * math.log(1.0 / n_classes)))\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n optimizer=mock_optimizer,\n model_dir=self._model_dir)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n est.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n n_classes,\n expected_global_step=num_steps,\n expected_age_weight=[[0.]] if n_classes == 2 else [[0.] * n_classes],\n expected_bias=[0.] if n_classes == 2 else [.0] * n_classes)\n\n def testBinaryClassesFromScratch(self):\n self._testFromScratch(n_classes=2)\n\n def testMultiClassesFromScratch(self):\n self._testFromScratch(n_classes=4)\n\n def _testFromCheckpoint(self, n_classes):\n # Create initial checkpoint.\n label = 1\n age = 17\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[2.0]] if n_classes == 2 else (np.reshape(\n 2.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n # For binary classifier:\n # logits = age * age_weight + bias = 17 * 2. - 35. = -1.\n # loss = sigmoid_cross_entropy(logits, label)\n # so, loss = 1 * -log ( sigmoid(-1) ) = 1.3133\n # For multi class classifier:\n # loss = cross_entropy(logits, label)\n # where logits = 17 * age_weight + bias and label = 1\n # so, loss = 1 * -log ( soft_max(logits)[1] )\n if n_classes == 2:\n expected_loss = 1.3133\n else:\n logits = age_weight * age + bias\n logits_exp = np.exp(logits)\n softmax = logits_exp / logits_exp.sum()\n expected_loss = -1 * math.log(softmax[0, label])\n\n mock_optimizer = self._mock_optimizer(expected_loss=expected_loss)\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n optimizer=mock_optimizer,\n model_dir=self._model_dir)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n est.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n n_classes,\n expected_global_step=initial_global_step + num_steps,\n expected_age_weight=age_weight,\n expected_bias=bias)\n\n def testBinaryClassesFromCheckpoint(self):\n self._testFromCheckpoint(n_classes=2)\n\n def testMultiClassesFromCheckpoint(self):\n self._testFromCheckpoint(n_classes=4)\n\n def _testFromCheckpointFloatLabels(self, n_classes):\n \"\"\"Tests float labels for binary classification.\"\"\"\n # Create initial checkpoint.\n if n_classes > 2:\n return\n label = 0.8\n age = 17\n age_weight = [[2.0]]\n bias = [-35.0]\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n # logits = age * age_weight + bias = 17 * 2. - 35. = -1.\n # loss = sigmoid_cross_entropy(logits, label)\n # => loss = -0.8 * log(sigmoid(-1)) -0.2 * log(sigmoid(+1)) = 1.1132617\n mock_optimizer = self._mock_optimizer(expected_loss=1.1132617)\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n optimizer=mock_optimizer,\n model_dir=self._model_dir)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n est.train(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n\n def testBinaryClassesFromCheckpointFloatLabels(self):\n self._testFromCheckpointFloatLabels(n_classes=2)\n\n def testMultiClassesFromCheckpointFloatLabels(self):\n self._testFromCheckpointFloatLabels(n_classes=4)\n\n def _testFromCheckpointMultiBatch(self, n_classes):\n # Create initial checkpoint.\n label = [1, 0]\n age = [17.0, 18.5]\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[2.0]] if n_classes == 2 else (np.reshape(\n 2.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n # For binary classifier:\n # logits = age * age_weight + bias\n # logits[0] = 17 * 2. - 35. = -1.\n # logits[1] = 18.5 * 2. - 35. = 2.\n # loss = sigmoid_cross_entropy(logits, label)\n # so, loss[0] = 1 * -log ( sigmoid(-1) ) = 1.3133\n # loss[1] = (1 - 0) * -log ( 1- sigmoid(2) ) = 2.1269\n # expected_loss = loss[0] + loss[1]\n # For multi class classifier:\n # loss = cross_entropy(logits, label)\n # where logits = [17, 18.5] * age_weight + bias and label = [1, 0]\n # so, loss = 1 * -log ( soft_max(logits)[label] )\n # expected_loss = loss[0] + loss[1]\n if n_classes == 2:\n expected_loss = 1.3133 + 2.1269\n else:\n logits = age_weight * np.reshape(age, (2, 1)) + bias\n logits_exp = np.exp(logits)\n softmax_row_0 = logits_exp[0] / logits_exp[0].sum()\n softmax_row_1 = logits_exp[1] / logits_exp[1].sum()\n expected_loss_0 = -1 * math.log(softmax_row_0[label[0]])\n expected_loss_1 = -1 * math.log(softmax_row_1[label[1]])\n expected_loss = expected_loss_0 + expected_loss_1\n\n mock_optimizer = self._mock_optimizer(expected_loss=expected_loss)\n\n est = linear.LinearClassifier(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n optimizer=mock_optimizer,\n model_dir=self._model_dir)\n self.assertEqual(0, mock_optimizer.minimize.call_count)\n\n # Train for a few steps, and validate optimizer and final checkpoint.\n num_steps = 10\n est.train(input_fn=lambda: ({'age': (age)}, (label)), steps=num_steps)\n self.assertEqual(1, mock_optimizer.minimize.call_count)\n self._assert_checkpoint(\n n_classes,\n expected_global_step=initial_global_step + num_steps,\n expected_age_weight=age_weight,\n expected_bias=bias)\n\n def testBinaryClassesFromCheckpointMultiBatch(self):\n self._testFromCheckpointMultiBatch(n_classes=2)\n\n def testMultiClassesFromCheckpointMultiBatch(self):\n self._testFromCheckpointMultiBatch(n_classes=4)\n\n\nclass BaseLinearClassifierEvaluationTest(object):\n\n def __init__(self, linear_classifier_fn, fc_lib=feature_column):\n self._linear_classifier_fn = linear_classifier_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n shutil.rmtree(self._model_dir)\n\n def _test_evaluation_for_simple_data(self, n_classes):\n label = 1\n age = 1.\n\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[-11.0]] if n_classes == 2 else (np.reshape(\n -11.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [-30.0] if n_classes == 2 else [-30.0] * n_classes\n\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n est = self._linear_classifier_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n model_dir=self._model_dir)\n eval_metrics = est.evaluate(\n input_fn=lambda: ({\n 'age': ((age,),)\n }, ((label,),)), steps=1)\n\n if n_classes == 2:\n # Binary classes: loss = sum(corss_entropy(41)) = 41.\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: 41.,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.LOSS_MEAN: 41.,\n metric_keys.MetricKeys.ACCURACY: 0.,\n metric_keys.MetricKeys.PRECISION: 0.,\n metric_keys.MetricKeys.RECALL: 0.,\n metric_keys.MetricKeys.PREDICTION_MEAN: 0.,\n metric_keys.MetricKeys.LABEL_MEAN: 1.,\n metric_keys.MetricKeys.ACCURACY_BASELINE: 1,\n metric_keys.MetricKeys.AUC: 0.,\n metric_keys.MetricKeys.AUC_PR: 1.,\n }\n else:\n # Multi classes: loss = 1 * -log ( soft_max(logits)[label] )\n logits = age_weight * age + bias\n logits_exp = np.exp(logits)\n softmax = logits_exp / logits_exp.sum()\n expected_loss = -1 * math.log(softmax[0, label])\n\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: expected_loss,\n metric_keys.MetricKeys.LOSS_MEAN: expected_loss,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.ACCURACY: 0.,\n }\n\n self.assertAllClose(\n sorted_key_dict(expected_metrics),\n sorted_key_dict(eval_metrics),\n rtol=1e-3)\n\n def test_binary_classes_evaluation_for_simple_data(self):\n self._test_evaluation_for_simple_data(n_classes=2)\n\n def test_multi_classes_evaluation_for_simple_data(self):\n self._test_evaluation_for_simple_data(n_classes=4)\n\n def _test_evaluation_batch(self, n_classes):\n \"\"\"Tests evaluation for batch_size==2.\"\"\"\n label = [1, 0]\n age = [17., 18.]\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[2.0]] if n_classes == 2 else (np.reshape(\n 2.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n est = self._linear_classifier_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n model_dir=self._model_dir)\n eval_metrics = est.evaluate(\n input_fn=lambda: ({\n 'age': (age)\n }, (label)), steps=1)\n\n if n_classes == 2:\n # Logits are (-1., 1.) labels are (1, 0).\n # Loss is\n # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133\n # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133\n expected_loss = 1.3133 * 2\n\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: expected_loss,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2,\n metric_keys.MetricKeys.ACCURACY: 0.,\n metric_keys.MetricKeys.PRECISION: 0.,\n metric_keys.MetricKeys.RECALL: 0.,\n metric_keys.MetricKeys.PREDICTION_MEAN: 0.5,\n metric_keys.MetricKeys.LABEL_MEAN: 0.5,\n metric_keys.MetricKeys.ACCURACY_BASELINE: 0.5,\n metric_keys.MetricKeys.AUC: 0.,\n metric_keys.MetricKeys.AUC_PR: 0.25,\n }\n else:\n # Multi classes: loss = 1 * -log ( soft_max(logits)[label] )\n logits = age_weight * np.reshape(age, (2, 1)) + bias\n logits_exp = np.exp(logits)\n softmax_row_0 = logits_exp[0] / logits_exp[0].sum()\n softmax_row_1 = logits_exp[1] / logits_exp[1].sum()\n expected_loss_0 = -1 * math.log(softmax_row_0[label[0]])\n expected_loss_1 = -1 * math.log(softmax_row_1[label[1]])\n expected_loss = expected_loss_0 + expected_loss_1\n\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: expected_loss,\n metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.ACCURACY: 0.,\n }\n\n self.assertAllClose(\n sorted_key_dict(expected_metrics),\n sorted_key_dict(eval_metrics),\n rtol=1e-3)\n\n def test_binary_classes_evaluation_batch(self):\n self._test_evaluation_batch(n_classes=2)\n\n def test_multi_classes_evaluation_batch(self):\n self._test_evaluation_batch(n_classes=4)\n\n def _test_evaluation_weights(self, n_classes):\n \"\"\"Tests evaluation with weights.\"\"\"\n\n label = [1, 0]\n age = [17., 18.]\n weights = [1., 2.]\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[2.0]] if n_classes == 2 else (np.reshape(\n 2.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes\n initial_global_step = 100\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(\n initial_global_step,\n name=tf.compat.v1.GraphKeys.GLOBAL_STEP,\n dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n est = self._linear_classifier_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n n_classes=n_classes,\n weight_column='w',\n model_dir=self._model_dir)\n eval_metrics = est.evaluate(\n input_fn=lambda: ({\n 'age': (age),\n 'w': (weights)\n }, (label)), steps=1)\n\n if n_classes == 2:\n # Logits are (-1., 1.) labels are (1, 0).\n # Loss is\n # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133\n # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133\n # weights = [1., 2.]\n expected_loss = 1.3133 * (1. + 2.)\n loss_mean = expected_loss / (1.0 + 2.0)\n label_mean = np.average(label, weights=weights)\n logits = [-1, 1]\n logistics = sigmoid(np.array(logits))\n predictions_mean = np.average(logistics, weights=weights)\n\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: expected_loss,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.LOSS_MEAN: loss_mean,\n metric_keys.MetricKeys.ACCURACY: 0.,\n metric_keys.MetricKeys.PRECISION: 0.,\n metric_keys.MetricKeys.RECALL: 0.,\n metric_keys.MetricKeys.PREDICTION_MEAN: predictions_mean,\n metric_keys.MetricKeys.LABEL_MEAN: label_mean,\n metric_keys.MetricKeys.ACCURACY_BASELINE:\n (max(label_mean, 1 - label_mean)),\n metric_keys.MetricKeys.AUC: 0.,\n metric_keys.MetricKeys.AUC_PR: 0.1668,\n }\n else:\n # Multi classes: unweighted_loss = 1 * -log ( soft_max(logits)[label] )\n logits = age_weight * np.reshape(age, (2, 1)) + bias\n logits_exp = np.exp(logits)\n softmax_row_0 = logits_exp[0] / logits_exp[0].sum()\n softmax_row_1 = logits_exp[1] / logits_exp[1].sum()\n expected_loss_0 = -1 * math.log(softmax_row_0[label[0]])\n expected_loss_1 = -1 * math.log(softmax_row_1[label[1]])\n loss_mean = np.average([expected_loss_0, expected_loss_1],\n weights=weights)\n expected_loss = loss_mean * np.sum(weights)\n\n expected_metrics = {\n metric_keys.MetricKeys.LOSS: expected_loss,\n metric_keys.MetricKeys.LOSS_MEAN: loss_mean,\n tf.compat.v1.GraphKeys.GLOBAL_STEP: 100,\n metric_keys.MetricKeys.ACCURACY: 0.,\n }\n\n self.assertAllClose(\n sorted_key_dict(expected_metrics),\n sorted_key_dict(eval_metrics),\n rtol=1e-3)\n\n def test_binary_classes_evaluation_weights(self):\n self._test_evaluation_weights(n_classes=2)\n\n def test_multi_classes_evaluation_weights(self):\n self._test_evaluation_weights(n_classes=4)\n\n\nclass BaseLinearClassifierPredictTest(object):\n\n def __init__(self, linear_classifier_fn, fc_lib=feature_column):\n self._linear_classifier_fn = linear_classifier_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n shutil.rmtree(self._model_dir)\n\n def _testPredictions(self, n_classes, label_vocabulary, label_output_fn):\n \"\"\"Tests predict when all variables are one-dimensional.\"\"\"\n age = 1.\n\n # For binary case, the expected weight has shape (1,1). For multi class\n # case, the shape is (1, n_classes). In order to test the weights, set\n # weights as 2.0 * range(n_classes).\n age_weight = [[-11.0]] if n_classes == 2 else (np.reshape(\n -11.0 * np.array(list(range(n_classes)), dtype=np.float32),\n (1, n_classes)))\n bias = [10.0] if n_classes == 2 else [10.0] * n_classes\n\n with tf.Graph().as_default():\n tf.Variable(age_weight, name=AGE_WEIGHT_NAME)\n tf.Variable(bias, name=BIAS_NAME)\n tf.Variable(100, name='global_step', dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n est = self._linear_classifier_fn(\n feature_columns=(self._fc_lib.numeric_column('age'),),\n label_vocabulary=label_vocabulary,\n n_classes=n_classes,\n model_dir=self._model_dir)\n\n predict_input_fn = numpy_io.numpy_input_fn(\n x={'age': np.array([[age]])},\n y=None,\n batch_size=1,\n num_epochs=1,\n shuffle=False)\n predictions = list(est.predict(input_fn=predict_input_fn))\n\n if n_classes == 2:\n scalar_logits = np.asscalar(\n np.reshape(np.array(age_weight) * age + bias, (1,)))\n two_classes_logits = [0, scalar_logits]\n two_classes_logits_exp = np.exp(two_classes_logits)\n softmax = two_classes_logits_exp / two_classes_logits_exp.sum()\n\n expected_predictions = {\n 'class_ids': [0],\n 'all_class_ids': [0, 1],\n 'classes': [label_output_fn(0)],\n 'all_classes': [label_output_fn(0),\n label_output_fn(1)],\n 'logistic': [sigmoid(np.array(scalar_logits))],\n 'logits': [scalar_logits],\n 'probabilities': softmax,\n }\n else:\n onedim_logits = np.reshape(np.array(age_weight) * age + bias, (-1,))\n class_ids = onedim_logits.argmax()\n all_class_ids = list(range(len(onedim_logits)))\n logits_exp = np.exp(onedim_logits)\n softmax = logits_exp / logits_exp.sum()\n expected_predictions = {\n 'class_ids': [class_ids],\n 'all_class_ids': all_class_ids,\n 'classes': [label_output_fn(class_ids)],\n 'all_classes': [label_output_fn(i) for i in all_class_ids],\n 'logits': onedim_logits,\n 'probabilities': softmax,\n }\n\n self.assertEqual(1, len(predictions))\n # assertAllClose cannot handle byte type.\n self.assertEqual(expected_predictions['classes'], predictions[0]['classes'])\n expected_predictions.pop('classes')\n predictions[0].pop('classes')\n self.assertAllEqual(expected_predictions['all_classes'],\n predictions[0]['all_classes'])\n expected_predictions.pop('all_classes')\n predictions[0].pop('all_classes')\n self.assertAllClose(\n sorted_key_dict(expected_predictions), sorted_key_dict(predictions[0]))\n\n def testBinaryClassesWithoutLabelVocabulary(self):\n n_classes = 2\n self._testPredictions(\n n_classes,\n label_vocabulary=None,\n label_output_fn=lambda x: ('%s' % x).encode())\n\n def testBinaryClassesWithLabelVocabulary(self):\n n_classes = 2\n self._testPredictions(\n n_classes,\n label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)],\n label_output_fn=lambda x: ('class_vocab_%s' % x).encode())\n\n def testMultiClassesWithoutLabelVocabulary(self):\n n_classes = 4\n self._testPredictions(\n n_classes,\n label_vocabulary=None,\n label_output_fn=lambda x: ('%s' % x).encode())\n\n def testMultiClassesWithLabelVocabulary(self):\n n_classes = 4\n self._testPredictions(\n n_classes,\n label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)],\n label_output_fn=lambda x: ('class_vocab_%s' % x).encode())\n\n def testSparseCombiner(self):\n w_a = 2.0\n w_b = 3.0\n w_c = 5.0\n bias = 5.0\n with tf.Graph().as_default():\n tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME)\n tf.Variable([bias], name=BIAS_NAME)\n tf.Variable(\n 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64)\n save_variables_to_ckpt(self._model_dir)\n\n def _input_fn():\n return tf.compat.v1.data.Dataset.from_tensors({\n 'language':\n tf.sparse.SparseTensor(\n values=['a', 'c', 'b', 'c'],\n indices=[[0, 0], [0, 1], [1, 0], [1, 1]],\n dense_shape=[2, 2]),\n })\n\n feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list(\n 'language', vocabulary_list=['a', 'b', 'c']),)\n\n # Check prediction for each sparse_combiner.\n # With sparse_combiner = 'sum', we have\n # logits_1 = w_a + w_c + bias\n # = 2.0 + 5.0 + 5.0 = 12.0\n # logits_2 = w_b + w_c + bias\n # = 3.0 + 5.0 + 5.0 = 13.0\n linear_classifier = self._linear_classifier_fn(\n feature_columns=feature_columns, model_dir=self._model_dir)\n predictions = linear_classifier.predict(input_fn=_input_fn)\n predicted_scores = list([x['logits'] for x in predictions])\n self.assertAllClose([[12.0], [13.0]], predicted_scores)\n\n # With sparse_combiner = 'mean', we have\n # logits_1 = 1/2 * (w_a + w_c) + bias\n # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5\n # logits_2 = 1/2 * (w_b + w_c) + bias\n # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0\n linear_classifier = self._linear_classifier_fn(\n feature_columns=feature_columns,\n model_dir=self._model_dir,\n sparse_combiner='mean')\n predictions = linear_classifier.predict(input_fn=_input_fn)\n predicted_scores = list([x['logits'] for x in predictions])\n self.assertAllClose([[8.5], [9.0]], predicted_scores)\n\n # With sparse_combiner = 'sqrtn', we have\n # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias\n # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974\n # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias\n # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685\n linear_classifier = self._linear_classifier_fn(\n feature_columns=feature_columns,\n model_dir=self._model_dir,\n sparse_combiner='sqrtn')\n predictions = linear_classifier.predict(input_fn=_input_fn)\n predicted_scores = list([x['logits'] for x in predictions])\n self.assertAllClose([[9.94974], [10.65685]], predicted_scores)\n\n\nclass BaseLinearClassifierIntegrationTest(object):\n\n def __init__(self, linear_classifier_fn, fc_lib=feature_column):\n self._linear_classifier_fn = linear_classifier_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n shutil.rmtree(self._model_dir)\n\n def _test_complete_flow(self, n_classes, train_input_fn, eval_input_fn,\n predict_input_fn, input_dimension, prediction_length):\n feature_columns = [\n self._fc_lib.numeric_column('x', shape=(input_dimension,))\n ]\n est = self._linear_classifier_fn(\n feature_columns=feature_columns,\n n_classes=n_classes,\n model_dir=self._model_dir)\n\n # TRAIN\n # learn y = x\n est.train(train_input_fn, steps=200)\n\n # EVALUTE\n scores = est.evaluate(eval_input_fn)\n self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP])\n self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores))\n\n # PREDICT\n predictions = np.array(\n [x['classes'] for x in est.predict(predict_input_fn)])\n self.assertAllEqual((prediction_length, 1), predictions.shape)\n\n # EXPORT\n feature_spec = tf.compat.v1.feature_column.make_parse_example_spec(\n feature_columns)\n serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn(\n feature_spec)\n export_dir = est.export_saved_model(tempfile.mkdtemp(),\n serving_input_receiver_fn)\n self.assertTrue(tf.compat.v1.gfile.Exists(export_dir))\n\n def _test_numpy_input_fn(self, n_classes):\n \"\"\"Tests complete flow with numpy_input_fn.\"\"\"\n input_dimension = 4\n batch_size = 10\n prediction_length = batch_size\n data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32)\n data = data.reshape(batch_size, input_dimension)\n target = np.array([1] * batch_size)\n\n train_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=target,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n eval_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=target,\n batch_size=batch_size,\n num_epochs=1,\n shuffle=False)\n predict_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=None,\n batch_size=batch_size,\n num_epochs=1,\n shuffle=False)\n\n self._test_complete_flow(\n n_classes=n_classes,\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=input_dimension,\n prediction_length=prediction_length)\n\n def test_binary_classes_numpy_input_fn(self):\n self._test_numpy_input_fn(n_classes=2)\n\n def test_multi_classes_numpy_input_fn(self):\n self._test_numpy_input_fn(n_classes=4)\n\n def _test_pandas_input_fn(self, n_classes):\n \"\"\"Tests complete flow with pandas_input_fn.\"\"\"\n if not HAS_PANDAS:\n return\n\n # Pandas DataFrame natually supports 1 dim data only.\n input_dimension = 1\n batch_size = 10\n data = np.array([1., 2., 3., 4.], dtype=np.float32)\n target = np.array([1, 0, 1, 0], dtype=np.int32)\n x = pd.DataFrame({'x': data})\n y = pd.Series(target)\n prediction_length = 4\n\n train_input_fn = pandas_io.pandas_input_fn(\n x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True)\n eval_input_fn = pandas_io.pandas_input_fn(\n x=x, y=y, batch_size=batch_size, shuffle=False)\n predict_input_fn = pandas_io.pandas_input_fn(\n x=x, batch_size=batch_size, shuffle=False)\n\n self._test_complete_flow(\n n_classes=n_classes,\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=input_dimension,\n prediction_length=prediction_length)\n\n def test_binary_classes_pandas_input_fn(self):\n self._test_pandas_input_fn(n_classes=2)\n\n def test_multi_classes_pandas_input_fn(self):\n self._test_pandas_input_fn(n_classes=4)\n\n def _test_input_fn_from_parse_example(self, n_classes):\n \"\"\"Tests complete flow with input_fn constructed from parse_example.\"\"\"\n input_dimension = 2\n batch_size = 10\n prediction_length = batch_size\n data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32)\n data = data.reshape(batch_size, input_dimension)\n target = np.array([1] * batch_size, dtype=np.int64)\n\n serialized_examples = []\n for x, y in zip(data, target):\n example = example_pb2.Example(\n features=feature_pb2.Features(\n feature={\n 'x':\n feature_pb2.Feature(\n float_list=feature_pb2.FloatList(value=x)),\n 'y':\n feature_pb2.Feature(\n int64_list=feature_pb2.Int64List(value=[y])),\n }))\n serialized_examples.append(example.SerializeToString())\n\n feature_spec = {\n 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32),\n 'y': tf.io.FixedLenFeature([1], tf.dtypes.int64),\n }\n\n def _train_input_fn():\n feature_map = tf.compat.v1.io.parse_example(serialized_examples,\n feature_spec)\n features = queue_parsed_features(feature_map)\n labels = features.pop('y')\n return features, labels\n\n def _eval_input_fn():\n feature_map = tf.compat.v1.io.parse_example(\n tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1),\n feature_spec)\n features = queue_parsed_features(feature_map)\n labels = features.pop('y')\n return features, labels\n\n def _predict_input_fn():\n feature_map = tf.compat.v1.io.parse_example(\n tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1),\n feature_spec)\n features = queue_parsed_features(feature_map)\n features.pop('y')\n return features, None\n\n self._test_complete_flow(\n n_classes=n_classes,\n train_input_fn=_train_input_fn,\n eval_input_fn=_eval_input_fn,\n predict_input_fn=_predict_input_fn,\n input_dimension=input_dimension,\n prediction_length=prediction_length)\n\n def test_binary_classes_input_fn_from_parse_example(self):\n self._test_input_fn_from_parse_example(n_classes=2)\n\n def test_multi_classes_input_fn_from_parse_example(self):\n self._test_input_fn_from_parse_example(n_classes=4)\n\n\nclass BaseLinearLogitFnTest(object):\n\n def __init__(self, fc_lib=feature_column):\n self._fc_lib = fc_lib\n\n def test_basic_logit_correctness(self):\n \"\"\"linear_logit_fn simply wraps feature_column_lib.linear_model.\"\"\"\n age = self._fc_lib.numeric_column('age')\n with tf.Graph().as_default():\n logit_fn = linear.linear_logit_fn_builder(units=2, feature_columns=[age])\n logits = logit_fn(features={'age': [[23.], [31.]]})\n bias_var = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.GLOBAL_VARIABLES,\n 'linear_model/bias_weights')[0]\n age_var = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0]\n with tf.compat.v1.Session() as sess:\n sess.run([tf.compat.v1.initializers.global_variables()])\n self.assertAllClose([[0., 0.], [0., 0.]], logits.eval())\n sess.run(bias_var.assign([10., 5.]))\n self.assertAllClose([[10., 5.], [10., 5.]], logits.eval())\n sess.run(age_var.assign([[2.0, 3.0]]))\n # [2 * 23 + 10, 3 * 23 + 5] = [56, 74].\n # [2 * 31 + 10, 3 * 31 + 5] = [72, 98]\n self.assertAllClose([[56., 74.], [72., 98.]], logits.eval())\n\n def test_compute_fraction_of_zero(self):\n \"\"\"Tests the calculation of sparsity.\"\"\"\n if self._fc_lib != feature_column:\n return\n age = tf.feature_column.numeric_column('age')\n occupation = feature_column.categorical_column_with_hash_bucket(\n 'occupation', hash_bucket_size=5)\n with tf.Graph().as_default():\n cols_to_vars = {}\n tf.compat.v1.feature_column.linear_model(\n features={\n 'age': [[23.], [31.]],\n 'occupation': [['doctor'], ['engineer']]\n },\n feature_columns=[age, occupation],\n units=3,\n cols_to_vars=cols_to_vars)\n cols_to_vars.pop('bias')\n fraction_zero = linear._compute_fraction_of_zero(\n list(cols_to_vars.values()))\n age_var = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0]\n with tf.compat.v1.Session() as sess:\n sess.run([tf.compat.v1.initializers.global_variables()])\n # Upon initialization, all variables will be zero.\n self.assertAllClose(1, fraction_zero.eval())\n\n sess.run(age_var.assign([[2.0, 0.0, -1.0]]))\n # 1 of the 3 age weights are zero, and all of the 15 (5 hash buckets\n # x 3-dim output) are zero.\n self.assertAllClose(16. / 18., fraction_zero.eval())\n\n def test_compute_fraction_of_zero_v2(self):\n \"\"\"Tests the calculation of sparsity.\"\"\"\n if self._fc_lib != feature_column_v2:\n return\n\n age = tf.feature_column.numeric_column('age')\n occupation = tf.feature_column.categorical_column_with_hash_bucket(\n 'occupation', hash_bucket_size=5)\n with tf.Graph().as_default():\n model = feature_column_v2.LinearModel(\n feature_columns=[age, occupation], units=3, name='linear_model')\n features = {\n 'age': [[23.], [31.]],\n 'occupation': [['doctor'], ['engineer']]\n }\n model(features)\n variables = model.variables\n variables.remove(model.bias)\n fraction_zero = linear._compute_fraction_of_zero(variables)\n age_var = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0]\n with tf.compat.v1.Session() as sess:\n sess.run([tf.compat.v1.initializers.global_variables()])\n # Upon initialization, all variables will be zero.\n self.assertAllClose(1, fraction_zero.eval())\n\n sess.run(age_var.assign([[2.0, 0.0, -1.0]]))\n # 1 of the 3 age weights are zero, and all of the 15 (5 hash buckets\n # x 3-dim output) are zero.\n self.assertAllClose(16. / 18., fraction_zero.eval())\n\n\nclass BaseLinearWarmStartingTest(object):\n\n def __init__(self,\n _linear_classifier_fn,\n _linear_regressor_fn,\n fc_lib=feature_column):\n self._linear_classifier_fn = _linear_classifier_fn\n self._linear_regressor_fn = _linear_regressor_fn\n self._fc_lib = fc_lib\n\n def setUp(self):\n # Create a directory to save our old checkpoint and vocabularies to.\n self._ckpt_and_vocab_dir = tempfile.mkdtemp()\n\n # Make a dummy input_fn.\n def _input_fn():\n features = {\n 'age': [[23.], [31.]],\n 'age_in_years': [[23.], [31.]],\n 'occupation': [['doctor'], ['consultant']]\n }\n return features, [0, 1]\n\n self._input_fn = _input_fn\n\n def tearDown(self):\n # Clean up checkpoint / vocab dir.\n tf.compat.v1.summary.FileWriterCache.clear()\n shutil.rmtree(self._ckpt_and_vocab_dir)\n\n def test_classifier_basic_warm_starting(self):\n \"\"\"Tests correctness of LinearClassifier default warm-start.\"\"\"\n age = self._fc_lib.numeric_column('age')\n\n # Create a LinearClassifier and train to save a checkpoint.\n linear_classifier = self._linear_classifier_fn(\n feature_columns=[age],\n model_dir=self._ckpt_and_vocab_dir,\n n_classes=4,\n optimizer='SGD')\n linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n\n # Create a second LinearClassifier, warm-started from the first. Use a\n # learning_rate = 0.0 optimizer to check values (use SGD so we don't have\n # accumulator values that change).\n warm_started_linear_classifier = self._linear_classifier_fn(\n feature_columns=[age],\n n_classes=4,\n optimizer=tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate=0.0),\n warm_start_from=linear_classifier.model_dir)\n\n warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n for variable_name in warm_started_linear_classifier.get_variable_names():\n self.assertAllClose(\n linear_classifier.get_variable_value(variable_name),\n warm_started_linear_classifier.get_variable_value(variable_name))\n\n def test_regressor_basic_warm_starting(self):\n \"\"\"Tests correctness of LinearRegressor default warm-start.\"\"\"\n age = self._fc_lib.numeric_column('age')\n\n # Create a LinearRegressor and train to save a checkpoint.\n linear_regressor = self._linear_regressor_fn(\n feature_columns=[age],\n model_dir=self._ckpt_and_vocab_dir,\n optimizer='SGD')\n linear_regressor.train(input_fn=self._input_fn, max_steps=1)\n\n # Create a second LinearRegressor, warm-started from the first. Use a\n # learning_rate = 0.0 optimizer to check values (use SGD so we don't have\n # accumulator values that change).\n warm_started_linear_regressor = self._linear_regressor_fn(\n feature_columns=[age],\n optimizer=tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate=0.0),\n warm_start_from=linear_regressor.model_dir)\n\n warm_started_linear_regressor.train(input_fn=self._input_fn, max_steps=1)\n for variable_name in warm_started_linear_regressor.get_variable_names():\n self.assertAllClose(\n linear_regressor.get_variable_value(variable_name),\n warm_started_linear_regressor.get_variable_value(variable_name))\n\n def test_warm_starting_selective_variables(self):\n \"\"\"Tests selecting variables to warm-start.\"\"\"\n age = self._fc_lib.numeric_column('age')\n\n # Create a LinearClassifier and train to save a checkpoint.\n linear_classifier = self._linear_classifier_fn(\n feature_columns=[age],\n model_dir=self._ckpt_and_vocab_dir,\n n_classes=4,\n optimizer='SGD')\n linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n\n # Create a second LinearClassifier, warm-started from the first. Use a\n # learning_rate = 0.0 optimizer to check values (use SGD so we don't have\n # accumulator values that change).\n warm_started_linear_classifier = self._linear_classifier_fn(\n feature_columns=[age],\n n_classes=4,\n optimizer=tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate=0.0),\n # The provided regular expression will only warm-start the age variable\n # and not the bias.\n warm_start_from=estimator.WarmStartSettings(\n ckpt_to_initialize_from=linear_classifier.model_dir,\n vars_to_warm_start='.*(age).*'))\n\n warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n self.assertAllClose(\n linear_classifier.get_variable_value(AGE_WEIGHT_NAME),\n warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME))\n # Bias should still be zero from initialization.\n self.assertAllClose(\n [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME))\n\n def test_warm_starting_with_vocab_remapping_and_partitioning(self):\n \"\"\"Tests warm-starting with vocab remapping and partitioning.\"\"\"\n vocab_list = ['doctor', 'lawyer', 'consultant']\n vocab_file = os.path.join(self._ckpt_and_vocab_dir, 'occupation_vocab')\n with open(vocab_file, 'w') as f:\n f.write('\\n'.join(vocab_list))\n occupation = self._fc_lib.categorical_column_with_vocabulary_file(\n 'occupation',\n vocabulary_file=vocab_file,\n vocabulary_size=len(vocab_list))\n\n # Create a LinearClassifier and train to save a checkpoint.\n partitioner = tf.compat.v1.fixed_size_partitioner(num_shards=2)\n linear_classifier = self._linear_classifier_fn(\n feature_columns=[occupation],\n model_dir=self._ckpt_and_vocab_dir,\n n_classes=4,\n optimizer='SGD',\n partitioner=partitioner)\n linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n\n # Create a second LinearClassifier, warm-started from the first. Use a\n # learning_rate = 0.0 optimizer to check values (use SGD so we don't have\n # accumulator values that change). Use a new FeatureColumn with a\n # different vocabulary for occupation.\n new_vocab_list = ['doctor', 'consultant', 'engineer']\n new_vocab_file = os.path.join(self._ckpt_and_vocab_dir,\n 'new_occupation_vocab')\n with open(new_vocab_file, 'w') as f:\n f.write('\\n'.join(new_vocab_list))\n new_occupation = self._fc_lib.categorical_column_with_vocabulary_file(\n 'occupation',\n vocabulary_file=new_vocab_file,\n vocabulary_size=len(new_vocab_list))\n # We can create our VocabInfo object from the new and old occupation\n # FeatureColumn's.\n occupation_vocab_info = estimator.VocabInfo(\n new_vocab=new_occupation.vocabulary_file,\n new_vocab_size=new_occupation.vocabulary_size,\n num_oov_buckets=new_occupation.num_oov_buckets,\n old_vocab=occupation.vocabulary_file,\n old_vocab_size=occupation.vocabulary_size,\n # Can't use constant_initializer with load_and_remap. In practice,\n # use a truncated normal initializer.\n backup_initializer=tf.compat.v1.initializers.random_uniform(\n minval=0.39, maxval=0.39))\n warm_started_linear_classifier = self._linear_classifier_fn(\n feature_columns=[occupation],\n n_classes=4,\n optimizer=tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate=0.0),\n warm_start_from=estimator.WarmStartSettings(\n ckpt_to_initialize_from=linear_classifier.model_dir,\n var_name_to_vocab_info={\n OCCUPATION_WEIGHT_NAME: occupation_vocab_info\n },\n # Explicitly providing None here will only warm-start variables\n # referenced in var_name_to_vocab_info (the bias will not be\n # warm-started).\n vars_to_warm_start=None),\n partitioner=partitioner)\n\n warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n # 'doctor' was ID-0 and still ID-0.\n self.assertAllClose(\n linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[0, :],\n warm_started_linear_classifier.get_variable_value(\n OCCUPATION_WEIGHT_NAME)[0, :])\n # 'consultant' was ID-2 and now ID-1.\n self.assertAllClose(\n linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[2, :],\n warm_started_linear_classifier.get_variable_value(\n OCCUPATION_WEIGHT_NAME)[1, :])\n # 'engineer' is a new entry and should be initialized with the\n # backup_initializer in VocabInfo.\n self.assertAllClose([0.39] * 4,\n warm_started_linear_classifier.get_variable_value(\n OCCUPATION_WEIGHT_NAME)[2, :])\n # Bias should still be zero (from initialization logic).\n self.assertAllClose(\n [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME))\n\n def test_warm_starting_with_naming_change(self):\n \"\"\"Tests warm-starting with a Tensor name remapping.\"\"\"\n age_in_years = self._fc_lib.numeric_column('age_in_years')\n\n # Create a LinearClassifier and train to save a checkpoint.\n linear_classifier = self._linear_classifier_fn(\n feature_columns=[age_in_years],\n model_dir=self._ckpt_and_vocab_dir,\n n_classes=4,\n optimizer='SGD')\n linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n\n # Create a second LinearClassifier, warm-started from the first. Use a\n # learning_rate = 0.0 optimizer to check values (use SGD so we don't have\n # accumulator values that change).\n warm_started_linear_classifier = self._linear_classifier_fn(\n feature_columns=[self._fc_lib.numeric_column('age')],\n n_classes=4,\n optimizer=tf.compat.v1.train.GradientDescentOptimizer(\n learning_rate=0.0),\n # The 'age' variable correspond to the 'age_in_years' variable in the\n # previous model.\n warm_start_from=estimator.WarmStartSettings(\n ckpt_to_initialize_from=linear_classifier.model_dir,\n var_name_to_prev_var_name={\n AGE_WEIGHT_NAME: AGE_WEIGHT_NAME.replace('age', 'age_in_years')\n }))\n\n warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1)\n self.assertAllClose(\n linear_classifier.get_variable_value(\n AGE_WEIGHT_NAME.replace('age', 'age_in_years')),\n warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME))\n # The bias is also warm-started (with no name remapping).\n self.assertAllClose(\n linear_classifier.get_variable_value(BIAS_NAME),\n warm_started_linear_classifier.get_variable_value(BIAS_NAME))\n", "# This file is MACHINE GENERATED! Do not edit.\n# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.\n\"\"\"Public API for tf.keras.mixed_precision namespace.\n\"\"\"\n\nfrom __future__ import print_function as _print_function\n\nimport sys as _sys\n\nfrom . import experimental\n\ndel _print_function\n\nfrom tensorflow.python.util import module_wrapper as _module_wrapper\n\nif not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):\n _sys.modules[__name__] = _module_wrapper.TFModuleWrapper(\n _sys.modules[__name__], \"keras.mixed_precision\", public_apis=None, deprecation=True,\n has_lite=False)\n", "import scipy.stats\nimport numpy as np\nfrom math import ceil\nfrom .. import img_as_float\nfrom ._denoise_cy import _denoise_bilateral, _denoise_tv_bregman\nfrom .._shared.utils import warn\nimport pywt\nimport skimage.color as color\nfrom skimage.color.colorconv import ycbcr_from_rgb\nimport numbers\n\n\ndef _gaussian_weight(array, sigma_squared, *, dtype=float):\n \"\"\"Helping function. Define a Gaussian weighting from array and\n sigma_square.\n\n Parameters\n ----------\n array : ndarray\n Input array.\n sigma_squared : float\n The squared standard deviation used in the filter.\n dtype : data type object, optional (default : float)\n The type and size of the data to be returned.\n\n Returns\n -------\n gaussian : ndarray\n The input array filtered by the Gaussian.\n \"\"\"\n return np.exp(-0.5 * (array ** 2 / sigma_squared), dtype=dtype)\n\n\ndef _compute_color_lut(bins, sigma, max_value, *, dtype=float):\n \"\"\"Helping function. Define a lookup table containing Gaussian filter\n values using the color distance sigma.\n\n Parameters\n ----------\n bins : int\n Number of discrete values for Gaussian weights of color filtering.\n A larger value results in improved accuracy.\n sigma : float\n Standard deviation for grayvalue/color distance (radiometric\n similarity). A larger value results in averaging of pixels with larger\n radiometric differences. Note, that the image will be converted using\n the `img_as_float` function and thus the standard deviation is in\n respect to the range ``[0, 1]``. If the value is ``None`` the standard\n deviation of the ``image`` will be used.\n max_value : float\n Maximum value of the input image.\n dtype : data type object, optional (default : float)\n The type and size of the data to be returned.\n\n Returns\n -------\n color_lut : ndarray\n Lookup table for the color distance sigma.\n \"\"\"\n values = np.linspace(0, max_value, bins, endpoint=False)\n return _gaussian_weight(values, sigma**2, dtype=dtype)\n\n\ndef _compute_spatial_lut(win_size, sigma, *, dtype=float):\n \"\"\"Helping function. Define a lookup table containing Gaussian filter\n values using the spatial sigma.\n\n Parameters\n ----------\n win_size : int\n Window size for filtering.\n If win_size is not specified, it is calculated as\n ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``.\n sigma : float\n Standard deviation for range distance. A larger value results in\n averaging of pixels with larger spatial differences.\n dtype : data type object\n The type and size of the data to be returned.\n\n Returns\n -------\n spatial_lut : ndarray\n Lookup table for the spatial sigma.\n \"\"\"\n grid_points = np.arange(-win_size // 2, win_size // 2 + 1)\n rr, cc = np.meshgrid(grid_points, grid_points, indexing='ij')\n distances = np.hypot(rr, cc)\n return _gaussian_weight(distances, sigma**2, dtype=dtype).ravel()\n\n\ndef denoise_bilateral(image, win_size=None, sigma_color=None, sigma_spatial=1,\n bins=10000, mode='constant', cval=0, multichannel=False):\n \"\"\"Denoise image using bilateral filter.\n\n Parameters\n ----------\n image : ndarray, shape (M, N[, 3])\n Input image, 2D grayscale or RGB.\n win_size : int\n Window size for filtering.\n If win_size is not specified, it is calculated as\n ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``.\n sigma_color : float\n Standard deviation for grayvalue/color distance (radiometric\n similarity). A larger value results in averaging of pixels with larger\n radiometric differences. Note, that the image will be converted using\n the `img_as_float` function and thus the standard deviation is in\n respect to the range ``[0, 1]``. If the value is ``None`` the standard\n deviation of the ``image`` will be used.\n sigma_spatial : float\n Standard deviation for range distance. A larger value results in\n averaging of pixels with larger spatial differences.\n bins : int\n Number of discrete values for Gaussian weights of color filtering.\n A larger value results in improved accuracy.\n mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}\n How to handle values outside the image borders. See\n `numpy.pad` for detail.\n cval : string\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n multichannel : bool\n Whether the last axis of the image is to be interpreted as multiple\n channels or another spatial dimension.\n\n Returns\n -------\n denoised : ndarray\n Denoised image.\n\n Notes\n -----\n This is an edge-preserving, denoising filter. It averages pixels based on\n their spatial closeness and radiometric similarity [1]_.\n\n Spatial closeness is measured by the Gaussian function of the Euclidean\n distance between two pixels and a certain standard deviation\n (`sigma_spatial`).\n\n Radiometric similarity is measured by the Gaussian function of the\n Euclidean distance between two color values and a certain standard\n deviation (`sigma_color`).\n\n References\n ----------\n .. [1] C. Tomasi and R. Manduchi. \"Bilateral Filtering for Gray and Color\n Images.\" IEEE International Conference on Computer Vision (1998)\n 839-846. :DOI:`10.1109/ICCV.1998.710815`\n\n Examples\n --------\n >>> from skimage import data, img_as_float\n >>> astro = img_as_float(data.astronaut())\n >>> astro = astro[220:300, 220:320]\n >>> noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape)\n >>> noisy = np.clip(noisy, 0, 1)\n >>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15,\n ... multichannel=True)\n \"\"\"\n if multichannel:\n if image.ndim != 3:\n if image.ndim == 2:\n raise ValueError(\"Use ``multichannel=False`` for 2D grayscale \"\n \"images. The last axis of the input image \"\n \"must be multiple color channels not another \"\n \"spatial dimension.\")\n else:\n raise ValueError(\"Bilateral filter is only implemented for \"\n \"2D grayscale images (image.ndim == 2) and \"\n \"2D multichannel (image.ndim == 3) images, \"\n \"but the input image has {0} dimensions. \"\n \"\".format(image.ndim))\n elif image.shape[2] not in (3, 4):\n if image.shape[2] > 4:\n msg = (\"The last axis of the input image is interpreted as \"\n \"channels. Input image with shape {0} has {1} channels \"\n \"in last axis. ``denoise_bilateral`` is implemented \"\n \"for 2D grayscale and color images only\")\n warn(msg.format(image.shape, image.shape[2]))\n else:\n msg = \"Input image must be grayscale, RGB, or RGBA; \" \\\n \"but has shape {0}.\"\n warn(msg.format(image.shape))\n else:\n if image.ndim > 2:\n raise ValueError(\"Bilateral filter is not implemented for \"\n \"grayscale images of 3 or more dimensions, \"\n \"but input image has {0} dimension. Use \"\n \"``multichannel=True`` for 2-D RGB \"\n \"images.\".format(image.shape))\n\n if win_size is None:\n win_size = max(5, 2 * int(ceil(3 * sigma_spatial)) + 1)\n\n min_value = image.min()\n max_value = image.max()\n\n if min_value == max_value:\n return image\n\n # if image.max() is 0, then dist_scale can have an unverified value\n # and color_lut[<int>(dist * dist_scale)] may cause a segmentation fault\n # so we verify we have a positive image and that the max is not 0.0.\n if min_value < 0.0:\n raise ValueError(\"Image must contain only positive values\")\n\n if max_value == 0.0:\n raise ValueError(\"The maximum value found in the image was 0.\")\n\n image = np.atleast_3d(img_as_float(image))\n image = np.ascontiguousarray(image)\n\n sigma_color = sigma_color or image.std()\n\n color_lut = _compute_color_lut(bins, sigma_color, max_value,\n dtype=image.dtype)\n\n range_lut = _compute_spatial_lut(win_size, sigma_spatial, dtype=image.dtype)\n\n out = np.empty(image.shape, dtype=image.dtype)\n\n dims = image.shape[2]\n\n # There are a number of arrays needed in the Cython function.\n # It's easier to allocate them outside of Cython so that all\n # arrays are in the same type, then just copy the empty array\n # where needed within Cython.\n empty_dims = np.empty(dims, dtype=image.dtype)\n\n return _denoise_bilateral(image, image.max(), win_size, sigma_color,\n sigma_spatial, bins, mode, cval, color_lut,\n range_lut, empty_dims, out)\n\n\ndef denoise_tv_bregman(image, weight, max_iter=100, eps=1e-3, isotropic=True,\n *, multichannel=False):\n \"\"\"Perform total-variation denoising using split-Bregman optimization.\n\n Total-variation denoising (also know as total-variation regularization)\n tries to find an image with less total-variation under the constraint\n of being similar to the input image, which is controlled by the\n regularization parameter ([1]_, [2]_, [3]_, [4]_).\n\n Parameters\n ----------\n image : ndarray\n Input data to be denoised (converted using img_as_float`).\n weight : float\n Denoising weight. The smaller the `weight`, the more denoising (at\n the expense of less similarity to the `input`). The regularization\n parameter `lambda` is chosen as `2 * weight`.\n eps : float, optional\n Relative difference of the value of the cost function that determines\n the stop criterion. The algorithm stops when::\n\n SUM((u(n) - u(n-1))**2) < eps\n\n max_iter : int, optional\n Maximal number of iterations used for the optimization.\n isotropic : boolean, optional\n Switch between isotropic and anisotropic TV denoising.\n multichannel : bool, optional\n Apply total-variation denoising separately for each channel. This\n option should be true for color images, otherwise the denoising is\n also applied in the channels dimension.\n\n Returns\n -------\n u : ndarray\n Denoised image.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Total_variation_denoising\n .. [2] Tom Goldstein and Stanley Osher, \"The Split Bregman Method For L1\n Regularized Problems\",\n ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf\n .. [3] Pascal Getreuer, \"Rudin–Osher–Fatemi Total Variation Denoising\n using Split Bregman\" in Image Processing On Line on 2012–05–19,\n https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf\n .. [4] https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf\n\n \"\"\"\n image = np.atleast_3d(img_as_float(image))\n\n rows = image.shape[0]\n cols = image.shape[1]\n dims = image.shape[2]\n\n shape_ext = (rows + 2, cols + 2, dims)\n\n out = np.zeros(shape_ext, image.dtype)\n\n if multichannel:\n channel_out = np.zeros(shape_ext[:2] + (1,), dtype=out.dtype)\n for c in range(image.shape[-1]):\n # the algorithm below expects 3 dimensions to always be present.\n # slicing the array in this fashion preserves the channel dimension for us\n channel_in = np.ascontiguousarray(image[..., c:c+1])\n\n _denoise_tv_bregman(channel_in, image.dtype.type(weight),\n max_iter, eps, isotropic, channel_out)\n\n out[..., c] = channel_out[..., 0]\n\n else:\n image = np.ascontiguousarray(image)\n\n _denoise_tv_bregman(image, image.dtype.type(weight), max_iter, eps,\n isotropic, out)\n\n return np.squeeze(out[1:-1, 1:-1])\n\n\ndef _denoise_tv_chambolle_nd(image, weight=0.1, eps=2.e-4, n_iter_max=200):\n \"\"\"Perform total-variation denoising on n-dimensional images.\n\n Parameters\n ----------\n image : ndarray\n n-D input data to be denoised.\n weight : float, optional\n Denoising weight. The greater `weight`, the more denoising (at\n the expense of fidelity to `input`).\n eps : float, optional\n Relative difference of the value of the cost function that determines\n the stop criterion. The algorithm stops when:\n\n (E_(n-1) - E_n) < eps * E_0\n\n n_iter_max : int, optional\n Maximal number of iterations used for the optimization.\n\n Returns\n -------\n out : ndarray\n Denoised array of floats.\n\n Notes\n -----\n Rudin, Osher and Fatemi algorithm.\n \"\"\"\n\n ndim = image.ndim\n p = np.zeros((image.ndim, ) + image.shape, dtype=image.dtype)\n g = np.zeros_like(p)\n d = np.zeros_like(image)\n i = 0\n while i < n_iter_max:\n if i > 0:\n # d will be the (negative) divergence of p\n d = -p.sum(0)\n slices_d = [slice(None), ] * ndim\n slices_p = [slice(None), ] * (ndim + 1)\n for ax in range(ndim):\n slices_d[ax] = slice(1, None)\n slices_p[ax+1] = slice(0, -1)\n slices_p[0] = ax\n d[tuple(slices_d)] += p[tuple(slices_p)]\n slices_d[ax] = slice(None)\n slices_p[ax+1] = slice(None)\n out = image + d\n else:\n out = image\n E = (d ** 2).sum()\n\n # g stores the gradients of out along each axis\n # e.g. g[0] is the first order finite difference along axis 0\n slices_g = [slice(None), ] * (ndim + 1)\n for ax in range(ndim):\n slices_g[ax+1] = slice(0, -1)\n slices_g[0] = ax\n g[tuple(slices_g)] = np.diff(out, axis=ax)\n slices_g[ax+1] = slice(None)\n\n norm = np.sqrt((g ** 2).sum(axis=0))[np.newaxis, ...]\n E += weight * norm.sum()\n tau = 1. / (2.*ndim)\n norm *= tau / weight\n norm += 1.\n p -= tau * g\n p /= norm\n E /= float(image.size)\n if i == 0:\n E_init = E\n E_previous = E\n else:\n if np.abs(E_previous - E) < eps * E_init:\n break\n else:\n E_previous = E\n i += 1\n return out\n\n\ndef denoise_tv_chambolle(image, weight=0.1, eps=2.e-4, n_iter_max=200,\n multichannel=False):\n \"\"\"Perform total-variation denoising on n-dimensional images.\n\n Parameters\n ----------\n image : ndarray of ints, uints or floats\n Input data to be denoised. `image` can be of any numeric type,\n but it is cast into an ndarray of floats for the computation\n of the denoised image.\n weight : float, optional\n Denoising weight. The greater `weight`, the more denoising (at\n the expense of fidelity to `input`).\n eps : float, optional\n Relative difference of the value of the cost function that\n determines the stop criterion. The algorithm stops when:\n\n (E_(n-1) - E_n) < eps * E_0\n\n n_iter_max : int, optional\n Maximal number of iterations used for the optimization.\n multichannel : bool, optional\n Apply total-variation denoising separately for each channel. This\n option should be true for color images, otherwise the denoising is\n also applied in the channels dimension.\n\n Returns\n -------\n out : ndarray\n Denoised image.\n\n Notes\n -----\n Make sure to set the multichannel parameter appropriately for color images.\n\n The principle of total variation denoising is explained in\n https://en.wikipedia.org/wiki/Total_variation_denoising\n\n The principle of total variation denoising is to minimize the\n total variation of the image, which can be roughly described as\n the integral of the norm of the image gradient. Total variation\n denoising tends to produce \"cartoon-like\" images, that is,\n piecewise-constant images.\n\n This code is an implementation of the algorithm of Rudin, Fatemi and Osher\n that was proposed by Chambolle in [1]_.\n\n References\n ----------\n .. [1] A. Chambolle, An algorithm for total variation minimization and\n applications, Journal of Mathematical Imaging and Vision,\n Springer, 2004, 20, 89-97.\n\n Examples\n --------\n 2D example on astronaut image:\n\n >>> from skimage import color, data\n >>> img = color.rgb2gray(data.astronaut())[:50, :50]\n >>> img += 0.5 * img.std() * np.random.randn(*img.shape)\n >>> denoised_img = denoise_tv_chambolle(img, weight=60)\n\n 3D example on synthetic data:\n\n >>> x, y, z = np.ogrid[0:20, 0:20, 0:20]\n >>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2\n >>> mask = mask.astype(np.float)\n >>> mask += 0.2*np.random.randn(*mask.shape)\n >>> res = denoise_tv_chambolle(mask, weight=100)\n\n \"\"\"\n\n im_type = image.dtype\n if not im_type.kind == 'f':\n image = img_as_float(image)\n\n if multichannel:\n out = np.zeros_like(image)\n for c in range(image.shape[-1]):\n out[..., c] = _denoise_tv_chambolle_nd(image[..., c], weight, eps,\n n_iter_max)\n else:\n out = _denoise_tv_chambolle_nd(image, weight, eps, n_iter_max)\n return out\n\n\ndef _bayes_thresh(details, var):\n \"\"\"BayesShrink threshold for a zero-mean details coeff array.\"\"\"\n # Equivalent to: dvar = np.var(details) for 0-mean details array\n dvar = np.mean(details*details)\n eps = np.finfo(details.dtype).eps\n thresh = var / np.sqrt(max(dvar - var, eps))\n return thresh\n\n\ndef _universal_thresh(img, sigma):\n \"\"\" Universal threshold used by the VisuShrink method \"\"\"\n return sigma*np.sqrt(2*np.log(img.size))\n\n\ndef _sigma_est_dwt(detail_coeffs, distribution='Gaussian'):\n \"\"\"Calculate the robust median estimator of the noise standard deviation.\n\n Parameters\n ----------\n detail_coeffs : ndarray\n The detail coefficients corresponding to the discrete wavelet\n transform of an image.\n distribution : str\n The underlying noise distribution.\n\n Returns\n -------\n sigma : float\n The estimated noise standard deviation (see section 4.2 of [1]_).\n\n References\n ----------\n .. [1] D. L. Donoho and I. M. Johnstone. \"Ideal spatial adaptation\n by wavelet shrinkage.\" Biometrika 81.3 (1994): 425-455.\n :DOI:`10.1093/biomet/81.3.425`\n \"\"\"\n # Consider regions with detail coefficients exactly zero to be masked out\n detail_coeffs = detail_coeffs[np.nonzero(detail_coeffs)]\n\n if distribution.lower() == 'gaussian':\n # 75th quantile of the underlying, symmetric noise distribution\n denom = scipy.stats.norm.ppf(0.75)\n sigma = np.median(np.abs(detail_coeffs)) / denom\n else:\n raise ValueError(\"Only Gaussian noise estimation is currently \"\n \"supported\")\n return sigma\n\n\ndef _wavelet_threshold(image, wavelet, method=None, threshold=None,\n sigma=None, mode='soft', wavelet_levels=None):\n \"\"\"Perform wavelet thresholding.\n\n Parameters\n ----------\n image : ndarray (2d or 3d) of ints, uints or floats\n Input data to be denoised. `image` can be of any numeric type,\n but it is cast into an ndarray of floats for the computation\n of the denoised image.\n wavelet : string\n The type of wavelet to perform. Can be any of the options\n pywt.wavelist outputs. For example, this may be any of ``{db1, db2,\n db3, db4, haar}``.\n method : {'BayesShrink', 'VisuShrink'}, optional\n Thresholding method to be used. The currently supported methods are\n \"BayesShrink\" [1]_ and \"VisuShrink\" [2]_. If it is set to None, a\n user-specified ``threshold`` must be supplied instead.\n threshold : float, optional\n The thresholding value to apply during wavelet coefficient\n thresholding. The default value (None) uses the selected ``method`` to\n estimate appropriate threshold(s) for noise removal.\n sigma : float, optional\n The standard deviation of the noise. The noise is estimated when sigma\n is None (the default) by the method in [2]_.\n mode : {'soft', 'hard'}, optional\n An optional argument to choose the type of denoising performed. It\n noted that choosing soft thresholding given additive noise finds the\n best approximation of the original image.\n wavelet_levels : int or None, optional\n The number of wavelet decomposition levels to use. The default is\n three less than the maximum number of possible decomposition levels\n (see Notes below).\n\n Returns\n -------\n out : ndarray\n Denoised image.\n\n References\n ----------\n .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. \"Adaptive wavelet\n thresholding for image denoising and compression.\" Image Processing,\n IEEE Transactions on 9.9 (2000): 1532-1546.\n :DOI:`10.1109/83.862633`\n .. [2] D. L. Donoho and I. M. Johnstone. \"Ideal spatial adaptation\n by wavelet shrinkage.\" Biometrika 81.3 (1994): 425-455.\n :DOI:`10.1093/biomet/81.3.425`\n \"\"\"\n wavelet = pywt.Wavelet(wavelet)\n if not wavelet.orthogonal:\n warn((\"Wavelet thresholding was designed for use with orthogonal \"\n \"wavelets. For nonorthogonal wavelets such as {}, results are \"\n \"likely to be suboptimal.\").format(wavelet.name))\n\n # original_extent is used to workaround PyWavelets issue #80\n # odd-sized input results in an image with 1 extra sample after waverecn\n original_extent = tuple(slice(s) for s in image.shape)\n\n # Determine the number of wavelet decomposition levels\n if wavelet_levels is None:\n # Determine the maximum number of possible levels for image\n dlen = wavelet.dec_len\n wavelet_levels = pywt.dwtn_max_level(image.shape, wavelet)\n\n # Skip coarsest wavelet scales (see Notes in docstring).\n wavelet_levels = max(wavelet_levels - 3, 1)\n\n coeffs = pywt.wavedecn(image, wavelet=wavelet, level=wavelet_levels)\n # Detail coefficients at each decomposition level\n dcoeffs = coeffs[1:]\n\n if sigma is None:\n # Estimate the noise via the method in [2]_\n detail_coeffs = dcoeffs[-1]['d' * image.ndim]\n sigma = _sigma_est_dwt(detail_coeffs, distribution='Gaussian')\n\n if method is not None and threshold is not None:\n warn((\"Thresholding method {} selected. The user-specified threshold \"\n \"will be ignored.\").format(method))\n\n if threshold is None:\n var = sigma**2\n if method is None:\n raise ValueError(\n \"If method is None, a threshold must be provided.\")\n elif method == \"BayesShrink\":\n # The BayesShrink thresholds from [1]_ in docstring\n threshold = [{key: _bayes_thresh(level[key], var) for key in level}\n for level in dcoeffs]\n elif method == \"VisuShrink\":\n # The VisuShrink thresholds from [2]_ in docstring\n threshold = _universal_thresh(image, sigma)\n else:\n raise ValueError(\"Unrecognized method: {}\".format(method))\n\n if np.isscalar(threshold):\n # A single threshold for all coefficient arrays\n denoised_detail = [{key: pywt.threshold(level[key],\n value=threshold,\n mode=mode) for key in level}\n for level in dcoeffs]\n else:\n # Dict of unique threshold coefficients for each detail coeff. array\n denoised_detail = [{key: pywt.threshold(level[key],\n value=thresh[key],\n mode=mode) for key in level}\n for thresh, level in zip(threshold, dcoeffs)]\n denoised_coeffs = [coeffs[0]] + denoised_detail\n return pywt.waverecn(denoised_coeffs, wavelet)[original_extent]\n\n\ndef _scale_sigma_and_image_consistently(image, sigma, multichannel,\n rescale_sigma):\n \"\"\"If the ``image`` is rescaled, also rescale ``sigma`` consistently.\n\n Images that are not floating point will be rescaled via ``img_as_float``.\n \"\"\"\n if multichannel:\n if isinstance(sigma, numbers.Number) or sigma is None:\n sigma = [sigma] * image.shape[-1]\n elif len(sigma) != image.shape[-1]:\n raise ValueError(\n \"When multichannel is True, sigma must be a scalar or have \"\n \"length equal to the number of channels\")\n if image.dtype.kind != 'f':\n if rescale_sigma:\n range_pre = image.max() - image.min()\n image = img_as_float(image)\n if rescale_sigma:\n range_post = image.max() - image.min()\n # apply the same magnitude scaling to sigma\n scale_factor = range_post / range_pre\n if multichannel:\n sigma = [s * scale_factor if s is not None else s\n for s in sigma]\n elif sigma is not None:\n sigma *= scale_factor\n return image, sigma\n\n\ndef _rescale_sigma_rgb2ycbcr(sigmas):\n \"\"\"Convert user-provided noise standard deviations to YCbCr space.\n\n Notes\n -----\n If R, G, B are linearly independent random variables and a1, a2, a3 are\n scalars, then random variable C:\n C = a1 * R + a2 * G + a3 * B\n has variance, var_C, given by:\n var_C = a1**2 * var_R + a2**2 * var_G + a3**2 * var_B\n \"\"\"\n if sigmas[0] is None:\n return sigmas\n sigmas = np.asarray(sigmas)\n rgv_variances = sigmas * sigmas\n for i in range(3):\n scalars = ycbcr_from_rgb[i, :]\n var_channel = np.sum(scalars * scalars * rgv_variances)\n sigmas[i] = np.sqrt(var_channel)\n return sigmas\n\n\ndef denoise_wavelet(image, sigma=None, wavelet='db1', mode='soft',\n wavelet_levels=None, multichannel=False,\n convert2ycbcr=False, method='BayesShrink',\n rescale_sigma=None):\n \"\"\"Perform wavelet denoising on an image.\n\n Parameters\n ----------\n image : ndarray ([M[, N[, ...P]][, C]) of ints, uints or floats\n Input data to be denoised. `image` can be of any numeric type,\n but it is cast into an ndarray of floats for the computation\n of the denoised image.\n sigma : float or list, optional\n The noise standard deviation used when computing the wavelet detail\n coefficient threshold(s). When None (default), the noise standard\n deviation is estimated via the method in [2]_.\n wavelet : string, optional\n The type of wavelet to perform and can be any of the options\n ``pywt.wavelist`` outputs. The default is `'db1'`. For example,\n ``wavelet`` can be any of ``{'db2', 'haar', 'sym9'}`` and many more.\n mode : {'soft', 'hard'}, optional\n An optional argument to choose the type of denoising performed. It\n noted that choosing soft thresholding given additive noise finds the\n best approximation of the original image.\n wavelet_levels : int or None, optional\n The number of wavelet decomposition levels to use. The default is\n three less than the maximum number of possible decomposition levels.\n multichannel : bool, optional\n Apply wavelet denoising separately for each channel (where channels\n correspond to the final axis of the array).\n convert2ycbcr : bool, optional\n If True and multichannel True, do the wavelet denoising in the YCbCr\n colorspace instead of the RGB color space. This typically results in\n better performance for RGB images.\n method : {'BayesShrink', 'VisuShrink'}, optional\n Thresholding method to be used. The currently supported methods are\n \"BayesShrink\" [1]_ and \"VisuShrink\" [2]_. Defaults to \"BayesShrink\".\n rescale_sigma : bool or None, optional\n If False, no rescaling of the user-provided ``sigma`` will be\n performed. The default of ``None`` rescales sigma appropriately if the\n image is rescaled internally. A ``DeprecationWarning`` is raised to\n warn the user about this new behaviour. This warning can be avoided\n by setting ``rescale_sigma=True``.\n\n .. versionadded:: 0.16\n ``rescale_sigma`` was introduced in 0.16\n\n Returns\n -------\n out : ndarray\n Denoised image.\n\n Notes\n -----\n The wavelet domain is a sparse representation of the image, and can be\n thought of similarly to the frequency domain of the Fourier transform.\n Sparse representations have most values zero or near-zero and truly random\n noise is (usually) represented by many small values in the wavelet domain.\n Setting all values below some threshold to 0 reduces the noise in the\n image, but larger thresholds also decrease the detail present in the image.\n\n If the input is 3D, this function performs wavelet denoising on each color\n plane separately.\n\n .. versionchanged:: 0.16\n For floating point inputs, the original input range is maintained and\n there is no clipping applied to the output. Other input types will be\n converted to a floating point value in the range [-1, 1] or [0, 1]\n depending on the input image range. Unless ``rescale_sigma = False``,\n any internal rescaling applied to the ``image`` will also be applied\n to ``sigma`` to maintain the same relative amplitude.\n\n Many wavelet coefficient thresholding approaches have been proposed. By\n default, ``denoise_wavelet`` applies BayesShrink, which is an adaptive\n thresholding method that computes separate thresholds for each wavelet\n sub-band as described in [1]_.\n\n If ``method == \"VisuShrink\"``, a single \"universal threshold\" is applied to\n all wavelet detail coefficients as described in [2]_. This threshold\n is designed to remove all Gaussian noise at a given ``sigma`` with high\n probability, but tends to produce images that appear overly smooth.\n\n Although any of the wavelets from ``PyWavelets`` can be selected, the\n thresholding methods assume an orthogonal wavelet transform and may not\n choose the threshold appropriately for biorthogonal wavelets. Orthogonal\n wavelets are desirable because white noise in the input remains white noise\n in the subbands. Biorthogonal wavelets lead to colored noise in the\n subbands. Additionally, the orthogonal wavelets in PyWavelets are\n orthonormal so that noise variance in the subbands remains identical to the\n noise variance of the input. Example orthogonal wavelets are the Daubechies\n (e.g. 'db2') or symmlet (e.g. 'sym2') families.\n\n References\n ----------\n .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. \"Adaptive wavelet\n thresholding for image denoising and compression.\" Image Processing,\n IEEE Transactions on 9.9 (2000): 1532-1546.\n :DOI:`10.1109/83.862633`\n .. [2] D. L. Donoho and I. M. Johnstone. \"Ideal spatial adaptation\n by wavelet shrinkage.\" Biometrika 81.3 (1994): 425-455.\n :DOI:`10.1093/biomet/81.3.425`\n\n Examples\n --------\n >>> from skimage import color, data\n >>> img = img_as_float(data.astronaut())\n >>> img = color.rgb2gray(img)\n >>> img += 0.1 * np.random.randn(*img.shape)\n >>> img = np.clip(img, 0, 1)\n >>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True)\n\n \"\"\"\n if method not in [\"BayesShrink\", \"VisuShrink\"]:\n raise ValueError(\n ('Invalid method: {}. The currently supported methods are '\n '\"BayesShrink\" and \"VisuShrink\"').format(method))\n\n # floating-point inputs are not rescaled, so don't clip their output.\n clip_output = image.dtype.kind != 'f'\n\n if convert2ycbcr and not multichannel:\n raise ValueError(\"convert2ycbcr requires multichannel == True\")\n\n if rescale_sigma is None:\n msg = (\n \"As of scikit-image 0.16, automated rescaling of sigma to match \"\n \"any internal rescaling of the image is performed. Setting \"\n \"rescale_sigma to False, will disable this new behaviour. To \"\n \"avoid this warning the user should explicitly set rescale_sigma \"\n \"to True or False.\"\n )\n warn(msg, FutureWarning, stacklevel=2)\n rescale_sigma = True\n image, sigma = _scale_sigma_and_image_consistently(image,\n sigma,\n multichannel,\n rescale_sigma)\n if multichannel:\n if convert2ycbcr:\n out = color.rgb2ycbcr(image)\n # convert user-supplied sigmas to the new colorspace as well\n if rescale_sigma:\n sigma = _rescale_sigma_rgb2ycbcr(sigma)\n for i in range(3):\n # renormalizing this color channel to live in [0, 1]\n _min, _max = out[..., i].min(), out[..., i].max()\n scale_factor = _max - _min\n if scale_factor == 0:\n # skip any channel containing only zeros!\n continue\n channel = out[..., i] - _min\n channel /= scale_factor\n sigma_channel = sigma[i]\n if sigma_channel is not None:\n sigma_channel /= scale_factor\n out[..., i] = denoise_wavelet(channel,\n wavelet=wavelet,\n method=method,\n sigma=sigma_channel,\n mode=mode,\n wavelet_levels=wavelet_levels,\n rescale_sigma=rescale_sigma)\n out[..., i] = out[..., i] * scale_factor\n out[..., i] += _min\n out = color.ycbcr2rgb(out)\n else:\n out = np.empty_like(image)\n for c in range(image.shape[-1]):\n out[..., c] = _wavelet_threshold(image[..., c],\n wavelet=wavelet,\n method=method,\n sigma=sigma[c], mode=mode,\n wavelet_levels=wavelet_levels)\n else:\n out = _wavelet_threshold(image, wavelet=wavelet, method=method,\n sigma=sigma, mode=mode,\n wavelet_levels=wavelet_levels)\n\n if clip_output:\n clip_range = (-1, 1) if image.min() < 0 else (0, 1)\n out = np.clip(out, *clip_range, out=out)\n return out\n\n\ndef estimate_sigma(image, average_sigmas=False, multichannel=False):\n \"\"\"\n Robust wavelet-based estimator of the (Gaussian) noise standard deviation.\n\n Parameters\n ----------\n image : ndarray\n Image for which to estimate the noise standard deviation.\n average_sigmas : bool, optional\n If true, average the channel estimates of `sigma`. Otherwise return\n a list of sigmas corresponding to each channel.\n multichannel : bool\n Estimate sigma separately for each channel.\n\n Returns\n -------\n sigma : float or list\n Estimated noise standard deviation(s). If `multichannel` is True and\n `average_sigmas` is False, a separate noise estimate for each channel\n is returned. Otherwise, the average of the individual channel\n estimates is returned.\n\n Notes\n -----\n This function assumes the noise follows a Gaussian distribution. The\n estimation algorithm is based on the median absolute deviation of the\n wavelet detail coefficients as described in section 4.2 of [1]_.\n\n References\n ----------\n .. [1] D. L. Donoho and I. M. Johnstone. \"Ideal spatial adaptation\n by wavelet shrinkage.\" Biometrika 81.3 (1994): 425-455.\n :DOI:`10.1093/biomet/81.3.425`\n\n Examples\n --------\n >>> import skimage.data\n >>> from skimage import img_as_float\n >>> img = img_as_float(skimage.data.camera())\n >>> sigma = 0.1\n >>> img = img + sigma * np.random.standard_normal(img.shape)\n >>> sigma_hat = estimate_sigma(img, multichannel=False)\n \"\"\"\n if multichannel:\n nchannels = image.shape[-1]\n sigmas = [estimate_sigma(\n image[..., c], multichannel=False) for c in range(nchannels)]\n if average_sigmas:\n sigmas = np.mean(sigmas)\n return sigmas\n elif image.shape[-1] <= 4:\n msg = (\"image is size {0} on the last axis, but multichannel is \"\n \"False. If this is a color image, please set multichannel \"\n \"to True for proper noise estimation.\")\n warn(msg.format(image.shape[-1]))\n coeffs = pywt.dwtn(image, wavelet='db2')\n detail_coeffs = coeffs['d' * image.ndim]\n return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')\n", "\"\"\"Python wrappers around TensorFlow ops.\n\nThis file is MACHINE GENERATED! Do not edit.\nOriginal C++ source file: debug_ops.cc\n\"\"\"\n\nimport collections\n\nfrom tensorflow.python import pywrap_tfe as pywrap_tfe\nfrom tensorflow.python.eager import context as _context\nfrom tensorflow.python.eager import core as _core\nfrom tensorflow.python.eager import execute as _execute\nfrom tensorflow.python.framework import dtypes as _dtypes\n\nfrom tensorflow.python.framework import op_def_registry as _op_def_registry\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import op_def_library as _op_def_library\nfrom tensorflow.python.util.deprecation import deprecated_endpoints\nfrom tensorflow.python.util import dispatch as _dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef copy(input, tensor_name=\"\", debug_ops_spec=[], name=None):\n r\"\"\"Copy a tensor from CPU-to-CPU or GPU-to-GPU.\n\n Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the\n device on which the tensor is allocated.\n N.B.: If the all downstream attached debug ops are disabled given the current\n gRPC gating status, the output will simply forward the input tensor without\n deep-copying. See the documentation of Debug* ops for more details.\n\n Unlike the CopyHost Op, this op does not have HostMemory constraint on its\n input or output.\n\n Args:\n input: A `Tensor`. Input tensor.\n tensor_name: An optional `string`. Defaults to `\"\"`.\n The name of the input tensor.\n debug_ops_spec: An optional list of `strings`. Defaults to `[]`.\n A list of debug op spec (op, url, gated_grpc) for attached debug\n ops. Each element of the list has the format\n <debug_op>;<grpc_url>;<gated_grpc>, wherein gated_grpc is boolean represented\n as 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n \"DebugIdentity;file:///tmp/tfdbg_1;0\".\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"Copy\", name, tld.op_callbacks,\n input, \"tensor_name\", tensor_name, \"debug_ops_spec\", debug_ops_spec)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return copy_eager_fallback(\n input, tensor_name=tensor_name, debug_ops_spec=debug_ops_spec,\n name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_ops_spec is None:\n debug_ops_spec = []\n if not isinstance(debug_ops_spec, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_ops_spec' argument to \"\n \"'copy' Op, not %r.\" % debug_ops_spec)\n debug_ops_spec = [_execute.make_str(_s, \"debug_ops_spec\") for _s in debug_ops_spec]\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"Copy\", input=input, tensor_name=tensor_name,\n debug_ops_spec=debug_ops_spec, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"tensor_name\",\n _op.get_attr(\"tensor_name\"), \"debug_ops_spec\",\n _op.get_attr(\"debug_ops_spec\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"Copy\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nCopy = tf_export(\"raw_ops.Copy\")(_ops.to_raw_op(copy))\n\n\ndef copy_eager_fallback(input, tensor_name, debug_ops_spec, name, ctx):\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_ops_spec is None:\n debug_ops_spec = []\n if not isinstance(debug_ops_spec, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_ops_spec' argument to \"\n \"'copy' Op, not %r.\" % debug_ops_spec)\n debug_ops_spec = [_execute.make_str(_s, \"debug_ops_spec\") for _s in debug_ops_spec]\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"tensor_name\", tensor_name, \"debug_ops_spec\",\n debug_ops_spec)\n _result = _execute.execute(b\"Copy\", 1, inputs=_inputs_flat, attrs=_attrs,\n ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"Copy\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef copy_host(input, tensor_name=\"\", debug_ops_spec=[], name=None):\n r\"\"\"Copy a tensor to host.\n\n Performs CPU-to-CPU deep-copying of tensor.\n N.B.: If the all downstream attached debug ops are disabled given the current\n gRPC gating status, the output will simply forward the input tensor without\n deep-copying. See the documentation of Debug* ops for more details.\n\n Unlike the Copy Op, this op has HostMemory constraint on its input or output.\n\n Args:\n input: A `Tensor`. Input tensor.\n tensor_name: An optional `string`. Defaults to `\"\"`.\n The name of the input tensor.\n debug_ops_spec: An optional list of `strings`. Defaults to `[]`.\n A list of debug op spec (op, url, gated_grpc) for attached debug\n ops. Each element of the list has the format\n <debug_op>;<grpc_url>;<gated_grpc>, wherein gated_grpc is boolean represented\n as 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n \"DebugIdentity;file:///tmp/tfdbg_1;0\".\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"CopyHost\", name,\n tld.op_callbacks, input, \"tensor_name\", tensor_name, \"debug_ops_spec\",\n debug_ops_spec)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return copy_host_eager_fallback(\n input, tensor_name=tensor_name, debug_ops_spec=debug_ops_spec,\n name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_ops_spec is None:\n debug_ops_spec = []\n if not isinstance(debug_ops_spec, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_ops_spec' argument to \"\n \"'copy_host' Op, not %r.\" % debug_ops_spec)\n debug_ops_spec = [_execute.make_str(_s, \"debug_ops_spec\") for _s in debug_ops_spec]\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"CopyHost\", input=input, tensor_name=tensor_name,\n debug_ops_spec=debug_ops_spec, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"tensor_name\",\n _op.get_attr(\"tensor_name\"), \"debug_ops_spec\",\n _op.get_attr(\"debug_ops_spec\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"CopyHost\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nCopyHost = tf_export(\"raw_ops.CopyHost\")(_ops.to_raw_op(copy_host))\n\n\ndef copy_host_eager_fallback(input, tensor_name, debug_ops_spec, name, ctx):\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_ops_spec is None:\n debug_ops_spec = []\n if not isinstance(debug_ops_spec, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_ops_spec' argument to \"\n \"'copy_host' Op, not %r.\" % debug_ops_spec)\n debug_ops_spec = [_execute.make_str(_s, \"debug_ops_spec\") for _s in debug_ops_spec]\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"tensor_name\", tensor_name, \"debug_ops_spec\",\n debug_ops_spec)\n _result = _execute.execute(b\"CopyHost\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"CopyHost\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef debug_identity(input, device_name=\"\", tensor_name=\"\", debug_urls=[], gated_grpc=False, name=None):\n r\"\"\"Provides an identity mapping of the non-Ref type input tensor for debugging.\n\n Provides an identity mapping of the non-Ref type input tensor for debugging.\n\n Args:\n input: A `Tensor`. Input tensor, non-Reference type\n device_name: An optional `string`. Defaults to `\"\"`.\n Name of the device on which the tensor resides.\n tensor_name: An optional `string`. Defaults to `\"\"`.\n Name of the input tensor.\n debug_urls: An optional list of `strings`. Defaults to `[]`.\n List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011\n gated_grpc: An optional `bool`. Defaults to `False`.\n Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DebugIdentity\", name,\n tld.op_callbacks, input, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"gated_grpc\", gated_grpc)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return debug_identity_eager_fallback(\n input, device_name=device_name, tensor_name=tensor_name,\n debug_urls=debug_urls, gated_grpc=gated_grpc, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_identity' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DebugIdentity\", input=input, device_name=device_name,\n tensor_name=tensor_name, debug_urls=debug_urls,\n gated_grpc=gated_grpc, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"device_name\",\n _op.get_attr(\"device_name\"), \"tensor_name\",\n _op.get_attr(\"tensor_name\"), \"debug_urls\",\n _op.get_attr(\"debug_urls\"), \"gated_grpc\",\n _op._get_attr_bool(\"gated_grpc\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DebugIdentity\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nDebugIdentity = tf_export(\"raw_ops.DebugIdentity\")(_ops.to_raw_op(debug_identity))\n\n\ndef debug_identity_eager_fallback(input, device_name, tensor_name, debug_urls, gated_grpc, name, ctx):\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_identity' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"gated_grpc\", gated_grpc)\n _result = _execute.execute(b\"DebugIdentity\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DebugIdentity\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef debug_identity_v2(input, tfdbg_context_id=\"\", op_name=\"\", output_slot=-1, tensor_debug_mode=-1, debug_urls=[], circular_buffer_size=1000, tfdbg_run_id=\"\", name=None):\n r\"\"\"Debug Identity V2 Op.\n\n Provides an identity mapping from input to output, while writing the content of\n the input tensor by calling DebugEventsWriter.\n\n The semantics of the input tensor depends on tensor_debug_mode. In typical\n usage, the input tensor comes directly from the user computation only when\n graph_debug_mode is FULL_TENSOR (see protobuf/debug_event.proto for a\n list of all the possible values of graph_debug_mode). For the other debug modes,\n the input tensor should be produced by an additional op or subgraph that\n computes summary information about one or more tensors.\n\n Args:\n input: A `Tensor`. Input tensor, non-Reference type\n tfdbg_context_id: An optional `string`. Defaults to `\"\"`.\n A tfdbg-generated ID for the context that the op belongs to,\n e.g., a concrete compiled tf.function.\n op_name: An optional `string`. Defaults to `\"\"`.\n Optional. Name of the op that the debug op is concerned with.\n Used only for single-tensor trace.\n output_slot: An optional `int`. Defaults to `-1`.\n Optional. Output slot index of the tensor that the debug op\n is concerned with. Used only for single-tensor trace.\n tensor_debug_mode: An optional `int`. Defaults to `-1`.\n TensorDebugMode enum value. See debug_event.proto for details.\n debug_urls: An optional list of `strings`. Defaults to `[]`.\n List of URLs to debug targets, e.g., file:///foo/tfdbg_dump.\n circular_buffer_size: An optional `int`. Defaults to `1000`.\n tfdbg_run_id: An optional `string`. Defaults to `\"\"`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DebugIdentityV2\", name,\n tld.op_callbacks, input, \"tfdbg_context_id\", tfdbg_context_id,\n \"op_name\", op_name, \"output_slot\", output_slot, \"tensor_debug_mode\",\n tensor_debug_mode, \"debug_urls\", debug_urls, \"circular_buffer_size\",\n circular_buffer_size, \"tfdbg_run_id\", tfdbg_run_id)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return debug_identity_v2_eager_fallback(\n input, tfdbg_context_id=tfdbg_context_id, op_name=op_name,\n output_slot=output_slot, tensor_debug_mode=tensor_debug_mode,\n debug_urls=debug_urls, circular_buffer_size=circular_buffer_size,\n tfdbg_run_id=tfdbg_run_id, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if tfdbg_context_id is None:\n tfdbg_context_id = \"\"\n tfdbg_context_id = _execute.make_str(tfdbg_context_id, \"tfdbg_context_id\")\n if op_name is None:\n op_name = \"\"\n op_name = _execute.make_str(op_name, \"op_name\")\n if output_slot is None:\n output_slot = -1\n output_slot = _execute.make_int(output_slot, \"output_slot\")\n if tensor_debug_mode is None:\n tensor_debug_mode = -1\n tensor_debug_mode = _execute.make_int(tensor_debug_mode, \"tensor_debug_mode\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_identity_v2' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if circular_buffer_size is None:\n circular_buffer_size = 1000\n circular_buffer_size = _execute.make_int(circular_buffer_size, \"circular_buffer_size\")\n if tfdbg_run_id is None:\n tfdbg_run_id = \"\"\n tfdbg_run_id = _execute.make_str(tfdbg_run_id, \"tfdbg_run_id\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DebugIdentityV2\", input=input, tfdbg_context_id=tfdbg_context_id,\n op_name=op_name, output_slot=output_slot,\n tensor_debug_mode=tensor_debug_mode,\n debug_urls=debug_urls,\n circular_buffer_size=circular_buffer_size,\n tfdbg_run_id=tfdbg_run_id, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"tfdbg_context_id\",\n _op.get_attr(\"tfdbg_context_id\"), \"op_name\",\n _op.get_attr(\"op_name\"), \"output_slot\",\n _op._get_attr_int(\"output_slot\"), \"tensor_debug_mode\",\n _op._get_attr_int(\"tensor_debug_mode\"), \"debug_urls\",\n _op.get_attr(\"debug_urls\"), \"circular_buffer_size\",\n _op._get_attr_int(\"circular_buffer_size\"), \"tfdbg_run_id\",\n _op.get_attr(\"tfdbg_run_id\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DebugIdentityV2\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nDebugIdentityV2 = tf_export(\"raw_ops.DebugIdentityV2\")(_ops.to_raw_op(debug_identity_v2))\n\n\ndef debug_identity_v2_eager_fallback(input, tfdbg_context_id, op_name, output_slot, tensor_debug_mode, debug_urls, circular_buffer_size, tfdbg_run_id, name, ctx):\n if tfdbg_context_id is None:\n tfdbg_context_id = \"\"\n tfdbg_context_id = _execute.make_str(tfdbg_context_id, \"tfdbg_context_id\")\n if op_name is None:\n op_name = \"\"\n op_name = _execute.make_str(op_name, \"op_name\")\n if output_slot is None:\n output_slot = -1\n output_slot = _execute.make_int(output_slot, \"output_slot\")\n if tensor_debug_mode is None:\n tensor_debug_mode = -1\n tensor_debug_mode = _execute.make_int(tensor_debug_mode, \"tensor_debug_mode\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_identity_v2' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if circular_buffer_size is None:\n circular_buffer_size = 1000\n circular_buffer_size = _execute.make_int(circular_buffer_size, \"circular_buffer_size\")\n if tfdbg_run_id is None:\n tfdbg_run_id = \"\"\n tfdbg_run_id = _execute.make_str(tfdbg_run_id, \"tfdbg_run_id\")\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"tfdbg_context_id\", tfdbg_context_id, \"op_name\",\n op_name, \"output_slot\", output_slot, \"tensor_debug_mode\", tensor_debug_mode,\n \"debug_urls\", debug_urls, \"circular_buffer_size\", circular_buffer_size,\n \"tfdbg_run_id\", tfdbg_run_id)\n _result = _execute.execute(b\"DebugIdentityV2\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DebugIdentityV2\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef debug_nan_count(input, device_name=\"\", tensor_name=\"\", debug_urls=[], gated_grpc=False, name=None):\n r\"\"\"Debug NaN Value Counter Op.\n\n Counts number of NaNs in the input tensor, for debugging.\n\n Args:\n input: A `Tensor`. Input tensor, non-Reference type.\n device_name: An optional `string`. Defaults to `\"\"`.\n tensor_name: An optional `string`. Defaults to `\"\"`.\n Name of the input tensor.\n debug_urls: An optional list of `strings`. Defaults to `[]`.\n List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.\n gated_grpc: An optional `bool`. Defaults to `False`.\n Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `int64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DebugNanCount\", name,\n tld.op_callbacks, input, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"gated_grpc\", gated_grpc)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return debug_nan_count_eager_fallback(\n input, device_name=device_name, tensor_name=tensor_name,\n debug_urls=debug_urls, gated_grpc=gated_grpc, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_nan_count' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DebugNanCount\", input=input, device_name=device_name,\n tensor_name=tensor_name, debug_urls=debug_urls,\n gated_grpc=gated_grpc, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"device_name\",\n _op.get_attr(\"device_name\"), \"tensor_name\",\n _op.get_attr(\"tensor_name\"), \"debug_urls\",\n _op.get_attr(\"debug_urls\"), \"gated_grpc\",\n _op._get_attr_bool(\"gated_grpc\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DebugNanCount\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nDebugNanCount = tf_export(\"raw_ops.DebugNanCount\")(_ops.to_raw_op(debug_nan_count))\n\n\ndef debug_nan_count_eager_fallback(input, device_name, tensor_name, debug_urls, gated_grpc, name, ctx):\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_nan_count' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"gated_grpc\", gated_grpc)\n _result = _execute.execute(b\"DebugNanCount\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DebugNanCount\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef debug_numeric_summary(input, device_name=\"\", tensor_name=\"\", debug_urls=[], lower_bound=float('-inf'), upper_bound=float('inf'), mute_if_healthy=False, gated_grpc=False, name=None):\n r\"\"\"Debug Numeric Summary Op.\n\n Provide a basic summary of numeric value types, range and distribution.\n\n output: A double tensor of shape [14 + nDimensions], where nDimensions is the\n number of dimensions of the tensor's shape. The elements of output are:\n [0]: is initialized (1.0) or not (0.0).\n [1]: total number of elements\n [2]: NaN element count\n [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by\n default.\n [4]: negative element count (excluding -inf), if lower_bound is the default\n -inf. Otherwise, this is the count of elements > lower_bound and < 0.\n [5]: zero element count\n [6]: positive element count (excluding +inf), if upper_bound is the default\n +inf. Otherwise, this is the count of elements < upper_bound and > 0.\n [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by\n default.\n Output elements [1:8] are all zero, if the tensor is uninitialized.\n [8]: minimum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: +inf.\n [9]: maximum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: -inf.\n [10]: mean of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [11]: variance of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [12]: Data type of the tensor encoded as an enum integer. See the DataType\n proto for more details.\n [13]: Number of dimensions of the tensor (ndims).\n [14+]: Sizes of the dimensions.\n\n Args:\n input: A `Tensor`. Input tensor, non-Reference type.\n device_name: An optional `string`. Defaults to `\"\"`.\n tensor_name: An optional `string`. Defaults to `\"\"`.\n Name of the input tensor.\n debug_urls: An optional list of `strings`. Defaults to `[]`.\n List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.\n lower_bound: An optional `float`. Defaults to `float('-inf')`.\n (float) The lower bound <= which values will be included in the\n generalized -inf count. Default: -inf.\n upper_bound: An optional `float`. Defaults to `float('inf')`.\n (float) The upper bound >= which values will be included in the\n generalized +inf count. Default: +inf.\n mute_if_healthy: An optional `bool`. Defaults to `False`.\n (bool) Do not send data to the debug URLs unless at least one\n of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and\n inf counts) is non-zero.\n gated_grpc: An optional `bool`. Defaults to `False`.\n Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `float64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DebugNumericSummary\", name,\n tld.op_callbacks, input, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"lower_bound\", lower_bound,\n \"upper_bound\", upper_bound, \"mute_if_healthy\", mute_if_healthy,\n \"gated_grpc\", gated_grpc)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return debug_numeric_summary_eager_fallback(\n input, device_name=device_name, tensor_name=tensor_name,\n debug_urls=debug_urls, lower_bound=lower_bound,\n upper_bound=upper_bound, mute_if_healthy=mute_if_healthy,\n gated_grpc=gated_grpc, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_numeric_summary' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if lower_bound is None:\n lower_bound = float('-inf')\n lower_bound = _execute.make_float(lower_bound, \"lower_bound\")\n if upper_bound is None:\n upper_bound = float('inf')\n upper_bound = _execute.make_float(upper_bound, \"upper_bound\")\n if mute_if_healthy is None:\n mute_if_healthy = False\n mute_if_healthy = _execute.make_bool(mute_if_healthy, \"mute_if_healthy\")\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DebugNumericSummary\", input=input, device_name=device_name,\n tensor_name=tensor_name, debug_urls=debug_urls,\n lower_bound=lower_bound,\n upper_bound=upper_bound,\n mute_if_healthy=mute_if_healthy,\n gated_grpc=gated_grpc, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"device_name\",\n _op.get_attr(\"device_name\"), \"tensor_name\",\n _op.get_attr(\"tensor_name\"), \"debug_urls\",\n _op.get_attr(\"debug_urls\"), \"lower_bound\",\n _op.get_attr(\"lower_bound\"), \"upper_bound\",\n _op.get_attr(\"upper_bound\"), \"mute_if_healthy\",\n _op._get_attr_bool(\"mute_if_healthy\"), \"gated_grpc\",\n _op._get_attr_bool(\"gated_grpc\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DebugNumericSummary\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nDebugNumericSummary = tf_export(\"raw_ops.DebugNumericSummary\")(_ops.to_raw_op(debug_numeric_summary))\n\n\ndef debug_numeric_summary_eager_fallback(input, device_name, tensor_name, debug_urls, lower_bound, upper_bound, mute_if_healthy, gated_grpc, name, ctx):\n if device_name is None:\n device_name = \"\"\n device_name = _execute.make_str(device_name, \"device_name\")\n if tensor_name is None:\n tensor_name = \"\"\n tensor_name = _execute.make_str(tensor_name, \"tensor_name\")\n if debug_urls is None:\n debug_urls = []\n if not isinstance(debug_urls, (list, tuple)):\n raise TypeError(\n \"Expected list for 'debug_urls' argument to \"\n \"'debug_numeric_summary' Op, not %r.\" % debug_urls)\n debug_urls = [_execute.make_str(_s, \"debug_urls\") for _s in debug_urls]\n if lower_bound is None:\n lower_bound = float('-inf')\n lower_bound = _execute.make_float(lower_bound, \"lower_bound\")\n if upper_bound is None:\n upper_bound = float('inf')\n upper_bound = _execute.make_float(upper_bound, \"upper_bound\")\n if mute_if_healthy is None:\n mute_if_healthy = False\n mute_if_healthy = _execute.make_bool(mute_if_healthy, \"mute_if_healthy\")\n if gated_grpc is None:\n gated_grpc = False\n gated_grpc = _execute.make_bool(gated_grpc, \"gated_grpc\")\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"T\", _attr_T, \"device_name\", device_name, \"tensor_name\",\n tensor_name, \"debug_urls\", debug_urls, \"lower_bound\", lower_bound,\n \"upper_bound\", upper_bound, \"mute_if_healthy\", mute_if_healthy,\n \"gated_grpc\", gated_grpc)\n _result = _execute.execute(b\"DebugNumericSummary\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DebugNumericSummary\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef debug_numeric_summary_v2(input, output_dtype=_dtypes.float32, tensor_debug_mode=-1, tensor_id=-1, name=None):\n r\"\"\"Debug Numeric Summary V2 Op.\n\n Computes a numeric summary of the input tensor. The shape of the output\n depends on the tensor_debug_mode attribute.\n This op is used internally by TensorFlow Debugger (tfdbg) v2.\n\n Args:\n input: A `Tensor`. Input tensor, to be summarized by the op.\n output_dtype: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`.\n Optional. The type of the output. Can be float32 or float64 (default: float32).\n tensor_debug_mode: An optional `int`. Defaults to `-1`.\n Tensor debug mode: the mode in which the input tensor is summarized\n by the op. See the TensorDebugMode enum in\n tensorflow/core/protobuf/debug_event.proto for details.\n\n Supported values:\n 2 (CURT_HEALTH): Output a float32/64 tensor of shape [2]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is a bit which is set to 1 if the input tensor has an\n infinity or nan value, or zero otherwise.\n\n 3 (CONCISE_HEALTH): Output a float32/64 tensor of shape [5]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The\n remaining four slots are the total number of elements, -infs,\n +infs, and nans in the input tensor respectively.\n\n 4 (FULL_HEALTH): Output a float32/64 tensor of shape [11]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The remaining elements hold the total number of elements, -infs,\n +infs, nans, negative finite numbers, zeros, and positive finite\n numbers in the input tensor respectively.\n\n 5 (SHAPE): Output a float32/64 tensor of shape [10]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 3rd element holds the rank of the tensor. The 4th element holds\n the number of elements within the tensor. Finally the remaining 6\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated.\n\n 6 (FULL_NUMERICS): Output a float32/64 tensor of shape [22]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 4th element holds the rank of the tensor. The 5th to 11th\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated. The 12th to\n 18th elements hold the number of elements, -infs, +infs, nans,\n denormal floats, negative finite numbers, zeros, and positive\n finite numbers in the input tensor respectively. The final four\n elements hold the min value, max value, mean, and variance of the\n input tensor.\n\n 8 (REDUCE_INF_NAN_THREE_SLOTS): Output a float32/64 tensor of shape\n [3]. The 1st element is -inf if any elements of the input tensor\n is -inf, or zero otherwise. The 2nd element is +inf if any elements\n of the input tensor is +inf, or zero otherwise. The 3rd element is\n nan if any element of the input tensor is nan, or zero otherwise.\n tensor_id: An optional `int`. Defaults to `-1`.\n Optional. An integer identifier for the tensor being summarized by this op.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `output_dtype`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DebugNumericSummaryV2\", name,\n tld.op_callbacks, input, \"output_dtype\", output_dtype,\n \"tensor_debug_mode\", tensor_debug_mode, \"tensor_id\", tensor_id)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return debug_numeric_summary_v2_eager_fallback(\n input, output_dtype=output_dtype,\n tensor_debug_mode=tensor_debug_mode, tensor_id=tensor_id, name=name,\n ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if output_dtype is None:\n output_dtype = _dtypes.float32\n output_dtype = _execute.make_type(output_dtype, \"output_dtype\")\n if tensor_debug_mode is None:\n tensor_debug_mode = -1\n tensor_debug_mode = _execute.make_int(tensor_debug_mode, \"tensor_debug_mode\")\n if tensor_id is None:\n tensor_id = -1\n tensor_id = _execute.make_int(tensor_id, \"tensor_id\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DebugNumericSummaryV2\", input=input, output_dtype=output_dtype,\n tensor_debug_mode=tensor_debug_mode,\n tensor_id=tensor_id, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"output_dtype\", _op._get_attr_type(\"output_dtype\"), \"T\",\n _op._get_attr_type(\"T\"), \"tensor_debug_mode\",\n _op._get_attr_int(\"tensor_debug_mode\"), \"tensor_id\",\n _op._get_attr_int(\"tensor_id\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DebugNumericSummaryV2\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nDebugNumericSummaryV2 = tf_export(\"raw_ops.DebugNumericSummaryV2\")(_ops.to_raw_op(debug_numeric_summary_v2))\n\n\ndef debug_numeric_summary_v2_eager_fallback(input, output_dtype, tensor_debug_mode, tensor_id, name, ctx):\n if output_dtype is None:\n output_dtype = _dtypes.float32\n output_dtype = _execute.make_type(output_dtype, \"output_dtype\")\n if tensor_debug_mode is None:\n tensor_debug_mode = -1\n tensor_debug_mode = _execute.make_int(tensor_debug_mode, \"tensor_debug_mode\")\n if tensor_id is None:\n tensor_id = -1\n tensor_id = _execute.make_int(tensor_id, \"tensor_id\")\n _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx)\n _inputs_flat = [input]\n _attrs = (\"output_dtype\", output_dtype, \"T\", _attr_T, \"tensor_debug_mode\",\n tensor_debug_mode, \"tensor_id\", tensor_id)\n _result = _execute.execute(b\"DebugNumericSummaryV2\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DebugNumericSummaryV2\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n", "\"\"\"Python wrappers around TensorFlow ops.\n\nThis file is MACHINE GENERATED! Do not edit.\nOriginal C++ source file: ragged_conversion_ops.cc\n\"\"\"\n\nimport collections\n\nfrom tensorflow.python import pywrap_tfe as pywrap_tfe\nfrom tensorflow.python.eager import context as _context\nfrom tensorflow.python.eager import core as _core\nfrom tensorflow.python.eager import execute as _execute\nfrom tensorflow.python.framework import dtypes as _dtypes\n\nfrom tensorflow.python.framework import op_def_registry as _op_def_registry\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import op_def_library as _op_def_library\nfrom tensorflow.python.util.deprecation import deprecated_endpoints\nfrom tensorflow.python.util import dispatch as _dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n\n_RaggedTensorFromVariantOutput = collections.namedtuple(\n \"RaggedTensorFromVariant\",\n [\"output_nested_splits\", \"output_dense_values\"])\n\n\ndef ragged_tensor_from_variant(encoded_ragged, input_ragged_rank, output_ragged_rank, Tvalues, Tsplits=_dtypes.int64, name=None):\n r\"\"\"Decodes a `variant` Tensor into a `RaggedTensor`.\n\n Decodes the given `variant` Tensor and returns a `RaggedTensor`. The input\n could be a scalar, meaning it encodes a single `RaggedTensor` with ragged_rank\n `output_ragged_rank`. It could also have an arbitrary rank, in which case each\n element is decoded into a `RaggedTensor` with ragged_rank `input_ragged_rank`\n and these are then stacked according to the input shape to output a single\n `RaggedTensor` with ragged_rank `output_ragged_rank`. Each `variant` element in\n the input Tensor is decoded by retrieving from the element a 1-D `variant`\n Tensor with `input_ragged_rank + 1` Tensors, corresponding to the splits and\n values of the decoded `RaggedTensor`. If `input_ragged_rank` is -1, then it is\n inferred as `output_ragged_rank` - `rank(encoded_ragged)`. See\n `RaggedTensorToVariant` for the corresponding encoding logic.\n\n Args:\n encoded_ragged: A `Tensor` of type `variant`.\n A `variant` Tensor containing encoded `RaggedTensor`s.\n input_ragged_rank: An `int` that is `>= -1`.\n The ragged rank of each encoded `RaggedTensor` component in the input. If set to\n -1, this is inferred as `output_ragged_rank` - `rank(encoded_ragged)`\n output_ragged_rank: An `int` that is `>= 0`.\n The expected ragged rank of the output `RaggedTensor`. The following must hold:\n `output_ragged_rank = rank(encoded_ragged) + input_ragged_rank`.\n Tvalues: A `tf.DType`.\n Tsplits: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (output_nested_splits, output_dense_values).\n\n output_nested_splits: A list of `output_ragged_rank` `Tensor` objects with type `Tsplits`.\n output_dense_values: A `Tensor` of type `Tvalues`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"RaggedTensorFromVariant\",\n name, tld.op_callbacks, encoded_ragged, \"input_ragged_rank\",\n input_ragged_rank, \"output_ragged_rank\", output_ragged_rank,\n \"Tvalues\", Tvalues, \"Tsplits\", Tsplits)\n _result = _RaggedTensorFromVariantOutput._make(_result)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return ragged_tensor_from_variant_eager_fallback(\n encoded_ragged, input_ragged_rank=input_ragged_rank,\n output_ragged_rank=output_ragged_rank, Tvalues=Tvalues,\n Tsplits=Tsplits, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n input_ragged_rank = _execute.make_int(input_ragged_rank, \"input_ragged_rank\")\n output_ragged_rank = _execute.make_int(output_ragged_rank, \"output_ragged_rank\")\n Tvalues = _execute.make_type(Tvalues, \"Tvalues\")\n if Tsplits is None:\n Tsplits = _dtypes.int64\n Tsplits = _execute.make_type(Tsplits, \"Tsplits\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"RaggedTensorFromVariant\", encoded_ragged=encoded_ragged,\n input_ragged_rank=input_ragged_rank,\n output_ragged_rank=output_ragged_rank,\n Tvalues=Tvalues, Tsplits=Tsplits,\n name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"input_ragged_rank\", _op._get_attr_int(\"input_ragged_rank\"),\n \"output_ragged_rank\", _op._get_attr_int(\"output_ragged_rank\"),\n \"Tvalues\", _op._get_attr_type(\"Tvalues\"), \"Tsplits\",\n _op._get_attr_type(\"Tsplits\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"RaggedTensorFromVariant\", _inputs_flat, _attrs, _result)\n _result = [_result[:output_ragged_rank]] + _result[output_ragged_rank:]\n _result = _RaggedTensorFromVariantOutput._make(_result)\n return _result\n\nRaggedTensorFromVariant = tf_export(\"raw_ops.RaggedTensorFromVariant\")(_ops.to_raw_op(ragged_tensor_from_variant))\n\n\ndef ragged_tensor_from_variant_eager_fallback(encoded_ragged, input_ragged_rank, output_ragged_rank, Tvalues, Tsplits, name, ctx):\n input_ragged_rank = _execute.make_int(input_ragged_rank, \"input_ragged_rank\")\n output_ragged_rank = _execute.make_int(output_ragged_rank, \"output_ragged_rank\")\n Tvalues = _execute.make_type(Tvalues, \"Tvalues\")\n if Tsplits is None:\n Tsplits = _dtypes.int64\n Tsplits = _execute.make_type(Tsplits, \"Tsplits\")\n encoded_ragged = _ops.convert_to_tensor(encoded_ragged, _dtypes.variant)\n _inputs_flat = [encoded_ragged]\n _attrs = (\"input_ragged_rank\", input_ragged_rank, \"output_ragged_rank\",\n output_ragged_rank, \"Tvalues\", Tvalues, \"Tsplits\", Tsplits)\n _result = _execute.execute(b\"RaggedTensorFromVariant\", output_ragged_rank +\n 1, inputs=_inputs_flat, attrs=_attrs, ctx=ctx,\n name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"RaggedTensorFromVariant\", _inputs_flat, _attrs, _result)\n _result = [_result[:output_ragged_rank]] + _result[output_ragged_rank:]\n _result = _RaggedTensorFromVariantOutput._make(_result)\n return _result\n\n_RaggedTensorToSparseOutput = collections.namedtuple(\n \"RaggedTensorToSparse\",\n [\"sparse_indices\", \"sparse_values\", \"sparse_dense_shape\"])\n\n\ndef ragged_tensor_to_sparse(rt_nested_splits, rt_dense_values, name=None):\n r\"\"\"Converts a `RaggedTensor` into a `SparseTensor` with the same values.\n\n input=ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits)\n output=SparseTensor(indices=sparse_indices, values=sparse_values,\n dense_shape=sparse_dense_shape)\n\n Args:\n rt_nested_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`.\n The `row_splits` for the `RaggedTensor`.\n rt_dense_values: A `Tensor`. The `flat_values` for the `RaggedTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_dense_shape).\n\n sparse_indices: A `Tensor` of type `int64`.\n sparse_values: A `Tensor`. Has the same type as `rt_dense_values`.\n sparse_dense_shape: A `Tensor` of type `int64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"RaggedTensorToSparse\", name,\n tld.op_callbacks, rt_nested_splits, rt_dense_values)\n _result = _RaggedTensorToSparseOutput._make(_result)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return ragged_tensor_to_sparse_eager_fallback(\n rt_nested_splits, rt_dense_values, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if not isinstance(rt_nested_splits, (list, tuple)):\n raise TypeError(\n \"Expected list for 'rt_nested_splits' argument to \"\n \"'ragged_tensor_to_sparse' Op, not %r.\" % rt_nested_splits)\n _attr_RAGGED_RANK = len(rt_nested_splits)\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"RaggedTensorToSparse\", rt_nested_splits=rt_nested_splits,\n rt_dense_values=rt_dense_values, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"RAGGED_RANK\", _op._get_attr_int(\"RAGGED_RANK\"), \"T\",\n _op._get_attr_type(\"T\"), \"Tsplits\",\n _op._get_attr_type(\"Tsplits\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"RaggedTensorToSparse\", _inputs_flat, _attrs, _result)\n _result = _RaggedTensorToSparseOutput._make(_result)\n return _result\n\nRaggedTensorToSparse = tf_export(\"raw_ops.RaggedTensorToSparse\")(_ops.to_raw_op(ragged_tensor_to_sparse))\n\n\ndef ragged_tensor_to_sparse_eager_fallback(rt_nested_splits, rt_dense_values, name, ctx):\n if not isinstance(rt_nested_splits, (list, tuple)):\n raise TypeError(\n \"Expected list for 'rt_nested_splits' argument to \"\n \"'ragged_tensor_to_sparse' Op, not %r.\" % rt_nested_splits)\n _attr_RAGGED_RANK = len(rt_nested_splits)\n _attr_T, (rt_dense_values,) = _execute.args_to_matching_eager([rt_dense_values], ctx)\n _attr_Tsplits, rt_nested_splits = _execute.args_to_matching_eager(list(rt_nested_splits), ctx, _dtypes.int64)\n _inputs_flat = list(rt_nested_splits) + [rt_dense_values]\n _attrs = (\"RAGGED_RANK\", _attr_RAGGED_RANK, \"T\", _attr_T, \"Tsplits\",\n _attr_Tsplits)\n _result = _execute.execute(b\"RaggedTensorToSparse\", 3, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"RaggedTensorToSparse\", _inputs_flat, _attrs, _result)\n _result = _RaggedTensorToSparseOutput._make(_result)\n return _result\n\n\ndef ragged_tensor_to_tensor(shape, values, default_value, row_partition_tensors, row_partition_types, name=None):\n r\"\"\"Create a dense tensor from a ragged tensor, possibly altering its shape.\n\n The `ragged_to_dense` op creates a dense tensor from a list of row partition\n tensors, a value vector, and default values. If the shape is unspecified, the\n minimal shape required to contain all the elements in the ragged tensor (the\n natural shape) will be used. If some dimensions are left unspecified, then the\n size of the natural shape is used in that dimension.\n\n The default_value will be broadcast to the output shape. After that, the values\n from the ragged tensor overwrite the default values. Note that the default_value\n must have less dimensions than the value.\n\n The row partition tensors are in the order of the dimensions.\n At present, the types can be:\n * \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceded by \"FIRST_DIM_SIZE\".\n\n Args:\n shape: A `Tensor`. Must be one of the following types: `int64`, `int32`.\n The desired shape of the the output tensor. If left unspecified (empty),\n the minimal shape required to contain all the elements in the ragged tensor\n (the natural shape) will be used. If some dimensions are left unspecified, then\n the size of the natural shape is used in that dimension.\n\n Note that dense dimensions cannot be modified by the shape argument. Trying to\n change the size of a dense dimension will cause the op to fail.\n Examples:\n natural shape: [4, 5, 6]\n shape: -1\n output shape: [4, 5, 6]\n\n natural shape: [4, 5, 6]\n shape: [3, -1, 2]\n output shape: [3, 5, 2]\n\n natural shape: [4, 5, 6]\n shape: [3, 7, 2]\n output shape: [3, 7, 2]\n values: A `Tensor`.\n A 1D tensor representing the values of the ragged tensor.\n default_value: A `Tensor`. Must have the same type as `values`.\n The default_value when the shape is larger than the ragged tensor. The\n default_value is broadcast until it is the shape of the output tensor, and\n then overwritten by values in the ragged tensor. The default value must be\n compatible with this broadcast operation, and must have fewer dimensions than\n the value tensor.\n row_partition_tensors: A list of at least 1 `Tensor` objects with the same type in: `int64`, `int32`.\n row_partition_types: A list of `strings`.\n The types of the row partition tensors. At present, these can be:\n * \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceeded by \"FIRST_DIM_SIZE\".\n The tensors are in the order of the dimensions.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `values`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"RaggedTensorToTensor\", name,\n tld.op_callbacks, shape, values, default_value, row_partition_tensors,\n \"row_partition_types\", row_partition_types)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return ragged_tensor_to_tensor_eager_fallback(\n shape, values, default_value, row_partition_tensors,\n row_partition_types=row_partition_types, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if not isinstance(row_partition_tensors, (list, tuple)):\n raise TypeError(\n \"Expected list for 'row_partition_tensors' argument to \"\n \"'ragged_tensor_to_tensor' Op, not %r.\" % row_partition_tensors)\n _attr_num_row_partition_tensors = len(row_partition_tensors)\n if not isinstance(row_partition_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'row_partition_types' argument to \"\n \"'ragged_tensor_to_tensor' Op, not %r.\" % row_partition_types)\n row_partition_types = [_execute.make_str(_s, \"row_partition_types\") for _s in row_partition_types]\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"RaggedTensorToTensor\", shape=shape, values=values,\n default_value=default_value,\n row_partition_tensors=row_partition_tensors,\n row_partition_types=row_partition_types,\n name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"Tindex\",\n _op._get_attr_type(\"Tindex\"), \"Tshape\",\n _op._get_attr_type(\"Tshape\"), \"num_row_partition_tensors\",\n _op._get_attr_int(\"num_row_partition_tensors\"),\n \"row_partition_types\", _op.get_attr(\"row_partition_types\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"RaggedTensorToTensor\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nRaggedTensorToTensor = tf_export(\"raw_ops.RaggedTensorToTensor\")(_ops.to_raw_op(ragged_tensor_to_tensor))\n\n\ndef ragged_tensor_to_tensor_eager_fallback(shape, values, default_value, row_partition_tensors, row_partition_types, name, ctx):\n if not isinstance(row_partition_tensors, (list, tuple)):\n raise TypeError(\n \"Expected list for 'row_partition_tensors' argument to \"\n \"'ragged_tensor_to_tensor' Op, not %r.\" % row_partition_tensors)\n _attr_num_row_partition_tensors = len(row_partition_tensors)\n if not isinstance(row_partition_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'row_partition_types' argument to \"\n \"'ragged_tensor_to_tensor' Op, not %r.\" % row_partition_types)\n row_partition_types = [_execute.make_str(_s, \"row_partition_types\") for _s in row_partition_types]\n _attr_T, _inputs_T = _execute.args_to_matching_eager([values, default_value], ctx)\n (values, default_value) = _inputs_T\n _attr_Tindex, row_partition_tensors = _execute.args_to_matching_eager(list(row_partition_tensors), ctx)\n _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx)\n _inputs_flat = [shape, values, default_value] + list(row_partition_tensors)\n _attrs = (\"T\", _attr_T, \"Tindex\", _attr_Tindex, \"Tshape\", _attr_Tshape,\n \"num_row_partition_tensors\", _attr_num_row_partition_tensors,\n \"row_partition_types\", row_partition_types)\n _result = _execute.execute(b\"RaggedTensorToTensor\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"RaggedTensorToTensor\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n\ndef ragged_tensor_to_variant(rt_nested_splits, rt_dense_values, batched_input, name=None):\n r\"\"\"Encodes a `RaggedTensor` into a `variant` Tensor.\n\n \n Encodes the given `RaggedTensor` and returns a `variant` Tensor. If\n `batched_input` is True, then input `RaggedTensor` is unbatched along the\n zero-th dimension, each component `RaggedTensor` is encoded into a scalar\n `variant` Tensor, and these are stacked to return a 1-D `variant` Tensor.\n If `batched_input` is False, then the input `RaggedTensor` is encoded as is and\n a scalar `variant` Tensor is returned. A `RaggedTensor` is encoded by first\n creating a 1-D `variant` Tensor with `ragged_rank + 1` elements, containing the\n splits and values Tensors of the `RaggedTensor`. Then the 1-D `variant` Tensor\n is wrapped in a scalar `variant` Tensor. See `RaggedTensorFromVariant` for the\n corresponding decoding logic.\n\n Args:\n rt_nested_splits: A list of `Tensor` objects with the same type in: `int32`, `int64`.\n A list of one or more Tensors representing the splits of the input\n `RaggedTensor`.\n rt_dense_values: A `Tensor`.\n A Tensor representing the values of the input `RaggedTensor`.\n batched_input: A `bool`.\n A `bool` denoting whether the input is a batched `RaggedTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"RaggedTensorToVariant\", name,\n tld.op_callbacks, rt_nested_splits, rt_dense_values, \"batched_input\",\n batched_input)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return ragged_tensor_to_variant_eager_fallback(\n rt_nested_splits, rt_dense_values, batched_input=batched_input,\n name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n if not isinstance(rt_nested_splits, (list, tuple)):\n raise TypeError(\n \"Expected list for 'rt_nested_splits' argument to \"\n \"'ragged_tensor_to_variant' Op, not %r.\" % rt_nested_splits)\n _attr_RAGGED_RANK = len(rt_nested_splits)\n batched_input = _execute.make_bool(batched_input, \"batched_input\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"RaggedTensorToVariant\", rt_nested_splits=rt_nested_splits,\n rt_dense_values=rt_dense_values,\n batched_input=batched_input, name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"RAGGED_RANK\", _op._get_attr_int(\"RAGGED_RANK\"), \"Tvalues\",\n _op._get_attr_type(\"Tvalues\"), \"Tsplits\",\n _op._get_attr_type(\"Tsplits\"), \"batched_input\",\n _op._get_attr_bool(\"batched_input\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"RaggedTensorToVariant\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\nRaggedTensorToVariant = tf_export(\"raw_ops.RaggedTensorToVariant\")(_ops.to_raw_op(ragged_tensor_to_variant))\n\n\ndef ragged_tensor_to_variant_eager_fallback(rt_nested_splits, rt_dense_values, batched_input, name, ctx):\n if not isinstance(rt_nested_splits, (list, tuple)):\n raise TypeError(\n \"Expected list for 'rt_nested_splits' argument to \"\n \"'ragged_tensor_to_variant' Op, not %r.\" % rt_nested_splits)\n _attr_RAGGED_RANK = len(rt_nested_splits)\n batched_input = _execute.make_bool(batched_input, \"batched_input\")\n _attr_Tvalues, (rt_dense_values,) = _execute.args_to_matching_eager([rt_dense_values], ctx)\n _attr_Tsplits, rt_nested_splits = _execute.args_to_matching_eager(list(rt_nested_splits), ctx, _dtypes.int64)\n _inputs_flat = list(rt_nested_splits) + [rt_dense_values]\n _attrs = (\"RAGGED_RANK\", _attr_RAGGED_RANK, \"Tvalues\", _attr_Tvalues,\n \"Tsplits\", _attr_Tsplits, \"batched_input\", batched_input)\n _result = _execute.execute(b\"RaggedTensorToVariant\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=ctx, name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"RaggedTensorToVariant\", _inputs_flat, _attrs, _result)\n _result, = _result\n return _result\n\n", "# This file is MACHINE GENERATED! Do not edit.\n# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.\n\"\"\"Inception V3 model for Keras.\n\nReference paper:\n - [Rethinking the Inception Architecture for Computer Vision](\n http://arxiv.org/abs/1512.00567) (CVPR 2016)\n\n\"\"\"\n\nfrom __future__ import print_function as _print_function\n\nimport sys as _sys\n\nfrom tensorflow.python.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.python.keras.applications.inception_v3 import decode_predictions\nfrom tensorflow.python.keras.applications.inception_v3 import preprocess_input\n\ndel _print_function\n\nfrom tensorflow.python.util import module_wrapper as _module_wrapper\n\nif not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):\n _sys.modules[__name__] = _module_wrapper.TFModuleWrapper(\n _sys.modules[__name__], \"keras.applications.inception_v3\", public_apis=None, deprecation=True,\n has_lite=False)\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Bring in all of the public TensorFlow interface into this module.\"\"\"\n\nfrom __future__ import absolute_import as _absolute_import\nfrom __future__ import division as _division\nfrom __future__ import print_function as _print_function\n\nimport os as _os\nimport sys as _sys\nimport six as _six\n\nfrom tensorflow.python.tools import module_util as _module_util\nfrom tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader\n\n# pylint: disable=g-bad-import-order\n\nfrom . import compat\nfrom tensorflow._api.v2.compat.v1 import app\nfrom tensorflow._api.v2.compat.v1 import audio\nfrom tensorflow._api.v2.compat.v1 import autograph\nfrom tensorflow._api.v2.compat.v1 import bitwise\nfrom tensorflow._api.v2.compat.v1 import config\nfrom tensorflow._api.v2.compat.v1 import data\nfrom tensorflow._api.v2.compat.v1 import debugging\nfrom tensorflow._api.v2.compat.v1 import distribute\nfrom tensorflow._api.v2.compat.v1 import distributions\nfrom tensorflow._api.v2.compat.v1 import dtypes\nfrom tensorflow._api.v2.compat.v1 import errors\nfrom tensorflow._api.v2.compat.v1 import experimental\nfrom tensorflow._api.v2.compat.v1 import feature_column\nfrom tensorflow._api.v2.compat.v1 import gfile\nfrom tensorflow._api.v2.compat.v1 import graph_util\nfrom tensorflow._api.v2.compat.v1 import image\nfrom tensorflow._api.v2.compat.v1 import initializers\nfrom tensorflow._api.v2.compat.v1 import io\nfrom tensorflow._api.v2.compat.v1 import layers\nfrom tensorflow._api.v2.compat.v1 import linalg\nfrom tensorflow._api.v2.compat.v1 import lite\nfrom tensorflow._api.v2.compat.v1 import logging\nfrom tensorflow._api.v2.compat.v1 import lookup\nfrom tensorflow._api.v2.compat.v1 import losses\nfrom tensorflow._api.v2.compat.v1 import manip\nfrom tensorflow._api.v2.compat.v1 import math\nfrom tensorflow._api.v2.compat.v1 import metrics\nfrom tensorflow._api.v2.compat.v1 import mixed_precision\nfrom tensorflow._api.v2.compat.v1 import mlir\nfrom tensorflow._api.v2.compat.v1 import nest\nfrom tensorflow._api.v2.compat.v1 import nn\nfrom tensorflow._api.v2.compat.v1 import profiler\nfrom tensorflow._api.v2.compat.v1 import python_io\nfrom tensorflow._api.v2.compat.v1 import quantization\nfrom tensorflow._api.v2.compat.v1 import queue\nfrom tensorflow._api.v2.compat.v1 import ragged\nfrom tensorflow._api.v2.compat.v1 import random\nfrom tensorflow._api.v2.compat.v1 import raw_ops\nfrom tensorflow._api.v2.compat.v1 import resource_loader\nfrom tensorflow._api.v2.compat.v1 import saved_model\nfrom tensorflow._api.v2.compat.v1 import sets\nfrom tensorflow._api.v2.compat.v1 import signal\nfrom tensorflow._api.v2.compat.v1 import sparse\nfrom tensorflow._api.v2.compat.v1 import spectral\nfrom tensorflow._api.v2.compat.v1 import strings\nfrom tensorflow._api.v2.compat.v1 import summary\nfrom tensorflow._api.v2.compat.v1 import sysconfig\nfrom tensorflow._api.v2.compat.v1 import test\nfrom tensorflow._api.v2.compat.v1 import tpu\nfrom tensorflow._api.v2.compat.v1 import train\nfrom tensorflow._api.v2.compat.v1 import user_ops\nfrom tensorflow._api.v2.compat.v1 import version\nfrom tensorflow._api.v2.compat.v1 import xla\nfrom tensorflow.core.framework.attr_value_pb2 import AttrValue\nfrom tensorflow.core.framework.attr_value_pb2 import NameAttrList\nfrom tensorflow.core.framework.graph_pb2 import GraphDef\nfrom tensorflow.core.framework.node_def_pb2 import NodeDef\nfrom tensorflow.core.framework.summary_pb2 import HistogramProto\nfrom tensorflow.core.framework.summary_pb2 import Summary\nfrom tensorflow.core.framework.summary_pb2 import SummaryMetadata\nfrom tensorflow.core.protobuf.config_pb2 import ConfigProto\nfrom tensorflow.core.protobuf.config_pb2 import GPUOptions\nfrom tensorflow.core.protobuf.config_pb2 import GraphOptions\nfrom tensorflow.core.protobuf.config_pb2 import OptimizerOptions\nfrom tensorflow.core.protobuf.config_pb2 import RunMetadata\nfrom tensorflow.core.protobuf.config_pb2 import RunOptions\nfrom tensorflow.core.protobuf.meta_graph_pb2 import MetaGraphDef\nfrom tensorflow.core.protobuf.meta_graph_pb2 import TensorInfo\nfrom tensorflow.core.util.event_pb2 import Event\nfrom tensorflow.core.util.event_pb2 import LogMessage\nfrom tensorflow.core.util.event_pb2 import SessionLog\nfrom tensorflow.python.client.session import InteractiveSession\nfrom tensorflow.python.client.session import Session\nfrom tensorflow.python.compat.v2_compat import disable_v2_behavior\nfrom tensorflow.python.compat.v2_compat import enable_v2_behavior\nfrom tensorflow.python.data.ops.optional_ops import OptionalSpec\nfrom tensorflow.python.eager.backprop import GradientTape\nfrom tensorflow.python.eager.context import executing_eagerly_v1 as executing_eagerly\nfrom tensorflow.python.eager.def_function import function\nfrom tensorflow.python.eager.wrap_function import wrap_function\nfrom tensorflow.python.framework.constant_op import constant_v1 as constant\nfrom tensorflow.python.framework.device_spec import DeviceSpecV1 as DeviceSpec\nfrom tensorflow.python.framework.dtypes import DType\nfrom tensorflow.python.framework.dtypes import QUANTIZED_DTYPES\nfrom tensorflow.python.framework.dtypes import as_dtype\nfrom tensorflow.python.framework.dtypes import bfloat16\nfrom tensorflow.python.framework.dtypes import bool\nfrom tensorflow.python.framework.dtypes import complex128\nfrom tensorflow.python.framework.dtypes import complex64\nfrom tensorflow.python.framework.dtypes import double\nfrom tensorflow.python.framework.dtypes import float16\nfrom tensorflow.python.framework.dtypes import float32\nfrom tensorflow.python.framework.dtypes import float64\nfrom tensorflow.python.framework.dtypes import half\nfrom tensorflow.python.framework.dtypes import int16\nfrom tensorflow.python.framework.dtypes import int32\nfrom tensorflow.python.framework.dtypes import int64\nfrom tensorflow.python.framework.dtypes import int8\nfrom tensorflow.python.framework.dtypes import qint16\nfrom tensorflow.python.framework.dtypes import qint32\nfrom tensorflow.python.framework.dtypes import qint8\nfrom tensorflow.python.framework.dtypes import quint16\nfrom tensorflow.python.framework.dtypes import quint8\nfrom tensorflow.python.framework.dtypes import resource\nfrom tensorflow.python.framework.dtypes import string\nfrom tensorflow.python.framework.dtypes import uint16\nfrom tensorflow.python.framework.dtypes import uint32\nfrom tensorflow.python.framework.dtypes import uint64\nfrom tensorflow.python.framework.dtypes import uint8\nfrom tensorflow.python.framework.dtypes import variant\nfrom tensorflow.python.framework.errors_impl import OpError\nfrom tensorflow.python.framework.importer import import_graph_def\nfrom tensorflow.python.framework.indexed_slices import IndexedSlices\nfrom tensorflow.python.framework.indexed_slices import IndexedSlicesSpec\nfrom tensorflow.python.framework.indexed_slices import convert_to_tensor_or_indexed_slices\nfrom tensorflow.python.framework.load_library import load_file_system_library\nfrom tensorflow.python.framework.load_library import load_library\nfrom tensorflow.python.framework.load_library import load_op_library\nfrom tensorflow.python.framework.ops import Graph\nfrom tensorflow.python.framework.ops import GraphKeys\nfrom tensorflow.python.framework.ops import Operation\nfrom tensorflow.python.framework.ops import RegisterGradient\nfrom tensorflow.python.framework.ops import Tensor\nfrom tensorflow.python.framework.ops import _colocate_with as colocate_with\nfrom tensorflow.python.framework.ops import add_to_collection\nfrom tensorflow.python.framework.ops import add_to_collections\nfrom tensorflow.python.framework.ops import container\nfrom tensorflow.python.framework.ops import control_dependencies\nfrom tensorflow.python.framework.ops import convert_to_tensor_v1 as convert_to_tensor\nfrom tensorflow.python.framework.ops import device\nfrom tensorflow.python.framework.ops import disable_eager_execution\nfrom tensorflow.python.framework.ops import disable_tensor_equality\nfrom tensorflow.python.framework.ops import enable_eager_execution\nfrom tensorflow.python.framework.ops import enable_tensor_equality\nfrom tensorflow.python.framework.ops import executing_eagerly_outside_functions\nfrom tensorflow.python.framework.ops import get_collection\nfrom tensorflow.python.framework.ops import get_collection_ref\nfrom tensorflow.python.framework.ops import get_default_graph\nfrom tensorflow.python.framework.ops import get_default_session\nfrom tensorflow.python.framework.ops import init_scope\nfrom tensorflow.python.framework.ops import name_scope_v1 as name_scope\nfrom tensorflow.python.framework.ops import no_gradient\nfrom tensorflow.python.framework.ops import no_gradient as NoGradient\nfrom tensorflow.python.framework.ops import no_gradient as NotDifferentiable\nfrom tensorflow.python.framework.ops import op_scope\nfrom tensorflow.python.framework.ops import reset_default_graph\nfrom tensorflow.python.framework.random_seed import get_seed\nfrom tensorflow.python.framework.random_seed import set_random_seed\nfrom tensorflow.python.framework.sparse_tensor import SparseTensor\nfrom tensorflow.python.framework.sparse_tensor import SparseTensorSpec\nfrom tensorflow.python.framework.sparse_tensor import SparseTensorValue\nfrom tensorflow.python.framework.sparse_tensor import convert_to_tensor_or_sparse_tensor\nfrom tensorflow.python.framework.tensor_conversion_registry import register_tensor_conversion_function\nfrom tensorflow.python.framework.tensor_shape import Dimension\nfrom tensorflow.python.framework.tensor_shape import TensorShape\nfrom tensorflow.python.framework.tensor_shape import dimension_at_index\nfrom tensorflow.python.framework.tensor_shape import dimension_value\nfrom tensorflow.python.framework.tensor_shape import disable_v2_tensorshape\nfrom tensorflow.python.framework.tensor_shape import enable_v2_tensorshape\nfrom tensorflow.python.framework.tensor_spec import TensorSpec\nfrom tensorflow.python.framework.tensor_util import MakeNdarray as make_ndarray\nfrom tensorflow.python.framework.tensor_util import constant_value as get_static_value\nfrom tensorflow.python.framework.tensor_util import is_tensor\nfrom tensorflow.python.framework.tensor_util import make_tensor_proto\nfrom tensorflow.python.framework.type_spec import TypeSpec\nfrom tensorflow.python.framework.type_spec import type_spec_from_value\nfrom tensorflow.python.framework.versions import COMPILER_VERSION\nfrom tensorflow.python.framework.versions import COMPILER_VERSION as __compiler_version__\nfrom tensorflow.python.framework.versions import CXX11_ABI_FLAG\nfrom tensorflow.python.framework.versions import CXX11_ABI_FLAG as __cxx11_abi_flag__\nfrom tensorflow.python.framework.versions import GIT_VERSION\nfrom tensorflow.python.framework.versions import GIT_VERSION as __git_version__\nfrom tensorflow.python.framework.versions import GRAPH_DEF_VERSION\nfrom tensorflow.python.framework.versions import GRAPH_DEF_VERSION_MIN_CONSUMER\nfrom tensorflow.python.framework.versions import GRAPH_DEF_VERSION_MIN_PRODUCER\nfrom tensorflow.python.framework.versions import MONOLITHIC_BUILD\nfrom tensorflow.python.framework.versions import MONOLITHIC_BUILD as __monolithic_build__\nfrom tensorflow.python.framework.versions import VERSION\nfrom tensorflow.python.framework.versions import VERSION as __version__\nfrom tensorflow.python.module.module import Module\nfrom tensorflow.python.ops.array_ops import batch_gather\nfrom tensorflow.python.ops.array_ops import batch_to_space\nfrom tensorflow.python.ops.array_ops import boolean_mask\nfrom tensorflow.python.ops.array_ops import broadcast_dynamic_shape\nfrom tensorflow.python.ops.array_ops import broadcast_static_shape\nfrom tensorflow.python.ops.array_ops import concat\nfrom tensorflow.python.ops.array_ops import depth_to_space\nfrom tensorflow.python.ops.array_ops import dequantize\nfrom tensorflow.python.ops.array_ops import edit_distance\nfrom tensorflow.python.ops.array_ops import expand_dims\nfrom tensorflow.python.ops.array_ops import extract_image_patches\nfrom tensorflow.python.ops.array_ops import fill\nfrom tensorflow.python.ops.array_ops import fingerprint\nfrom tensorflow.python.ops.array_ops import gather\nfrom tensorflow.python.ops.array_ops import gather_nd\nfrom tensorflow.python.ops.array_ops import identity\nfrom tensorflow.python.ops.array_ops import matrix_diag\nfrom tensorflow.python.ops.array_ops import matrix_diag_part\nfrom tensorflow.python.ops.array_ops import matrix_set_diag\nfrom tensorflow.python.ops.array_ops import matrix_transpose\nfrom tensorflow.python.ops.array_ops import meshgrid\nfrom tensorflow.python.ops.array_ops import newaxis\nfrom tensorflow.python.ops.array_ops import one_hot\nfrom tensorflow.python.ops.array_ops import ones\nfrom tensorflow.python.ops.array_ops import ones_like\nfrom tensorflow.python.ops.array_ops import pad\nfrom tensorflow.python.ops.array_ops import parallel_stack\nfrom tensorflow.python.ops.array_ops import placeholder\nfrom tensorflow.python.ops.array_ops import placeholder_with_default\nfrom tensorflow.python.ops.array_ops import quantize\nfrom tensorflow.python.ops.array_ops import quantize_v2\nfrom tensorflow.python.ops.array_ops import rank\nfrom tensorflow.python.ops.array_ops import repeat\nfrom tensorflow.python.ops.array_ops import required_space_to_batch_paddings\nfrom tensorflow.python.ops.array_ops import reshape\nfrom tensorflow.python.ops.array_ops import reverse_sequence\nfrom tensorflow.python.ops.array_ops import searchsorted\nfrom tensorflow.python.ops.array_ops import sequence_mask\nfrom tensorflow.python.ops.array_ops import setdiff1d\nfrom tensorflow.python.ops.array_ops import shape\nfrom tensorflow.python.ops.array_ops import shape_n\nfrom tensorflow.python.ops.array_ops import size\nfrom tensorflow.python.ops.array_ops import slice\nfrom tensorflow.python.ops.array_ops import space_to_batch\nfrom tensorflow.python.ops.array_ops import space_to_depth\nfrom tensorflow.python.ops.array_ops import sparse_mask\nfrom tensorflow.python.ops.array_ops import sparse_placeholder\nfrom tensorflow.python.ops.array_ops import split\nfrom tensorflow.python.ops.array_ops import squeeze\nfrom tensorflow.python.ops.array_ops import stack\nfrom tensorflow.python.ops.array_ops import strided_slice\nfrom tensorflow.python.ops.array_ops import transpose\nfrom tensorflow.python.ops.array_ops import unique\nfrom tensorflow.python.ops.array_ops import unique_with_counts\nfrom tensorflow.python.ops.array_ops import unstack\nfrom tensorflow.python.ops.array_ops import where\nfrom tensorflow.python.ops.array_ops import where_v2\nfrom tensorflow.python.ops.array_ops import zeros\nfrom tensorflow.python.ops.array_ops import zeros_like\nfrom tensorflow.python.ops.batch_ops import batch_function as nondifferentiable_batch_function\nfrom tensorflow.python.ops.bincount_ops import bincount_v1 as bincount\nfrom tensorflow.python.ops.check_ops import assert_equal\nfrom tensorflow.python.ops.check_ops import assert_greater\nfrom tensorflow.python.ops.check_ops import assert_greater_equal\nfrom tensorflow.python.ops.check_ops import assert_integer\nfrom tensorflow.python.ops.check_ops import assert_less\nfrom tensorflow.python.ops.check_ops import assert_less_equal\nfrom tensorflow.python.ops.check_ops import assert_near\nfrom tensorflow.python.ops.check_ops import assert_negative\nfrom tensorflow.python.ops.check_ops import assert_non_negative\nfrom tensorflow.python.ops.check_ops import assert_non_positive\nfrom tensorflow.python.ops.check_ops import assert_none_equal\nfrom tensorflow.python.ops.check_ops import assert_positive\nfrom tensorflow.python.ops.check_ops import assert_proper_iterable\nfrom tensorflow.python.ops.check_ops import assert_rank\nfrom tensorflow.python.ops.check_ops import assert_rank_at_least\nfrom tensorflow.python.ops.check_ops import assert_rank_in\nfrom tensorflow.python.ops.check_ops import assert_same_float_dtype\nfrom tensorflow.python.ops.check_ops import assert_scalar\nfrom tensorflow.python.ops.check_ops import assert_type\nfrom tensorflow.python.ops.check_ops import ensure_shape\nfrom tensorflow.python.ops.check_ops import is_non_decreasing\nfrom tensorflow.python.ops.check_ops import is_numeric_tensor\nfrom tensorflow.python.ops.check_ops import is_strictly_increasing\nfrom tensorflow.python.ops.clip_ops import clip_by_average_norm\nfrom tensorflow.python.ops.clip_ops import clip_by_global_norm\nfrom tensorflow.python.ops.clip_ops import clip_by_norm\nfrom tensorflow.python.ops.clip_ops import clip_by_value\nfrom tensorflow.python.ops.clip_ops import global_norm\nfrom tensorflow.python.ops.confusion_matrix import confusion_matrix_v1 as confusion_matrix\nfrom tensorflow.python.ops.control_flow_ops import Assert\nfrom tensorflow.python.ops.control_flow_ops import case\nfrom tensorflow.python.ops.control_flow_ops import cond\nfrom tensorflow.python.ops.control_flow_ops import group\nfrom tensorflow.python.ops.control_flow_ops import switch_case\nfrom tensorflow.python.ops.control_flow_ops import tuple\nfrom tensorflow.python.ops.control_flow_ops import while_loop\nfrom tensorflow.python.ops.control_flow_v2_toggles import control_flow_v2_enabled\nfrom tensorflow.python.ops.control_flow_v2_toggles import disable_control_flow_v2\nfrom tensorflow.python.ops.control_flow_v2_toggles import enable_control_flow_v2\nfrom tensorflow.python.ops.critical_section_ops import CriticalSection\nfrom tensorflow.python.ops.custom_gradient import custom_gradient\nfrom tensorflow.python.ops.custom_gradient import grad_pass_through\nfrom tensorflow.python.ops.custom_gradient import recompute_grad\nfrom tensorflow.python.ops.data_flow_ops import ConditionalAccumulator\nfrom tensorflow.python.ops.data_flow_ops import ConditionalAccumulatorBase\nfrom tensorflow.python.ops.data_flow_ops import FIFOQueue\nfrom tensorflow.python.ops.data_flow_ops import PaddingFIFOQueue\nfrom tensorflow.python.ops.data_flow_ops import PriorityQueue\nfrom tensorflow.python.ops.data_flow_ops import QueueBase\nfrom tensorflow.python.ops.data_flow_ops import RandomShuffleQueue\nfrom tensorflow.python.ops.data_flow_ops import SparseConditionalAccumulator\nfrom tensorflow.python.ops.functional_ops import foldl\nfrom tensorflow.python.ops.functional_ops import foldr\nfrom tensorflow.python.ops.functional_ops import scan\nfrom tensorflow.python.ops.gen_array_ops import batch_to_space_nd\nfrom tensorflow.python.ops.gen_array_ops import bitcast\nfrom tensorflow.python.ops.gen_array_ops import broadcast_to\nfrom tensorflow.python.ops.gen_array_ops import check_numerics\nfrom tensorflow.python.ops.gen_array_ops import diag\nfrom tensorflow.python.ops.gen_array_ops import diag_part\nfrom tensorflow.python.ops.gen_array_ops import extract_volume_patches\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_args\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_args_gradient\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_vars\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_vars_gradient\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_vars_per_channel\nfrom tensorflow.python.ops.gen_array_ops import fake_quant_with_min_max_vars_per_channel_gradient\nfrom tensorflow.python.ops.gen_array_ops import guarantee_const\nfrom tensorflow.python.ops.gen_array_ops import identity_n\nfrom tensorflow.python.ops.gen_array_ops import invert_permutation\nfrom tensorflow.python.ops.gen_array_ops import matrix_band_part\nfrom tensorflow.python.ops.gen_array_ops import quantized_concat\nfrom tensorflow.python.ops.gen_array_ops import reverse_v2\nfrom tensorflow.python.ops.gen_array_ops import reverse_v2 as reverse\nfrom tensorflow.python.ops.gen_array_ops import scatter_nd\nfrom tensorflow.python.ops.gen_array_ops import space_to_batch_nd\nfrom tensorflow.python.ops.gen_array_ops import stop_gradient\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_add\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_add as tensor_scatter_nd_add\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_max as tensor_scatter_nd_max\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_min as tensor_scatter_nd_min\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_sub\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_sub as tensor_scatter_nd_sub\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_update\nfrom tensorflow.python.ops.gen_array_ops import tensor_scatter_update as tensor_scatter_nd_update\nfrom tensorflow.python.ops.gen_array_ops import tile\nfrom tensorflow.python.ops.gen_array_ops import unravel_index\nfrom tensorflow.python.ops.gen_control_flow_ops import no_op\nfrom tensorflow.python.ops.gen_data_flow_ops import dynamic_partition\nfrom tensorflow.python.ops.gen_data_flow_ops import dynamic_stitch\nfrom tensorflow.python.ops.gen_io_ops import matching_files\nfrom tensorflow.python.ops.gen_io_ops import read_file\nfrom tensorflow.python.ops.gen_io_ops import write_file\nfrom tensorflow.python.ops.gen_linalg_ops import cholesky\nfrom tensorflow.python.ops.gen_linalg_ops import matrix_determinant\nfrom tensorflow.python.ops.gen_linalg_ops import matrix_inverse\nfrom tensorflow.python.ops.gen_linalg_ops import matrix_solve\nfrom tensorflow.python.ops.gen_linalg_ops import matrix_square_root\nfrom tensorflow.python.ops.gen_linalg_ops import qr\nfrom tensorflow.python.ops.gen_logging_ops import timestamp\nfrom tensorflow.python.ops.gen_math_ops import acos\nfrom tensorflow.python.ops.gen_math_ops import acosh\nfrom tensorflow.python.ops.gen_math_ops import add\nfrom tensorflow.python.ops.gen_math_ops import arg_max\nfrom tensorflow.python.ops.gen_math_ops import arg_min\nfrom tensorflow.python.ops.gen_math_ops import asin\nfrom tensorflow.python.ops.gen_math_ops import asinh\nfrom tensorflow.python.ops.gen_math_ops import atan\nfrom tensorflow.python.ops.gen_math_ops import atan2\nfrom tensorflow.python.ops.gen_math_ops import atanh\nfrom tensorflow.python.ops.gen_math_ops import betainc\nfrom tensorflow.python.ops.gen_math_ops import cos\nfrom tensorflow.python.ops.gen_math_ops import cosh\nfrom tensorflow.python.ops.gen_math_ops import cross\nfrom tensorflow.python.ops.gen_math_ops import digamma\nfrom tensorflow.python.ops.gen_math_ops import erf\nfrom tensorflow.python.ops.gen_math_ops import erfc\nfrom tensorflow.python.ops.gen_math_ops import expm1\nfrom tensorflow.python.ops.gen_math_ops import floor\nfrom tensorflow.python.ops.gen_math_ops import floor_div\nfrom tensorflow.python.ops.gen_math_ops import floor_mod as floormod\nfrom tensorflow.python.ops.gen_math_ops import floor_mod as mod\nfrom tensorflow.python.ops.gen_math_ops import greater\nfrom tensorflow.python.ops.gen_math_ops import greater_equal\nfrom tensorflow.python.ops.gen_math_ops import igamma\nfrom tensorflow.python.ops.gen_math_ops import igammac\nfrom tensorflow.python.ops.gen_math_ops import is_finite\nfrom tensorflow.python.ops.gen_math_ops import is_inf\nfrom tensorflow.python.ops.gen_math_ops import is_nan\nfrom tensorflow.python.ops.gen_math_ops import less\nfrom tensorflow.python.ops.gen_math_ops import less_equal\nfrom tensorflow.python.ops.gen_math_ops import lgamma\nfrom tensorflow.python.ops.gen_math_ops import log\nfrom tensorflow.python.ops.gen_math_ops import log1p\nfrom tensorflow.python.ops.gen_math_ops import logical_not\nfrom tensorflow.python.ops.gen_math_ops import logical_or\nfrom tensorflow.python.ops.gen_math_ops import maximum\nfrom tensorflow.python.ops.gen_math_ops import minimum\nfrom tensorflow.python.ops.gen_math_ops import neg as negative\nfrom tensorflow.python.ops.gen_math_ops import polygamma\nfrom tensorflow.python.ops.gen_math_ops import real_div as realdiv\nfrom tensorflow.python.ops.gen_math_ops import reciprocal\nfrom tensorflow.python.ops.gen_math_ops import rint\nfrom tensorflow.python.ops.gen_math_ops import segment_max\nfrom tensorflow.python.ops.gen_math_ops import segment_mean\nfrom tensorflow.python.ops.gen_math_ops import segment_min\nfrom tensorflow.python.ops.gen_math_ops import segment_prod\nfrom tensorflow.python.ops.gen_math_ops import segment_sum\nfrom tensorflow.python.ops.gen_math_ops import sin\nfrom tensorflow.python.ops.gen_math_ops import sinh\nfrom tensorflow.python.ops.gen_math_ops import sparse_mat_mul as sparse_matmul\nfrom tensorflow.python.ops.gen_math_ops import square\nfrom tensorflow.python.ops.gen_math_ops import squared_difference\nfrom tensorflow.python.ops.gen_math_ops import tan\nfrom tensorflow.python.ops.gen_math_ops import tanh\nfrom tensorflow.python.ops.gen_math_ops import truncate_div as truncatediv\nfrom tensorflow.python.ops.gen_math_ops import truncate_mod as truncatemod\nfrom tensorflow.python.ops.gen_math_ops import unsorted_segment_max\nfrom tensorflow.python.ops.gen_math_ops import unsorted_segment_min\nfrom tensorflow.python.ops.gen_math_ops import unsorted_segment_prod\nfrom tensorflow.python.ops.gen_math_ops import unsorted_segment_sum\nfrom tensorflow.python.ops.gen_math_ops import zeta\nfrom tensorflow.python.ops.gen_parsing_ops import decode_compressed\nfrom tensorflow.python.ops.gen_parsing_ops import decode_json_example\nfrom tensorflow.python.ops.gen_parsing_ops import parse_tensor\nfrom tensorflow.python.ops.gen_parsing_ops import serialize_tensor\nfrom tensorflow.python.ops.gen_spectral_ops import fft\nfrom tensorflow.python.ops.gen_spectral_ops import fft2d\nfrom tensorflow.python.ops.gen_spectral_ops import fft3d\nfrom tensorflow.python.ops.gen_spectral_ops import ifft\nfrom tensorflow.python.ops.gen_spectral_ops import ifft2d\nfrom tensorflow.python.ops.gen_spectral_ops import ifft3d\nfrom tensorflow.python.ops.gen_string_ops import as_string\nfrom tensorflow.python.ops.gen_string_ops import decode_base64\nfrom tensorflow.python.ops.gen_string_ops import encode_base64\nfrom tensorflow.python.ops.gen_string_ops import string_strip\nfrom tensorflow.python.ops.gen_string_ops import string_to_hash_bucket_fast\nfrom tensorflow.python.ops.gen_string_ops import string_to_hash_bucket_strong\nfrom tensorflow.python.ops.gradients_impl import gradients\nfrom tensorflow.python.ops.gradients_impl import hessians\nfrom tensorflow.python.ops.gradients_util import AggregationMethod\nfrom tensorflow.python.ops.histogram_ops import histogram_fixed_width\nfrom tensorflow.python.ops.histogram_ops import histogram_fixed_width_bins\nfrom tensorflow.python.ops.init_ops import Constant as constant_initializer\nfrom tensorflow.python.ops.init_ops import GlorotNormal as glorot_normal_initializer\nfrom tensorflow.python.ops.init_ops import GlorotUniform as glorot_uniform_initializer\nfrom tensorflow.python.ops.init_ops import Ones as ones_initializer\nfrom tensorflow.python.ops.init_ops import Orthogonal as orthogonal_initializer\nfrom tensorflow.python.ops.init_ops import RandomNormal as random_normal_initializer\nfrom tensorflow.python.ops.init_ops import RandomUniform as random_uniform_initializer\nfrom tensorflow.python.ops.init_ops import TruncatedNormal as truncated_normal_initializer\nfrom tensorflow.python.ops.init_ops import UniformUnitScaling as uniform_unit_scaling_initializer\nfrom tensorflow.python.ops.init_ops import VarianceScaling as variance_scaling_initializer\nfrom tensorflow.python.ops.init_ops import Zeros as zeros_initializer\nfrom tensorflow.python.ops.io_ops import FixedLengthRecordReader\nfrom tensorflow.python.ops.io_ops import IdentityReader\nfrom tensorflow.python.ops.io_ops import LMDBReader\nfrom tensorflow.python.ops.io_ops import ReaderBase\nfrom tensorflow.python.ops.io_ops import TFRecordReader\nfrom tensorflow.python.ops.io_ops import TextLineReader\nfrom tensorflow.python.ops.io_ops import WholeFileReader\nfrom tensorflow.python.ops.linalg_ops import cholesky_solve\nfrom tensorflow.python.ops.linalg_ops import eye\nfrom tensorflow.python.ops.linalg_ops import matrix_solve_ls\nfrom tensorflow.python.ops.linalg_ops import matrix_triangular_solve\nfrom tensorflow.python.ops.linalg_ops import norm\nfrom tensorflow.python.ops.linalg_ops import self_adjoint_eig\nfrom tensorflow.python.ops.linalg_ops import self_adjoint_eigvals\nfrom tensorflow.python.ops.linalg_ops import svd\nfrom tensorflow.python.ops.logging_ops import Print\nfrom tensorflow.python.ops.logging_ops import print_v2 as print\nfrom tensorflow.python.ops.lookup_ops import initialize_all_tables\nfrom tensorflow.python.ops.lookup_ops import tables_initializer\nfrom tensorflow.python.ops.manip_ops import roll\nfrom tensorflow.python.ops.map_fn import map_fn\nfrom tensorflow.python.ops.math_ops import abs\nfrom tensorflow.python.ops.math_ops import accumulate_n\nfrom tensorflow.python.ops.math_ops import add_n\nfrom tensorflow.python.ops.math_ops import angle\nfrom tensorflow.python.ops.math_ops import argmax\nfrom tensorflow.python.ops.math_ops import argmin\nfrom tensorflow.python.ops.math_ops import cast\nfrom tensorflow.python.ops.math_ops import ceil\nfrom tensorflow.python.ops.math_ops import complex\nfrom tensorflow.python.ops.math_ops import conj\nfrom tensorflow.python.ops.math_ops import count_nonzero\nfrom tensorflow.python.ops.math_ops import cumprod\nfrom tensorflow.python.ops.math_ops import cumsum\nfrom tensorflow.python.ops.math_ops import div\nfrom tensorflow.python.ops.math_ops import div_no_nan\nfrom tensorflow.python.ops.math_ops import divide\nfrom tensorflow.python.ops.math_ops import equal\nfrom tensorflow.python.ops.math_ops import exp\nfrom tensorflow.python.ops.math_ops import floordiv\nfrom tensorflow.python.ops.math_ops import imag\nfrom tensorflow.python.ops.math_ops import linspace_nd as lin_space\nfrom tensorflow.python.ops.math_ops import linspace_nd as linspace\nfrom tensorflow.python.ops.math_ops import log_sigmoid\nfrom tensorflow.python.ops.math_ops import logical_and\nfrom tensorflow.python.ops.math_ops import logical_xor\nfrom tensorflow.python.ops.math_ops import matmul\nfrom tensorflow.python.ops.math_ops import multiply\nfrom tensorflow.python.ops.math_ops import not_equal\nfrom tensorflow.python.ops.math_ops import pow\nfrom tensorflow.python.ops.math_ops import range\nfrom tensorflow.python.ops.math_ops import real\nfrom tensorflow.python.ops.math_ops import reduce_all_v1 as reduce_all\nfrom tensorflow.python.ops.math_ops import reduce_any_v1 as reduce_any\nfrom tensorflow.python.ops.math_ops import reduce_logsumexp_v1 as reduce_logsumexp\nfrom tensorflow.python.ops.math_ops import reduce_max_v1 as reduce_max\nfrom tensorflow.python.ops.math_ops import reduce_mean_v1 as reduce_mean\nfrom tensorflow.python.ops.math_ops import reduce_min_v1 as reduce_min\nfrom tensorflow.python.ops.math_ops import reduce_prod_v1 as reduce_prod\nfrom tensorflow.python.ops.math_ops import reduce_sum_v1 as reduce_sum\nfrom tensorflow.python.ops.math_ops import round\nfrom tensorflow.python.ops.math_ops import rsqrt\nfrom tensorflow.python.ops.math_ops import saturate_cast\nfrom tensorflow.python.ops.math_ops import scalar_mul\nfrom tensorflow.python.ops.math_ops import sigmoid\nfrom tensorflow.python.ops.math_ops import sign\nfrom tensorflow.python.ops.math_ops import sparse_segment_mean\nfrom tensorflow.python.ops.math_ops import sparse_segment_sqrt_n\nfrom tensorflow.python.ops.math_ops import sparse_segment_sum\nfrom tensorflow.python.ops.math_ops import sqrt\nfrom tensorflow.python.ops.math_ops import subtract\nfrom tensorflow.python.ops.math_ops import tensordot\nfrom tensorflow.python.ops.math_ops import to_bfloat16\nfrom tensorflow.python.ops.math_ops import to_complex128\nfrom tensorflow.python.ops.math_ops import to_complex64\nfrom tensorflow.python.ops.math_ops import to_double\nfrom tensorflow.python.ops.math_ops import to_float\nfrom tensorflow.python.ops.math_ops import to_int32\nfrom tensorflow.python.ops.math_ops import to_int64\nfrom tensorflow.python.ops.math_ops import trace\nfrom tensorflow.python.ops.math_ops import truediv\nfrom tensorflow.python.ops.math_ops import unsorted_segment_mean\nfrom tensorflow.python.ops.math_ops import unsorted_segment_sqrt_n\nfrom tensorflow.python.ops.numerics import add_check_numerics_ops\nfrom tensorflow.python.ops.numerics import verify_tensor_all_finite\nfrom tensorflow.python.ops.parallel_for.control_flow_ops import vectorized_map\nfrom tensorflow.python.ops.parsing_config import FixedLenFeature\nfrom tensorflow.python.ops.parsing_config import FixedLenSequenceFeature\nfrom tensorflow.python.ops.parsing_config import SparseFeature\nfrom tensorflow.python.ops.parsing_config import VarLenFeature\nfrom tensorflow.python.ops.parsing_ops import decode_csv\nfrom tensorflow.python.ops.parsing_ops import decode_raw_v1 as decode_raw\nfrom tensorflow.python.ops.parsing_ops import parse_example\nfrom tensorflow.python.ops.parsing_ops import parse_single_example\nfrom tensorflow.python.ops.parsing_ops import parse_single_sequence_example\nfrom tensorflow.python.ops.partitioned_variables import create_partitioned_variables\nfrom tensorflow.python.ops.partitioned_variables import fixed_size_partitioner\nfrom tensorflow.python.ops.partitioned_variables import min_max_variable_partitioner\nfrom tensorflow.python.ops.partitioned_variables import variable_axis_size_partitioner\nfrom tensorflow.python.ops.ragged.ragged_string_ops import string_split\nfrom tensorflow.python.ops.ragged.ragged_tensor import RaggedTensor\nfrom tensorflow.python.ops.ragged.ragged_tensor import RaggedTensorSpec\nfrom tensorflow.python.ops.random_ops import multinomial\nfrom tensorflow.python.ops.random_ops import random_crop\nfrom tensorflow.python.ops.random_ops import random_gamma\nfrom tensorflow.python.ops.random_ops import random_normal\nfrom tensorflow.python.ops.random_ops import random_poisson\nfrom tensorflow.python.ops.random_ops import random_shuffle\nfrom tensorflow.python.ops.random_ops import random_uniform\nfrom tensorflow.python.ops.random_ops import truncated_normal\nfrom tensorflow.python.ops.script_ops import eager_py_func as py_function\nfrom tensorflow.python.ops.script_ops import numpy_function\nfrom tensorflow.python.ops.script_ops import py_func\nfrom tensorflow.python.ops.session_ops import delete_session_tensor\nfrom tensorflow.python.ops.session_ops import get_session_handle\nfrom tensorflow.python.ops.session_ops import get_session_tensor\nfrom tensorflow.python.ops.sort_ops import argsort\nfrom tensorflow.python.ops.sort_ops import sort\nfrom tensorflow.python.ops.sparse_ops import deserialize_many_sparse\nfrom tensorflow.python.ops.sparse_ops import serialize_many_sparse\nfrom tensorflow.python.ops.sparse_ops import serialize_sparse\nfrom tensorflow.python.ops.sparse_ops import sparse_add\nfrom tensorflow.python.ops.sparse_ops import sparse_concat\nfrom tensorflow.python.ops.sparse_ops import sparse_fill_empty_rows\nfrom tensorflow.python.ops.sparse_ops import sparse_maximum\nfrom tensorflow.python.ops.sparse_ops import sparse_merge\nfrom tensorflow.python.ops.sparse_ops import sparse_minimum\nfrom tensorflow.python.ops.sparse_ops import sparse_reduce_max\nfrom tensorflow.python.ops.sparse_ops import sparse_reduce_max_sparse\nfrom tensorflow.python.ops.sparse_ops import sparse_reduce_sum\nfrom tensorflow.python.ops.sparse_ops import sparse_reduce_sum_sparse\nfrom tensorflow.python.ops.sparse_ops import sparse_reorder\nfrom tensorflow.python.ops.sparse_ops import sparse_reset_shape\nfrom tensorflow.python.ops.sparse_ops import sparse_reshape\nfrom tensorflow.python.ops.sparse_ops import sparse_retain\nfrom tensorflow.python.ops.sparse_ops import sparse_slice\nfrom tensorflow.python.ops.sparse_ops import sparse_softmax\nfrom tensorflow.python.ops.sparse_ops import sparse_split\nfrom tensorflow.python.ops.sparse_ops import sparse_tensor_dense_matmul\nfrom tensorflow.python.ops.sparse_ops import sparse_tensor_to_dense\nfrom tensorflow.python.ops.sparse_ops import sparse_to_dense\nfrom tensorflow.python.ops.sparse_ops import sparse_to_indicator\nfrom tensorflow.python.ops.sparse_ops import sparse_transpose\nfrom tensorflow.python.ops.special_math_ops import einsum\nfrom tensorflow.python.ops.special_math_ops import lbeta\nfrom tensorflow.python.ops.state_ops import assign\nfrom tensorflow.python.ops.state_ops import assign_add\nfrom tensorflow.python.ops.state_ops import assign_sub\nfrom tensorflow.python.ops.state_ops import batch_scatter_update\nfrom tensorflow.python.ops.state_ops import count_up_to\nfrom tensorflow.python.ops.state_ops import scatter_add\nfrom tensorflow.python.ops.state_ops import scatter_div\nfrom tensorflow.python.ops.state_ops import scatter_max\nfrom tensorflow.python.ops.state_ops import scatter_min\nfrom tensorflow.python.ops.state_ops import scatter_mul\nfrom tensorflow.python.ops.state_ops import scatter_nd_add\nfrom tensorflow.python.ops.state_ops import scatter_nd_sub\nfrom tensorflow.python.ops.state_ops import scatter_nd_update\nfrom tensorflow.python.ops.state_ops import scatter_sub\nfrom tensorflow.python.ops.state_ops import scatter_update\nfrom tensorflow.python.ops.string_ops import reduce_join\nfrom tensorflow.python.ops.string_ops import regex_replace\nfrom tensorflow.python.ops.string_ops import string_join\nfrom tensorflow.python.ops.string_ops import string_to_hash_bucket_v1 as string_to_hash_bucket\nfrom tensorflow.python.ops.string_ops import string_to_number_v1 as string_to_number\nfrom tensorflow.python.ops.string_ops import substr_deprecated as substr\nfrom tensorflow.python.ops.template import make_template\nfrom tensorflow.python.ops.tensor_array_ops import TensorArray\nfrom tensorflow.python.ops.tensor_array_ops import TensorArraySpec\nfrom tensorflow.python.ops.unconnected_gradients import UnconnectedGradients\nfrom tensorflow.python.ops.variable_scope import AUTO_REUSE\nfrom tensorflow.python.ops.variable_scope import VariableScope\nfrom tensorflow.python.ops.variable_scope import disable_resource_variables\nfrom tensorflow.python.ops.variable_scope import enable_resource_variables\nfrom tensorflow.python.ops.variable_scope import get_local_variable\nfrom tensorflow.python.ops.variable_scope import get_variable\nfrom tensorflow.python.ops.variable_scope import get_variable_scope\nfrom tensorflow.python.ops.variable_scope import no_regularizer\nfrom tensorflow.python.ops.variable_scope import resource_variables_enabled\nfrom tensorflow.python.ops.variable_scope import variable_creator_scope_v1 as variable_creator_scope\nfrom tensorflow.python.ops.variable_scope import variable_op_scope\nfrom tensorflow.python.ops.variable_scope import variable_scope\nfrom tensorflow.python.ops.variables import VariableAggregation\nfrom tensorflow.python.ops.variables import VariableSynchronization\nfrom tensorflow.python.ops.variables import VariableV1 as Variable\nfrom tensorflow.python.ops.variables import all_variables\nfrom tensorflow.python.ops.variables import assert_variables_initialized\nfrom tensorflow.python.ops.variables import global_variables\nfrom tensorflow.python.ops.variables import global_variables_initializer\nfrom tensorflow.python.ops.variables import initialize_all_variables\nfrom tensorflow.python.ops.variables import initialize_local_variables\nfrom tensorflow.python.ops.variables import initialize_variables\nfrom tensorflow.python.ops.variables import is_variable_initialized\nfrom tensorflow.python.ops.variables import local_variables\nfrom tensorflow.python.ops.variables import local_variables_initializer\nfrom tensorflow.python.ops.variables import model_variables\nfrom tensorflow.python.ops.variables import moving_average_variables\nfrom tensorflow.python.ops.variables import report_uninitialized_variables\nfrom tensorflow.python.ops.variables import trainable_variables\nfrom tensorflow.python.ops.variables import variables_initializer\nfrom tensorflow.python.platform.tf_logging import get_logger\n\n# WRAPPER_PLACEHOLDER\n\n# Hook external TensorFlow modules.\n_current_module = _sys.modules[__name__]\n\n# Lazy-load estimator.\n_estimator_module = \"tensorflow_estimator.python.estimator.api._v1.estimator\"\nestimator = _LazyLoader(\"estimator\", globals(), _estimator_module)\n_module_dir = _module_util.get_parent_dir_for_name(_estimator_module)\nif _module_dir:\n _current_module.__path__ = [_module_dir] + _current_module.__path__\nsetattr(_current_module, \"estimator\", estimator)\n\ntry:\n from tensorflow.python.keras.api._v1 import keras\n _current_module.__path__ = (\n [_module_util.get_parent_dir(keras)] + _current_module.__path__)\n setattr(_current_module, \"keras\", keras)\nexcept ImportError:\n pass\n\n# Explicitly import lazy-loaded modules to support autocompletion.\n# pylint: disable=g-import-not-at-top\nif not _six.PY2:\n import typing as _typing\n if _typing.TYPE_CHECKING:\n from tensorflow_estimator.python.estimator.api._v1 import estimator\n# pylint: enable=g-import-not-at-top\n\n\nfrom tensorflow.python.platform import flags # pylint: disable=g-import-not-at-top\n_current_module.app.flags = flags # pylint: disable=undefined-variable\nsetattr(_current_module, \"flags\", flags)\n", "import tensorflow as tf\nfrom PIL import Image\n\n\nclass ImageSimilarity:\n\n def compare(self, path1, path2):\n # Read images from file.\n img_raw = tf.io.read_file(path1)\n\n img1 = tf.io.decode_image(\n img_raw, channels=3, dtype=tf.dtypes.uint8, name=None,\n expand_animations=True\n )\n\n img1 = tf.image.resize(img1, (224, 224))\n img_raw2 = tf.io.read_file(path2)\n img2 = tf.io.decode_image(\n img_raw2, channels=3, dtype=tf.dtypes.uint8, name=None,\n expand_animations=True\n )\n img2 = tf.image.resize(img2, (224, 224))\n\n # Compute SSIM over tf.uint8 Tensors.\n ssim1 = tf.image.ssim(img1, img2, max_val=255, filter_size=11,\n filter_sigma=1.5, k1=0.01, k2=0.03)\n\n # Compute SSIM over tf.float32 Tensors.\n im1 = tf.image.convert_image_dtype(img1, tf.float32)\n im2 = tf.image.convert_image_dtype(img2, tf.float32)\n ssim2 = tf.image.ssim(im1, im2, max_val=1.0, filter_size=11,\n filter_sigma=1.5, k1=0.01, k2=0.03)\n # ssim1 and ssim2 both have type tf.float32 and are almost equal.\n # tf.compat.v1.disable_eager_execution()\n # with tf.compat.v1.Session() as sess:\n # print(ssim1.eval())\n # print(ssim1.numpy())\n compare1 = ssim1.numpy() * 100.0\n compare2 = ssim2.numpy() * 100.0\n # print(ssim2.numpy())\n print(\"Le immagini sono simili al : \" + str(compare1) + \" %\")\n # print(\"Le immagini sono simili al : \"+str(compare2)+\" %\")\n average = (compare1 + compare2) / 2.0\n #print(\"Le immagini sono simili al : \" + str(average))\n return compare1\n\n\n# print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n# tf.test.gpu_device_name()\n# tf.config.list_physical_devices('GPU')\n\n", "\"\"\"\nAlgorithms for computing the skeleton of a binary image\n\"\"\"\n\n\nimport numpy as np\nfrom ..util import img_as_ubyte, crop\nfrom scipy import ndimage as ndi\n\nfrom .._shared.utils import check_nD, warn\nfrom ._skeletonize_cy import (_fast_skeletonize, _skeletonize_loop,\n _table_lookup_index)\nfrom ._skeletonize_3d_cy import _compute_thin_image\n\n\ndef skeletonize(image, *, method=None):\n \"\"\"Compute the skeleton of a binary image.\n\n Thinning is used to reduce each connected component in a binary image\n to a single-pixel wide skeleton.\n\n Parameters\n ----------\n image : ndarray, 2D or 3D\n A binary image containing the objects to be skeletonized. Zeros\n represent background, nonzero values are foreground.\n method : {'zhang', 'lee'}, optional\n Which algorithm to use. Zhang's algorithm [Zha84]_ only works for\n 2D images, and is the default for 2D. Lee's algorithm [Lee94]_\n works for 2D or 3D images and is the default for 3D.\n\n Returns\n -------\n skeleton : ndarray\n The thinned image.\n\n See also\n --------\n medial_axis\n\n References\n ----------\n .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models\n via 3-D medial surface/axis thinning algorithms.\n Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.\n\n .. [Zha84] A fast parallel algorithm for thinning digital patterns,\n T. Y. Zhang and C. Y. Suen, Communications of the ACM,\n March 1984, Volume 27, Number 3.\n\n\n Examples\n --------\n >>> X, Y = np.ogrid[0:9, 0:9]\n >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(np.uint8)\n >>> ellipse\n array([[0, 0, 0, 1, 1, 1, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)\n >>> skel = skeletonize(ellipse)\n >>> skel.astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n\n \"\"\"\n\n if image.ndim == 2 and (method is None or method == 'zhang'):\n skeleton = skeletonize_2d(image)\n elif image.ndim == 3 and method == 'zhang':\n raise ValueError('skeletonize method \"zhang\" only works for 2D '\n 'images.')\n elif image.ndim == 3 or (image.ndim == 2 and method == 'lee'):\n skeleton = skeletonize_3d(image)\n else:\n raise ValueError('skeletonize requires a 2D or 3D image as input, '\n 'got {}D.'.format(image.ndim))\n return skeleton\n\n\ndef skeletonize_2d(image):\n \"\"\"Return the skeleton of a 2D binary image.\n\n Thinning is used to reduce each connected component in a binary image\n to a single-pixel wide skeleton.\n\n Parameters\n ----------\n image : numpy.ndarray\n A binary image containing the objects to be skeletonized. '1'\n represents foreground, and '0' represents background. It\n also accepts arrays of boolean values where True is foreground.\n\n Returns\n -------\n skeleton : ndarray\n A matrix containing the thinned image.\n\n See also\n --------\n medial_axis\n\n Notes\n -----\n The algorithm [Zha84]_ works by making successive passes of the image,\n removing pixels on object borders. This continues until no\n more pixels can be removed. The image is correlated with a\n mask that assigns each pixel a number in the range [0...255]\n corresponding to each possible pattern of its 8 neighbouring\n pixels. A look up table is then used to assign the pixels a\n value of 0, 1, 2 or 3, which are selectively removed during\n the iterations.\n\n Note that this algorithm will give different results than a\n medial axis transform, which is also often referred to as\n \"skeletonization\".\n\n References\n ----------\n .. [Zha84] A fast parallel algorithm for thinning digital patterns,\n T. Y. Zhang and C. Y. Suen, Communications of the ACM,\n March 1984, Volume 27, Number 3.\n\n\n Examples\n --------\n >>> X, Y = np.ogrid[0:9, 0:9]\n >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(np.uint8)\n >>> ellipse\n array([[0, 0, 0, 1, 1, 1, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)\n >>> skel = skeletonize(ellipse)\n >>> skel.astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n\n \"\"\"\n\n # convert to unsigned int (this should work for boolean values)\n image = image.astype(np.uint8)\n\n # check some properties of the input image:\n # - 2D\n # - binary image with only 0's and 1's\n if image.ndim != 2:\n raise ValueError('Skeletonize requires a 2D array')\n if not np.all(np.in1d(image.flat, (0, 1))):\n raise ValueError('Image contains values other than 0 and 1')\n\n return _fast_skeletonize(image)\n\n\n# --------- Skeletonization and thinning based on Guo and Hall 1989 ---------\n\ndef _generate_thin_luts():\n \"\"\"generate LUTs for thinning algorithm (for reference)\"\"\"\n\n def nabe(n):\n return np.array([n >> i & 1 for i in range(0, 9)]).astype(np.bool)\n\n def G1(n):\n s = 0\n bits = nabe(n)\n for i in (0, 2, 4, 6):\n if not(bits[i]) and (bits[i + 1] or bits[(i + 2) % 8]):\n s += 1\n return s == 1\n\n g1_lut = np.array([G1(n) for n in range(256)])\n\n def G2(n):\n n1, n2 = 0, 0\n bits = nabe(n)\n for k in (1, 3, 5, 7):\n if bits[k] or bits[k - 1]:\n n1 += 1\n if bits[k] or bits[(k + 1) % 8]:\n n2 += 1\n return min(n1, n2) in [2, 3]\n\n g2_lut = np.array([G2(n) for n in range(256)])\n\n g12_lut = g1_lut & g2_lut\n\n def G3(n):\n bits = nabe(n)\n return not((bits[1] or bits[2] or not(bits[7])) and bits[0])\n\n def G3p(n):\n bits = nabe(n)\n return not((bits[5] or bits[6] or not(bits[3])) and bits[4])\n\n g3_lut = np.array([G3(n) for n in range(256)])\n g3p_lut = np.array([G3p(n) for n in range(256)])\n\n g123_lut = g12_lut & g3_lut\n g123p_lut = g12_lut & g3p_lut\n\n return g123_lut, g123p_lut\n\n\nG123_LUT = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1,\n 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,\n 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=np.bool)\n\nG123P_LUT = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1,\n 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.bool)\n\n\ndef thin(image, max_iter=None):\n \"\"\"\n Perform morphological thinning of a binary image.\n\n Parameters\n ----------\n image : binary (M, N) ndarray\n The image to be thinned.\n\n max_iter : int, number of iterations, optional\n Regardless of the value of this parameter, the thinned image\n is returned immediately if an iteration produces no change.\n If this parameter is specified it thus sets an upper bound on\n the number of iterations performed.\n\n Returns\n -------\n out : ndarray of bool\n Thinned image.\n\n See also\n --------\n skeletonize, medial_axis\n\n Notes\n -----\n This algorithm [1]_ works by making multiple passes over the image,\n removing pixels matching a set of criteria designed to thin\n connected regions while preserving eight-connected components and\n 2 x 2 squares [2]_. In each of the two sub-iterations the algorithm\n correlates the intermediate skeleton image with a neighborhood mask,\n then looks up each neighborhood in a lookup table indicating whether\n the central pixel should be deleted in that sub-iteration.\n\n References\n ----------\n .. [1] Z. Guo and R. W. Hall, \"Parallel thinning with\n two-subiteration algorithms,\" Comm. ACM, vol. 32, no. 3,\n pp. 359-373, 1989. :DOI:`10.1145/62065.62074`\n .. [2] Lam, L., Seong-Whan Lee, and Ching Y. Suen, \"Thinning\n Methodologies-A Comprehensive Survey,\" IEEE Transactions on\n Pattern Analysis and Machine Intelligence, Vol 14, No. 9,\n p. 879, 1992. :DOI:`10.1109/34.161346`\n\n Examples\n --------\n >>> square = np.zeros((7, 7), dtype=np.uint8)\n >>> square[1:-1, 2:-2] = 1\n >>> square[0, 1] = 1\n >>> square\n array([[0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> skel = thin(square)\n >>> skel.astype(np.uint8)\n array([[0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n \"\"\"\n # check that image is 2d\n check_nD(image, 2)\n\n # convert image to uint8 with values in {0, 1}\n skel = np.asanyarray(image, dtype=bool).astype(np.uint8)\n\n # neighborhood mask\n mask = np.array([[ 8, 4, 2],\n [16, 0, 1],\n [32, 64, 128]], dtype=np.uint8)\n\n # iterate until convergence, up to the iteration limit\n max_iter = max_iter or np.inf\n n_iter = 0\n n_pts_old, n_pts_new = np.inf, np.sum(skel)\n while n_pts_old != n_pts_new and n_iter < max_iter:\n n_pts_old = n_pts_new\n\n # perform the two \"subiterations\" described in the paper\n for lut in [G123_LUT, G123P_LUT]:\n # correlate image with neighborhood mask\n N = ndi.correlate(skel, mask, mode='constant')\n # take deletion decision from this subiteration's LUT\n D = np.take(lut, N)\n # perform deletion\n skel[D] = 0\n\n n_pts_new = np.sum(skel) # count points after thinning\n n_iter += 1\n\n return skel.astype(np.bool)\n\n\n# --------- Skeletonization by medial axis transform --------\n\n_eight_connect = ndi.generate_binary_structure(2, 2)\n\n\ndef medial_axis(image, mask=None, return_distance=False):\n \"\"\"\n Compute the medial axis transform of a binary image\n\n Parameters\n ----------\n image : binary ndarray, shape (M, N)\n The image of the shape to be skeletonized.\n mask : binary ndarray, shape (M, N), optional\n If a mask is given, only those elements in `image` with a true\n value in `mask` are used for computing the medial axis.\n return_distance : bool, optional\n If true, the distance transform is returned as well as the skeleton.\n\n Returns\n -------\n out : ndarray of bools\n Medial axis transform of the image\n dist : ndarray of ints, optional\n Distance transform of the image (only returned if `return_distance`\n is True)\n\n See also\n --------\n skeletonize\n\n Notes\n -----\n This algorithm computes the medial axis transform of an image\n as the ridges of its distance transform.\n\n The different steps of the algorithm are as follows\n * A lookup table is used, that assigns 0 or 1 to each configuration of\n the 3x3 binary square, whether the central pixel should be removed\n or kept. We want a point to be removed if it has more than one neighbor\n and if removing it does not change the number of connected components.\n\n * The distance transform to the background is computed, as well as\n the cornerness of the pixel.\n\n * The foreground (value of 1) points are ordered by\n the distance transform, then the cornerness.\n\n * A cython function is called to reduce the image to its skeleton. It\n processes pixels in the order determined at the previous step, and\n removes or maintains a pixel according to the lookup table. Because\n of the ordering, it is possible to process all pixels in only one\n pass.\n\n Examples\n --------\n >>> square = np.zeros((7, 7), dtype=np.uint8)\n >>> square[1:-1, 2:-2] = 1\n >>> square\n array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n >>> medial_axis(square).astype(np.uint8)\n array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n\n \"\"\"\n global _eight_connect\n if mask is None:\n masked_image = image.astype(np.bool)\n else:\n masked_image = image.astype(bool).copy()\n masked_image[~mask] = False\n #\n # Build lookup table - three conditions\n # 1. Keep only positive pixels (center_is_foreground array).\n # AND\n # 2. Keep if removing the pixel results in a different connectivity\n # (if the number of connected components is different with and\n # without the central pixel)\n # OR\n # 3. Keep if # pixels in neighbourhood is 2 or less\n # Note that table is independent of image\n center_is_foreground = (np.arange(512) & 2**4).astype(bool)\n table = (center_is_foreground # condition 1.\n &\n (np.array([ndi.label(_pattern_of(index), _eight_connect)[1] !=\n ndi.label(_pattern_of(index & ~ 2**4),\n _eight_connect)[1]\n for index in range(512)]) # condition 2\n |\n np.array([np.sum(_pattern_of(index)) < 3 for index in range(512)]))\n # condition 3\n )\n\n # Build distance transform\n distance = ndi.distance_transform_edt(masked_image)\n if return_distance:\n store_distance = distance.copy()\n\n # Corners\n # The processing order along the edge is critical to the shape of the\n # resulting skeleton: if you process a corner first, that corner will\n # be eroded and the skeleton will miss the arm from that corner. Pixels\n # with fewer neighbors are more \"cornery\" and should be processed last.\n # We use a cornerness_table lookup table where the score of a\n # configuration is the number of background (0-value) pixels in the\n # 3x3 neighbourhood\n cornerness_table = np.array([9 - np.sum(_pattern_of(index))\n for index in range(512)])\n corner_score = _table_lookup(masked_image, cornerness_table)\n\n # Define arrays for inner loop\n i, j = np.mgrid[0:image.shape[0], 0:image.shape[1]]\n result = masked_image.copy()\n distance = distance[result]\n i = np.ascontiguousarray(i[result], dtype=np.intp)\n j = np.ascontiguousarray(j[result], dtype=np.intp)\n result = np.ascontiguousarray(result, np.uint8)\n\n # Determine the order in which pixels are processed.\n # We use a random # for tiebreaking. Assign each pixel in the image a\n # predictable, random # so that masking doesn't affect arbitrary choices\n # of skeletons\n #\n generator = np.random.RandomState(0)\n tiebreaker = generator.permutation(np.arange(masked_image.sum()))\n order = np.lexsort((tiebreaker,\n corner_score[masked_image],\n distance))\n order = np.ascontiguousarray(order, dtype=np.int32)\n\n table = np.ascontiguousarray(table, dtype=np.uint8)\n # Remove pixels not belonging to the medial axis\n _skeletonize_loop(result, i, j, order, table)\n\n result = result.astype(bool)\n if mask is not None:\n result[~mask] = image[~mask]\n if return_distance:\n return result, store_distance\n else:\n return result\n\n\ndef _pattern_of(index):\n \"\"\"\n Return the pattern represented by an index value\n Byte decomposition of index\n \"\"\"\n return np.array([[index & 2**0, index & 2**1, index & 2**2],\n [index & 2**3, index & 2**4, index & 2**5],\n [index & 2**6, index & 2**7, index & 2**8]], bool)\n\n\ndef _table_lookup(image, table):\n \"\"\"\n Perform a morphological transform on an image, directed by its\n neighbors\n\n Parameters\n ----------\n image : ndarray\n A binary image\n table : ndarray\n A 512-element table giving the transform of each pixel given\n the values of that pixel and its 8-connected neighbors.\n border_value : bool\n The value of pixels beyond the border of the image.\n\n Returns\n -------\n result : ndarray of same shape as `image`\n Transformed image\n\n Notes\n -----\n The pixels are numbered like this::\n\n\n 0 1 2\n 3 4 5\n 6 7 8\n\n The index at a pixel is the sum of 2**<pixel-number> for pixels\n that evaluate to true.\n \"\"\"\n #\n # We accumulate into the indexer to get the index into the table\n # at each point in the image\n #\n if image.shape[0] < 3 or image.shape[1] < 3:\n image = image.astype(bool)\n indexer = np.zeros(image.shape, int)\n indexer[1:, 1:] += image[:-1, :-1] * 2**0\n indexer[1:, :] += image[:-1, :] * 2**1\n indexer[1:, :-1] += image[:-1, 1:] * 2**2\n\n indexer[:, 1:] += image[:, :-1] * 2**3\n indexer[:, :] += image[:, :] * 2**4\n indexer[:, :-1] += image[:, 1:] * 2**5\n\n indexer[:-1, 1:] += image[1:, :-1] * 2**6\n indexer[:-1, :] += image[1:, :] * 2**7\n indexer[:-1, :-1] += image[1:, 1:] * 2**8\n else:\n indexer = _table_lookup_index(np.ascontiguousarray(image, np.uint8))\n image = table[indexer]\n return image\n\n\ndef skeletonize_3d(image):\n \"\"\"Compute the skeleton of a binary image.\n\n Thinning is used to reduce each connected component in a binary image\n to a single-pixel wide skeleton.\n\n Parameters\n ----------\n image : ndarray, 2D or 3D\n A binary image containing the objects to be skeletonized. Zeros\n represent background, nonzero values are foreground.\n\n Returns\n -------\n skeleton : ndarray\n The thinned image.\n\n See also\n --------\n skeletonize, medial_axis\n\n Notes\n -----\n The method of [Lee94]_ uses an octree data structure to examine a 3x3x3\n neighborhood of a pixel. The algorithm proceeds by iteratively sweeping\n over the image, and removing pixels at each iteration until the image\n stops changing. Each iteration consists of two steps: first, a list of\n candidates for removal is assembled; then pixels from this list are\n rechecked sequentially, to better preserve connectivity of the image.\n\n The algorithm this function implements is different from the algorithms\n used by either `skeletonize` or `medial_axis`, thus for 2D images the\n results produced by this function are generally different.\n\n References\n ----------\n .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models\n via 3-D medial surface/axis thinning algorithms.\n Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.\n\n \"\"\"\n # make sure the image is 3D or 2D\n if image.ndim < 2 or image.ndim > 3:\n raise ValueError(\"skeletonize_3d can only handle 2D or 3D images; \"\n \"got image.ndim = %s instead.\" % image.ndim)\n image = np.ascontiguousarray(image)\n image = img_as_ubyte(image, force_copy=False)\n\n # make an in image 3D and pad it w/ zeros to simplify dealing w/ boundaries\n # NB: careful here to not clobber the original *and* minimize copying\n image_o = image\n if image.ndim == 2:\n image_o = image[np.newaxis, ...]\n image_o = np.pad(image_o, pad_width=1, mode='constant')\n\n # normalize to binary\n maxval = image_o.max()\n image_o[image_o != 0] = 1\n\n # do the computation\n image_o = np.asarray(_compute_thin_image(image_o))\n\n # crop it back and restore the original intensity range\n image_o = crop(image_o, crop_width=1)\n if image.ndim == 2:\n image_o = image_o[0]\n image_o *= maxval\n\n return image_o\n", "from itertools import combinations_with_replacement\n\nimport numpy as np\nfrom scipy import ndimage as ndi\nfrom scipy import stats\nfrom scipy import spatial\n\nfrom ..util import img_as_float\nfrom .peak import peak_local_max\nfrom .util import _prepare_grayscale_input_2D\nfrom .corner_cy import _corner_fast\nfrom ._hessian_det_appx import _hessian_matrix_det\nfrom ..transform import integral_image\nfrom .._shared.utils import safe_as_int\nfrom .corner_cy import _corner_moravec, _corner_orientations\nfrom warnings import warn\n\n\ndef _compute_derivatives(image, mode='constant', cval=0):\n \"\"\"Compute derivatives in x and y direction using the Sobel operator.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional\n How to handle values outside the image borders.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n\n Returns\n -------\n imx : ndarray\n Derivative in x-direction.\n imy : ndarray\n Derivative in y-direction.\n\n \"\"\"\n\n imy = ndi.sobel(image, axis=0, mode=mode, cval=cval)\n imx = ndi.sobel(image, axis=1, mode=mode, cval=cval)\n\n return imx, imy\n\n\ndef structure_tensor(image, sigma=1, mode='constant', cval=0):\n \"\"\"Compute structure tensor using sum of squared differences.\n\n The structure tensor A is defined as::\n\n A = [Axx Axy]\n [Axy Ayy]\n\n which is approximated by the weighted sum of squared differences in a local\n window around each pixel in the image.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, which is used as a\n weighting function for the local summation of squared differences.\n mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional\n How to handle values outside the image borders.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n\n Returns\n -------\n Axx : ndarray\n Element of the structure tensor for each pixel in the input image.\n Axy : ndarray\n Element of the structure tensor for each pixel in the input image.\n Ayy : ndarray\n Element of the structure tensor for each pixel in the input image.\n\n Examples\n --------\n >>> from skimage.feature import structure_tensor\n >>> square = np.zeros((5, 5))\n >>> square[2, 2] = 1\n >>> Axx, Axy, Ayy = structure_tensor(square, sigma=0.1)\n >>> Axx\n array([[0., 0., 0., 0., 0.],\n [0., 1., 0., 1., 0.],\n [0., 4., 0., 4., 0.],\n [0., 1., 0., 1., 0.],\n [0., 0., 0., 0., 0.]])\n\n \"\"\"\n\n image = _prepare_grayscale_input_2D(image)\n\n imx, imy = _compute_derivatives(image, mode=mode, cval=cval)\n\n # structure tensore\n Axx = ndi.gaussian_filter(imx * imx, sigma, mode=mode, cval=cval)\n Axy = ndi.gaussian_filter(imx * imy, sigma, mode=mode, cval=cval)\n Ayy = ndi.gaussian_filter(imy * imy, sigma, mode=mode, cval=cval)\n\n return Axx, Axy, Ayy\n\n\ndef hessian_matrix(image, sigma=1, mode='constant', cval=0, order='rc'):\n \"\"\"Compute Hessian matrix.\n\n The Hessian matrix is defined as::\n\n H = [Hrr Hrc]\n [Hrc Hcc]\n\n which is computed by convolving the image with the second derivatives\n of the Gaussian kernel in the respective r- and c-directions.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n sigma : float\n Standard deviation used for the Gaussian kernel, which is used as\n weighting function for the auto-correlation matrix.\n mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional\n How to handle values outside the image borders.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n order : {'rc', 'xy'}, optional\n This parameter allows for the use of reverse or forward order of\n the image axes in gradient computation. 'rc' indicates the use of\n the first axis initially (Hrr, Hrc, Hcc), whilst 'xy' indicates the\n usage of the last axis initially (Hxx, Hxy, Hyy)\n\n Returns\n -------\n Hrr : ndarray\n Element of the Hessian matrix for each pixel in the input image.\n Hrc : ndarray\n Element of the Hessian matrix for each pixel in the input image.\n Hcc : ndarray\n Element of the Hessian matrix for each pixel in the input image.\n\n Examples\n --------\n >>> from skimage.feature import hessian_matrix\n >>> square = np.zeros((5, 5))\n >>> square[2, 2] = 4\n >>> Hrr, Hrc, Hcc = hessian_matrix(square, sigma=0.1, order='rc')\n >>> Hrc\n array([[ 0., 0., 0., 0., 0.],\n [ 0., 1., 0., -1., 0.],\n [ 0., 0., 0., 0., 0.],\n [ 0., -1., 0., 1., 0.],\n [ 0., 0., 0., 0., 0.]])\n \"\"\"\n\n image = img_as_float(image)\n\n gaussian_filtered = ndi.gaussian_filter(image, sigma=sigma,\n mode=mode, cval=cval)\n\n gradients = np.gradient(gaussian_filtered)\n axes = range(image.ndim)\n\n if order == 'rc':\n axes = reversed(axes)\n\n H_elems = [np.gradient(gradients[ax0], axis=ax1)\n for ax0, ax1 in combinations_with_replacement(axes, 2)]\n\n return H_elems\n\n\ndef _hessian_matrix_image(H_elems):\n \"\"\"Convert the upper-diagonal elements of the Hessian matrix to a matrix.\n\n Parameters\n ----------\n H_elems : list of array\n The upper-diagonal elements of the Hessian matrix, as returned by\n `hessian_matrix`.\n\n Returns\n -------\n hessian_image : array\n An array of shape ``(M, N[, ...], image.ndim, image.ndim)``,\n containing the Hessian matrix corresponding to each coordinate.\n \"\"\"\n image = H_elems[0]\n hessian_image = np.zeros(image.shape + (image.ndim, image.ndim))\n for idx, (row, col) in \\\n enumerate(combinations_with_replacement(range(image.ndim), 2)):\n hessian_image[..., row, col] = H_elems[idx]\n hessian_image[..., col, row] = H_elems[idx]\n return hessian_image\n\n\ndef hessian_matrix_det(image, sigma=1, approximate=True):\n \"\"\"Compute the approximate Hessian Determinant over an image.\n\n The 2D approximate method uses box filters over integral images to\n compute the approximate Hessian Determinant, as described in [1]_.\n\n Parameters\n ----------\n image : array\n The image over which to compute Hessian Determinant.\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, used for the Hessian\n matrix.\n approximate : bool, optional\n If ``True`` and the image is 2D, use a much faster approximate\n computation. This argument has no effect on 3D and higher images.\n\n Returns\n -------\n out : array\n The array of the Determinant of Hessians.\n\n References\n ----------\n .. [1] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool,\n \"SURF: Speeded Up Robust Features\"\n ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf\n\n Notes\n -----\n For 2D images when ``approximate=True``, the running time of this method\n only depends on size of the image. It is independent of `sigma` as one\n would expect. The downside is that the result for `sigma` less than `3`\n is not accurate, i.e., not similar to the result obtained if someone\n computed the Hessian and took its determinant.\n \"\"\"\n image = img_as_float(image)\n if image.ndim == 2 and approximate:\n integral = integral_image(image)\n return np.array(_hessian_matrix_det(integral, sigma))\n else: # slower brute-force implementation for nD images\n hessian_mat_array = _hessian_matrix_image(hessian_matrix(image, sigma))\n return np.linalg.det(hessian_mat_array)\n\n\ndef _image_orthogonal_matrix22_eigvals(M00, M01, M11):\n l1 = (M00 + M11) / 2 + np.sqrt(4 * M01 ** 2 + (M00 - M11) ** 2) / 2\n l2 = (M00 + M11) / 2 - np.sqrt(4 * M01 ** 2 + (M00 - M11) ** 2) / 2\n return l1, l2\n\n\ndef structure_tensor_eigvals(Axx, Axy, Ayy):\n \"\"\"Compute Eigen values of structure tensor.\n\n Parameters\n ----------\n Axx : ndarray\n Element of the structure tensor for each pixel in the input image.\n Axy : ndarray\n Element of the structure tensor for each pixel in the input image.\n Ayy : ndarray\n Element of the structure tensor for each pixel in the input image.\n\n Returns\n -------\n l1 : ndarray\n Larger eigen value for each input matrix.\n l2 : ndarray\n Smaller eigen value for each input matrix.\n\n Examples\n --------\n >>> from skimage.feature import structure_tensor, structure_tensor_eigvals\n >>> square = np.zeros((5, 5))\n >>> square[2, 2] = 1\n >>> Axx, Axy, Ayy = structure_tensor(square, sigma=0.1)\n >>> structure_tensor_eigvals(Axx, Axy, Ayy)[0]\n array([[0., 0., 0., 0., 0.],\n [0., 2., 4., 2., 0.],\n [0., 4., 0., 4., 0.],\n [0., 2., 4., 2., 0.],\n [0., 0., 0., 0., 0.]])\n\n \"\"\"\n\n return _image_orthogonal_matrix22_eigvals(Axx, Axy, Ayy)\n\n\ndef hessian_matrix_eigvals(H_elems):\n \"\"\"Compute Eigenvalues of Hessian matrix.\n\n Parameters\n ----------\n H_elems : list of ndarray\n The upper-diagonal elements of the Hessian matrix, as returned\n by `hessian_matrix`.\n\n Returns\n -------\n eigs : ndarray\n The eigenvalues of the Hessian matrix, in decreasing order. The\n eigenvalues are the leading dimension. That is, ``eigs[i, j, k]``\n contains the ith-largest eigenvalue at position (j, k).\n\n Examples\n --------\n >>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals\n >>> square = np.zeros((5, 5))\n >>> square[2, 2] = 4\n >>> H_elems = hessian_matrix(square, sigma=0.1, order='rc')\n >>> hessian_matrix_eigvals(H_elems)[0]\n array([[ 0., 0., 2., 0., 0.],\n [ 0., 1., 0., 1., 0.],\n [ 2., 0., -2., 0., 2.],\n [ 0., 1., 0., 1., 0.],\n [ 0., 0., 2., 0., 0.]])\n \"\"\"\n if len(H_elems) == 3: # Use fast Cython code for 2D\n eigvals = np.array(_image_orthogonal_matrix22_eigvals(*H_elems))\n else:\n matrices = _hessian_matrix_image(H_elems)\n # eigvalsh returns eigenvalues in increasing order. We want decreasing\n eigvals = np.linalg.eigvalsh(matrices)[..., ::-1]\n leading_axes = tuple(range(eigvals.ndim - 1))\n eigvals = np.transpose(eigvals, (eigvals.ndim - 1,) + leading_axes)\n return eigvals\n\n\ndef shape_index(image, sigma=1, mode='constant', cval=0):\n \"\"\"Compute the shape index.\n\n The shape index, as defined by Koenderink & van Doorn [1]_, is a\n single valued measure of local curvature, assuming the image as a 3D plane\n with intensities representing heights.\n\n It is derived from the eigen values of the Hessian, and its\n value ranges from -1 to 1 (and is undefined (=NaN) in *flat* regions),\n with following ranges representing following shapes:\n\n .. table:: Ranges of the shape index and corresponding shapes.\n\n =================== =============\n Interval (s in ...) Shape\n =================== =============\n [ -1, -7/8) Spherical cup\n [-7/8, -5/8) Through\n [-5/8, -3/8) Rut\n [-3/8, -1/8) Saddle rut\n [-1/8, +1/8) Saddle\n [+1/8, +3/8) Saddle ridge\n [+3/8, +5/8) Ridge\n [+5/8, +7/8) Dome\n [+7/8, +1] Spherical cap\n =================== =============\n\n Parameters\n ----------\n image : ndarray\n Input image.\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, which is used for\n smoothing the input data before Hessian eigen value calculation.\n mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional\n How to handle values outside the image borders\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n\n Returns\n -------\n s : ndarray\n Shape index\n\n References\n ----------\n .. [1] Koenderink, J. J. & van Doorn, A. J.,\n \"Surface shape and curvature scales\",\n Image and Vision Computing, 1992, 10, 557-564.\n :DOI:`10.1016/0262-8856(92)90076-F`\n\n Examples\n --------\n >>> from skimage.feature import shape_index\n >>> square = np.zeros((5, 5))\n >>> square[2, 2] = 4\n >>> s = shape_index(square, sigma=0.1)\n >>> s\n array([[ nan, nan, -0.5, nan, nan],\n [ nan, -0. , nan, -0. , nan],\n [-0.5, nan, -1. , nan, -0.5],\n [ nan, -0. , nan, -0. , nan],\n [ nan, nan, -0.5, nan, nan]])\n \"\"\"\n\n H = hessian_matrix(image, sigma=sigma, mode=mode, cval=cval, order='rc')\n l1, l2 = hessian_matrix_eigvals(H)\n\n return (2.0 / np.pi) * np.arctan((l2 + l1) / (l2 - l1))\n\n\ndef corner_kitchen_rosenfeld(image, mode='constant', cval=0):\n \"\"\"Compute Kitchen and Rosenfeld corner measure response image.\n\n The corner measure is calculated as follows::\n\n (imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy)\n / (imx**2 + imy**2)\n\n Where imx and imy are the first and imxx, imxy, imyy the second\n derivatives.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional\n How to handle values outside the image borders.\n cval : float, optional\n Used in conjunction with mode 'constant', the value outside\n the image boundaries.\n\n Returns\n -------\n response : ndarray\n Kitchen and Rosenfeld response image.\n\n References\n ----------\n .. [1] Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection.\n Pattern recognition letters, 1(2), 95-102.\n :DOI:`10.1016/0167-8655(82)90020-4`\n \"\"\"\n\n imx, imy = _compute_derivatives(image, mode=mode, cval=cval)\n imxx, imxy = _compute_derivatives(imx, mode=mode, cval=cval)\n imyx, imyy = _compute_derivatives(imy, mode=mode, cval=cval)\n\n numerator = (imxx * imy ** 2 + imyy * imx ** 2 - 2 * imxy * imx * imy)\n denominator = (imx ** 2 + imy ** 2)\n\n response = np.zeros_like(image, dtype=np.double)\n\n mask = denominator != 0\n response[mask] = numerator[mask] / denominator[mask]\n\n return response\n\n\ndef corner_harris(image, method='k', k=0.05, eps=1e-6, sigma=1):\n \"\"\"Compute Harris corner measure response image.\n\n This corner detector uses information from the auto-correlation matrix A::\n\n A = [(imx**2) (imx*imy)] = [Axx Axy]\n [(imx*imy) (imy**2)] [Axy Ayy]\n\n Where imx and imy are first derivatives, averaged with a gaussian filter.\n The corner measure is then defined as::\n\n det(A) - k * trace(A)**2\n\n or::\n\n 2 * det(A) / (trace(A) + eps)\n\n Parameters\n ----------\n image : ndarray\n Input image.\n method : {'k', 'eps'}, optional\n Method to compute the response image from the auto-correlation matrix.\n k : float, optional\n Sensitivity factor to separate corners from edges, typically in range\n `[0, 0.2]`. Small values of k result in detection of sharp corners.\n eps : float, optional\n Normalisation factor (Noble's corner measure).\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, which is used as\n weighting function for the auto-correlation matrix.\n\n Returns\n -------\n response : ndarray\n Harris response image.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Corner_detection\n\n Examples\n --------\n >>> from skimage.feature import corner_harris, corner_peaks\n >>> square = np.zeros([10, 10])\n >>> square[2:8, 2:8] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n >>> corner_peaks(corner_harris(square), min_distance=1, threshold_rel=0)\n array([[2, 2],\n [2, 7],\n [7, 2],\n [7, 7]])\n\n \"\"\"\n\n Axx, Axy, Ayy = structure_tensor(image, sigma)\n\n # determinant\n detA = Axx * Ayy - Axy ** 2\n # trace\n traceA = Axx + Ayy\n\n if method == 'k':\n response = detA - k * traceA ** 2\n else:\n response = 2 * detA / (traceA + eps)\n\n return response\n\n\ndef corner_shi_tomasi(image, sigma=1):\n \"\"\"Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image.\n\n This corner detector uses information from the auto-correlation matrix A::\n\n A = [(imx**2) (imx*imy)] = [Axx Axy]\n [(imx*imy) (imy**2)] [Axy Ayy]\n\n Where imx and imy are first derivatives, averaged with a gaussian filter.\n The corner measure is then defined as the smaller eigenvalue of A::\n\n ((Axx + Ayy) - sqrt((Axx - Ayy)**2 + 4 * Axy**2)) / 2\n\n Parameters\n ----------\n image : ndarray\n Input image.\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, which is used as\n weighting function for the auto-correlation matrix.\n\n Returns\n -------\n response : ndarray\n Shi-Tomasi response image.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Corner_detection\n\n Examples\n --------\n >>> from skimage.feature import corner_shi_tomasi, corner_peaks\n >>> square = np.zeros([10, 10])\n >>> square[2:8, 2:8] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n >>> corner_peaks(corner_shi_tomasi(square), min_distance=1,\n ... threshold_rel=0)\n array([[2, 2],\n [2, 7],\n [7, 2],\n [7, 7]])\n\n \"\"\"\n\n Axx, Axy, Ayy = structure_tensor(image, sigma)\n\n # minimum eigenvalue of A\n response = ((Axx + Ayy) - np.sqrt((Axx - Ayy) ** 2 + 4 * Axy ** 2)) / 2\n\n return response\n\n\ndef corner_foerstner(image, sigma=1):\n \"\"\"Compute Foerstner corner measure response image.\n\n This corner detector uses information from the auto-correlation matrix A::\n\n A = [(imx**2) (imx*imy)] = [Axx Axy]\n [(imx*imy) (imy**2)] [Axy Ayy]\n\n Where imx and imy are first derivatives, averaged with a gaussian filter.\n The corner measure is then defined as::\n\n w = det(A) / trace(A) (size of error ellipse)\n q = 4 * det(A) / trace(A)**2 (roundness of error ellipse)\n\n Parameters\n ----------\n image : ndarray\n Input image.\n sigma : float, optional\n Standard deviation used for the Gaussian kernel, which is used as\n weighting function for the auto-correlation matrix.\n\n Returns\n -------\n w : ndarray\n Error ellipse sizes.\n q : ndarray\n Roundness of error ellipse.\n\n References\n ----------\n .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for detection and\n precise location of distinct points, corners and centres of circular\n features. In Proc. ISPRS intercommission conference on fast processing of\n photogrammetric data (pp. 281-305).\n https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf\n .. [2] https://en.wikipedia.org/wiki/Corner_detection\n\n Examples\n --------\n >>> from skimage.feature import corner_foerstner, corner_peaks\n >>> square = np.zeros([10, 10])\n >>> square[2:8, 2:8] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n >>> w, q = corner_foerstner(square)\n >>> accuracy_thresh = 0.5\n >>> roundness_thresh = 0.3\n >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w\n >>> corner_peaks(foerstner, min_distance=1, threshold_rel=0)\n array([[2, 2],\n [2, 7],\n [7, 2],\n [7, 7]])\n\n \"\"\"\n\n Axx, Axy, Ayy = structure_tensor(image, sigma)\n\n # determinant\n detA = Axx * Ayy - Axy ** 2\n # trace\n traceA = Axx + Ayy\n\n w = np.zeros_like(image, dtype=np.double)\n q = np.zeros_like(image, dtype=np.double)\n\n mask = traceA != 0\n\n w[mask] = detA[mask] / traceA[mask]\n q[mask] = 4 * detA[mask] / traceA[mask] ** 2\n\n return w, q\n\n\ndef corner_fast(image, n=12, threshold=0.15):\n \"\"\"Extract FAST corners for a given image.\n\n Parameters\n ----------\n image : 2D ndarray\n Input image.\n n : int, optional\n Minimum number of consecutive pixels out of 16 pixels on the circle\n that should all be either brighter or darker w.r.t testpixel.\n A point c on the circle is darker w.r.t test pixel p if\n `Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also\n stands for the n in `FAST-n` corner detector.\n threshold : float, optional\n Threshold used in deciding whether the pixels on the circle are\n brighter, darker or similar w.r.t. the test pixel. Decrease the\n threshold when more corners are desired and vice-versa.\n\n Returns\n -------\n response : ndarray\n FAST corner response image.\n\n References\n ----------\n .. [1] Rosten, E., & Drummond, T. (2006, May). Machine learning for high-speed\n corner detection. In European conference on computer vision (pp. 430-443).\n Springer, Berlin, Heidelberg.\n :DOI:`10.1007/11744023_34`\n http://www.edwardrosten.com/work/rosten_2006_machine.pdf\n .. [2] Wikipedia, \"Features from accelerated segment test\",\n https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test\n\n Examples\n --------\n >>> from skimage.feature import corner_fast, corner_peaks\n >>> square = np.zeros((12, 12))\n >>> square[3:9, 3:9] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n >>> corner_peaks(corner_fast(square, 9), min_distance=1, threshold_rel=0)\n array([[3, 3],\n [3, 8],\n [8, 3],\n [8, 8]])\n\n \"\"\"\n image = _prepare_grayscale_input_2D(image)\n\n image = np.ascontiguousarray(image)\n response = _corner_fast(image, n, threshold)\n return response\n\n\ndef corner_subpix(image, corners, window_size=11, alpha=0.99):\n \"\"\"Determine subpixel position of corners.\n\n A statistical test decides whether the corner is defined as the\n intersection of two edges or a single peak. Depending on the classification\n result, the subpixel corner location is determined based on the local\n covariance of the grey-values. If the significance level for either\n statistical test is not sufficient, the corner cannot be classified, and\n the output subpixel position is set to NaN.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n corners : (N, 2) ndarray\n Corner coordinates `(row, col)`.\n window_size : int, optional\n Search window size for subpixel estimation.\n alpha : float, optional\n Significance level for corner classification.\n\n Returns\n -------\n positions : (N, 2) ndarray\n Subpixel corner positions. NaN for \"not classified\" corners.\n\n References\n ----------\n .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for detection and\n precise location of distinct points, corners and centres of circular\n features. In Proc. ISPRS intercommission conference on fast processing of\n photogrammetric data (pp. 281-305).\n https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf\n .. [2] https://en.wikipedia.org/wiki/Corner_detection\n\n Examples\n --------\n >>> from skimage.feature import corner_harris, corner_peaks, corner_subpix\n >>> img = np.zeros((10, 10))\n >>> img[:5, :5] = 1\n >>> img[5:, 5:] = 1\n >>> img.astype(int)\n array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]])\n >>> coords = corner_peaks(corner_harris(img), min_distance=2,\n ... threshold_rel=0)\n >>> coords_subpix = corner_subpix(img, coords, window_size=7)\n >>> coords_subpix\n array([[4.5, 4.5]])\n\n \"\"\"\n\n # window extent in one direction\n wext = (window_size - 1) // 2\n\n image = np.pad(image, pad_width=wext, mode='constant', constant_values=0)\n\n # add pad width, make sure to not modify the input values in-place\n corners = safe_as_int(corners + wext)\n\n # normal equation arrays\n N_dot = np.zeros((2, 2), dtype=np.double)\n N_edge = np.zeros((2, 2), dtype=np.double)\n b_dot = np.zeros((2, ), dtype=np.double)\n b_edge = np.zeros((2, ), dtype=np.double)\n\n # critical statistical test values\n redundancy = window_size ** 2 - 2\n t_crit_dot = stats.f.isf(1 - alpha, redundancy, redundancy)\n t_crit_edge = stats.f.isf(alpha, redundancy, redundancy)\n\n # coordinates of pixels within window\n y, x = np.mgrid[- wext:wext + 1, - wext:wext + 1]\n\n corners_subpix = np.zeros_like(corners, dtype=np.double)\n\n for i, (y0, x0) in enumerate(corners):\n\n # crop window around corner + border for sobel operator\n miny = y0 - wext - 1\n maxy = y0 + wext + 2\n minx = x0 - wext - 1\n maxx = x0 + wext + 2\n window = image[miny:maxy, minx:maxx]\n\n winx, winy = _compute_derivatives(window, mode='constant', cval=0)\n\n # compute gradient suares and remove border\n winx_winx = (winx * winx)[1:-1, 1:-1]\n winx_winy = (winx * winy)[1:-1, 1:-1]\n winy_winy = (winy * winy)[1:-1, 1:-1]\n\n # sum of squared differences (mean instead of gaussian filter)\n Axx = np.sum(winx_winx)\n Axy = np.sum(winx_winy)\n Ayy = np.sum(winy_winy)\n\n # sum of squared differences weighted with coordinates\n # (mean instead of gaussian filter)\n bxx_x = np.sum(winx_winx * x)\n bxx_y = np.sum(winx_winx * y)\n bxy_x = np.sum(winx_winy * x)\n bxy_y = np.sum(winx_winy * y)\n byy_x = np.sum(winy_winy * x)\n byy_y = np.sum(winy_winy * y)\n\n # normal equations for subpixel position\n N_dot[0, 0] = Axx\n N_dot[0, 1] = N_dot[1, 0] = - Axy\n N_dot[1, 1] = Ayy\n\n N_edge[0, 0] = Ayy\n N_edge[0, 1] = N_edge[1, 0] = Axy\n N_edge[1, 1] = Axx\n\n b_dot[:] = bxx_y - bxy_x, byy_x - bxy_y\n b_edge[:] = byy_y + bxy_x, bxx_x + bxy_y\n\n # estimated positions\n try:\n est_dot = np.linalg.solve(N_dot, b_dot)\n est_edge = np.linalg.solve(N_edge, b_edge)\n except np.linalg.LinAlgError:\n # if image is constant the system is singular\n corners_subpix[i, :] = np.nan, np.nan\n continue\n\n # residuals\n ry_dot = y - est_dot[0]\n rx_dot = x - est_dot[1]\n ry_edge = y - est_edge[0]\n rx_edge = x - est_edge[1]\n # squared residuals\n rxx_dot = rx_dot * rx_dot\n rxy_dot = rx_dot * ry_dot\n ryy_dot = ry_dot * ry_dot\n rxx_edge = rx_edge * rx_edge\n rxy_edge = rx_edge * ry_edge\n ryy_edge = ry_edge * ry_edge\n\n # determine corner class (dot or edge)\n # variance for different models\n var_dot = np.sum(winx_winx * ryy_dot - 2 * winx_winy * rxy_dot\n + winy_winy * rxx_dot)\n var_edge = np.sum(winy_winy * ryy_edge + 2 * winx_winy * rxy_edge\n + winx_winx * rxx_edge)\n\n # test value (F-distributed)\n if var_dot < np.spacing(1) and var_edge < np.spacing(1):\n t = np.nan\n elif var_dot == 0:\n t = np.inf\n else:\n t = var_edge / var_dot\n\n # 1 for edge, -1 for dot, 0 for \"not classified\"\n corner_class = int(t < t_crit_edge) - int(t > t_crit_dot)\n\n if corner_class == -1:\n corners_subpix[i, :] = y0 + est_dot[0], x0 + est_dot[1]\n elif corner_class == 0:\n corners_subpix[i, :] = np.nan, np.nan\n elif corner_class == 1:\n corners_subpix[i, :] = y0 + est_edge[0], x0 + est_edge[1]\n\n # subtract pad width\n corners_subpix -= wext\n\n return corners_subpix\n\n\ndef corner_peaks(image, min_distance=1, threshold_abs=None, threshold_rel=None,\n exclude_border=True, indices=True, num_peaks=np.inf,\n footprint=None, labels=None, *, num_peaks_per_label=np.inf,\n p_norm=np.inf):\n \"\"\"Find peaks in corner measure response image.\n\n This differs from `skimage.feature.peak_local_max` in that it suppresses\n multiple connected peaks with the same accumulator value.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n min_distance : int, optional\n The minimal allowed distance separating peaks.\n * : *\n See :py:meth:`skimage.feature.peak_local_max`.\n p_norm : float\n Which Minkowski p-norm to use. Should be in the range [1, inf].\n A finite large p may cause a ValueError if overflow can occur.\n ``inf`` corresponds to the Chebyshev distance and 2 to the\n Euclidean distance.\n\n Returns\n -------\n output : ndarray or ndarray of bools\n\n * If `indices = True` : (row, column, ...) coordinates of peaks.\n * If `indices = False` : Boolean array shaped like `image`, with peaks\n represented by True values.\n\n See also\n --------\n skimage.feature.peak_local_max\n\n Notes\n -----\n The `num_peaks` limit is applied before suppression of\n connected peaks. If you want to limit the number of peaks\n after suppression, you should set `num_peaks=np.inf` and\n post-process the output of this function.\n\n Examples\n --------\n >>> from skimage.feature import peak_local_max\n >>> response = np.zeros((5, 5))\n >>> response[2:4, 2:4] = 1\n >>> response\n array([[0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 1., 1., 0.],\n [0., 0., 1., 1., 0.],\n [0., 0., 0., 0., 0.]])\n >>> peak_local_max(response)\n array([[2, 2],\n [2, 3],\n [3, 2],\n [3, 3]])\n >>> corner_peaks(response, threshold_rel=0)\n array([[2, 2]])\n\n \"\"\"\n if threshold_rel is None:\n threshold_rel = 0.1\n warn(\"Until version 0.16, threshold_rel was set to 0.1 by default. \"\n \"Starting from version 0.16, the default value is set to None. \"\n \"Until version 0.18, a None value corresponds to a threshold \"\n \"value of 0.1. The default behavior will match \"\n \"skimage.feature.peak_local_max. To avoid this warning, set \"\n \"threshold_rel=0.\", category=FutureWarning, stacklevel=2)\n\n if np.isinf(num_peaks):\n num_peaks = None\n\n # Get the coordinates of the detected peaks\n coords = peak_local_max(image, min_distance=min_distance,\n threshold_abs=threshold_abs,\n threshold_rel=threshold_rel,\n exclude_border=exclude_border,\n indices=True, num_peaks=np.inf,\n footprint=footprint, labels=labels,\n num_peaks_per_label=num_peaks_per_label)\n\n if len(coords):\n # Use KDtree to find the peaks that are too close to each other\n tree = spatial.cKDTree(coords)\n\n rejected_peaks_indices = set()\n for idx, point in enumerate(coords):\n if idx not in rejected_peaks_indices:\n candidates = tree.query_ball_point(point, r=min_distance,\n p=p_norm)\n candidates.remove(idx)\n rejected_peaks_indices.update(candidates)\n\n # Remove the peaks that are too close to each other\n coords = np.delete(coords, tuple(rejected_peaks_indices),\n axis=0)[:num_peaks]\n\n if indices:\n return coords\n\n peaks = np.zeros_like(image, dtype=bool)\n peaks[tuple(coords.T)] = True\n\n return peaks\n\n\ndef corner_moravec(image, window_size=1):\n \"\"\"Compute Moravec corner measure response image.\n\n This is one of the simplest corner detectors and is comparatively fast but\n has several limitations (e.g. not rotation invariant).\n\n Parameters\n ----------\n image : ndarray\n Input image.\n window_size : int, optional\n Window size.\n\n Returns\n -------\n response : ndarray\n Moravec response image.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Corner_detection\n\n Examples\n --------\n >>> from skimage.feature import corner_moravec\n >>> square = np.zeros([7, 7])\n >>> square[3, 3] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]])\n >>> corner_moravec(square).astype(int)\n array([[0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 2, 1, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]])\n \"\"\"\n return _corner_moravec(image, window_size)\n\n\ndef corner_orientations(image, corners, mask):\n \"\"\"Compute the orientation of corners.\n\n The orientation of corners is computed using the first order central moment\n i.e. the center of mass approach. The corner orientation is the angle of\n the vector from the corner coordinate to the intensity centroid in the\n local neighborhood around the corner calculated using first order central\n moment.\n\n Parameters\n ----------\n image : 2D array\n Input grayscale image.\n corners : (N, 2) array\n Corner coordinates as ``(row, col)``.\n mask : 2D array\n Mask defining the local neighborhood of the corner used for the\n calculation of the central moment.\n\n Returns\n -------\n orientations : (N, 1) array\n Orientations of corners in the range [-pi, pi].\n\n References\n ----------\n .. [1] Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski\n \"ORB : An efficient alternative to SIFT and SURF\"\n http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf\n .. [2] Paul L. Rosin, \"Measuring Corner Properties\"\n http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf\n\n Examples\n --------\n >>> from skimage.morphology import octagon\n >>> from skimage.feature import (corner_fast, corner_peaks,\n ... corner_orientations)\n >>> square = np.zeros((12, 12))\n >>> square[3:9, 3:9] = 1\n >>> square.astype(int)\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n >>> corners = corner_peaks(corner_fast(square, 9), min_distance=1,\n ... threshold_rel=0)\n >>> corners\n array([[3, 3],\n [3, 8],\n [8, 3],\n [8, 8]])\n >>> orientations = corner_orientations(square, corners, octagon(3, 2))\n >>> np.rad2deg(orientations)\n array([ 45., 135., -45., -135.])\n\n \"\"\"\n image = _prepare_grayscale_input_2D(image)\n return _corner_orientations(image, corners, mask)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utilities for heads and unit tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow.core.framework import summary_pb2\nfrom tensorflow_estimator.python.estimator.head import binary_class_head\nfrom tensorflow_estimator.python.estimator.head import multi_class_head\n\n_DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n\n\ndef binary_or_multi_class_head(n_classes, weight_column, label_vocabulary,\n loss_reduction):\n \"\"\"Creates either binary or multi-class head.\n\n Args:\n n_classes: Number of label classes.\n weight_column: A string or a `NumericColumn` created by\n `tf.feature_column.numeric_column` defining feature column representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example. If it is a string, it is\n used as a key to fetch weight tensor from the `features`. If it is a\n `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then\n weight_column.normalizer_fn is applied on it to get weight tensor.\n label_vocabulary: A list of strings represents possible label values. If\n given, labels must be string type and have any value in\n `label_vocabulary`. If it is not given, that means labels are already\n encoded as integer or float within [0, 1] for `n_classes=2` and encoded as\n integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also there\n will be errors if vocabulary is not provided and labels are string.\n loss_reduction: One of `tf.losses.Reduction` except `NONE`. Defines how to\n reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`.\n\n Returns:\n A `Head` instance.\n \"\"\"\n if n_classes == 2:\n head = binary_class_head.BinaryClassHead(\n weight_column=weight_column,\n label_vocabulary=label_vocabulary,\n loss_reduction=loss_reduction)\n else:\n head = multi_class_head.MultiClassHead(\n n_classes,\n weight_column=weight_column,\n label_vocabulary=label_vocabulary,\n loss_reduction=loss_reduction)\n return head\n\n\ndef _initialize_variables(test_case, scaffold):\n scaffold.finalize()\n test_case.assertIsNone(scaffold.init_feed_dict)\n test_case.assertIsNone(scaffold.init_fn)\n scaffold.init_op.run()\n scaffold.ready_for_local_init_op.eval()\n scaffold.local_init_op.run()\n scaffold.ready_op.eval()\n test_case.assertIsNotNone(scaffold.saver)\n\n\ndef _assert_simple_summaries(test_case,\n expected_summaries,\n summary_str,\n tol=1e-6):\n \"\"\"Assert summary the specified simple values.\n\n Args:\n test_case: test case.\n expected_summaries: Dict of expected tags and simple values.\n summary_str: Serialized `summary_pb2.Summary`.\n tol: Tolerance for relative and absolute.\n \"\"\"\n summary = summary_pb2.Summary()\n summary.ParseFromString(summary_str)\n test_case.assertAllClose(\n expected_summaries, {v.tag: v.simple_value for v in summary.value},\n rtol=tol,\n atol=tol)\n\n\ndef _assert_no_hooks(test_case, spec):\n test_case.assertAllEqual([], spec.training_chief_hooks)\n test_case.assertAllEqual([], spec.training_hooks)\n", "# This file is MACHINE GENERATED! Do not edit.\n# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.\n\"\"\"Inception-ResNet V2 model for Keras.\n\n\nReference paper:\n - [Inception-v4, Inception-ResNet and the Impact of\n Residual Connections on Learning](https://arxiv.org/abs/1602.07261)\n (AAAI 2017)\n\n\"\"\"\n\nfrom __future__ import print_function as _print_function\n\nimport sys as _sys\n\nfrom tensorflow.python.keras.applications.inception_resnet_v2 import InceptionResNetV2\nfrom tensorflow.python.keras.applications.inception_resnet_v2 import decode_predictions\nfrom tensorflow.python.keras.applications.inception_resnet_v2 import preprocess_input\n\ndel _print_function\n\nfrom tensorflow.python.util import module_wrapper as _module_wrapper\n\nif not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):\n _sys.modules[__name__] = _module_wrapper.TFModuleWrapper(\n _sys.modules[__name__], \"keras.applications.inception_resnet_v2\", public_apis=None, deprecation=True,\n has_lite=False)\n", "\"\"\"Python wrappers around TensorFlow ops.\n\nThis file is MACHINE GENERATED! Do not edit.\nOriginal C++ source file: count_ops.cc\n\"\"\"\n\nimport collections\n\nfrom tensorflow.python import pywrap_tfe as pywrap_tfe\nfrom tensorflow.python.eager import context as _context\nfrom tensorflow.python.eager import core as _core\nfrom tensorflow.python.eager import execute as _execute\nfrom tensorflow.python.framework import dtypes as _dtypes\n\nfrom tensorflow.python.framework import op_def_registry as _op_def_registry\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import op_def_library as _op_def_library\nfrom tensorflow.python.util.deprecation import deprecated_endpoints\nfrom tensorflow.python.util import dispatch as _dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n\n_DenseCountSparseOutputOutput = collections.namedtuple(\n \"DenseCountSparseOutput\",\n [\"output_indices\", \"output_values\", \"output_dense_shape\"])\n\n\ndef dense_count_sparse_output(values, weights, binary_output, minlength=-1, maxlength=-1, name=None):\n r\"\"\"Performs sparse-output bin counting for a tf.tensor input.\n\n Counts the number of times each value occurs in the input.\n\n Args:\n values: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Tensor containing data to count.\n weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`.\n A Tensor of the same shape as indices containing per-index weight values. May\n also be the empty tensor if no weights are used.\n binary_output: A `bool`.\n Whether to output the number of occurrences of each value or 1.\n minlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Minimum value to count. Can be set to -1 for no minimum.\n maxlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Maximum value to count. Can be set to -1 for no maximum.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape).\n\n output_indices: A `Tensor` of type `int64`.\n output_values: A `Tensor`. Has the same type as `weights`.\n output_dense_shape: A `Tensor` of type `int64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"DenseCountSparseOutput\", name,\n tld.op_callbacks, values, weights, \"minlength\", minlength,\n \"maxlength\", maxlength, \"binary_output\", binary_output)\n _result = _DenseCountSparseOutputOutput._make(_result)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return dense_count_sparse_output_eager_fallback(\n values, weights, minlength=minlength, maxlength=maxlength,\n binary_output=binary_output, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"DenseCountSparseOutput\", values=values, weights=weights,\n binary_output=binary_output,\n minlength=minlength, maxlength=maxlength,\n name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"minlength\",\n _op._get_attr_int(\"minlength\"), \"maxlength\",\n _op._get_attr_int(\"maxlength\"), \"binary_output\",\n _op._get_attr_bool(\"binary_output\"), \"output_type\",\n _op._get_attr_type(\"output_type\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"DenseCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _DenseCountSparseOutputOutput._make(_result)\n return _result\n\nDenseCountSparseOutput = tf_export(\"raw_ops.DenseCountSparseOutput\")(_ops.to_raw_op(dense_count_sparse_output))\n\n\ndef dense_count_sparse_output_eager_fallback(values, weights, binary_output, minlength, maxlength, name, ctx):\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx)\n _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx)\n _inputs_flat = [values, weights]\n _attrs = (\"T\", _attr_T, \"minlength\", minlength, \"maxlength\", maxlength,\n \"binary_output\", binary_output, \"output_type\", _attr_output_type)\n _result = _execute.execute(b\"DenseCountSparseOutput\", 3,\n inputs=_inputs_flat, attrs=_attrs, ctx=ctx,\n name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"DenseCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _DenseCountSparseOutputOutput._make(_result)\n return _result\n\n_RaggedCountSparseOutputOutput = collections.namedtuple(\n \"RaggedCountSparseOutput\",\n [\"output_indices\", \"output_values\", \"output_dense_shape\"])\n\n\ndef ragged_count_sparse_output(splits, values, weights, binary_output, minlength=-1, maxlength=-1, name=None):\n r\"\"\"Performs sparse-output bin counting for a ragged tensor input.\n\n Counts the number of times each value occurs in the input.\n\n Args:\n splits: A `Tensor` of type `int64`.\n Tensor containing the row splits of the ragged tensor to count.\n values: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Tensor containing values of the sparse tensor to count.\n weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`.\n A Tensor of the same shape as indices containing per-index weight values.\n May also be the empty tensor if no weights are used.\n binary_output: A `bool`.\n Whether to output the number of occurrences of each value or 1.\n minlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Minimum value to count. Can be set to -1 for no minimum.\n maxlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Maximum value to count. Can be set to -1 for no maximum.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape).\n\n output_indices: A `Tensor` of type `int64`.\n output_values: A `Tensor`. Has the same type as `weights`.\n output_dense_shape: A `Tensor` of type `int64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"RaggedCountSparseOutput\",\n name, tld.op_callbacks, splits, values, weights, \"minlength\",\n minlength, \"maxlength\", maxlength, \"binary_output\", binary_output)\n _result = _RaggedCountSparseOutputOutput._make(_result)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return ragged_count_sparse_output_eager_fallback(\n splits, values, weights, minlength=minlength, maxlength=maxlength,\n binary_output=binary_output, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"RaggedCountSparseOutput\", splits=splits, values=values,\n weights=weights,\n binary_output=binary_output,\n minlength=minlength, maxlength=maxlength,\n name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"minlength\",\n _op._get_attr_int(\"minlength\"), \"maxlength\",\n _op._get_attr_int(\"maxlength\"), \"binary_output\",\n _op._get_attr_bool(\"binary_output\"), \"output_type\",\n _op._get_attr_type(\"output_type\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"RaggedCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _RaggedCountSparseOutputOutput._make(_result)\n return _result\n\nRaggedCountSparseOutput = tf_export(\"raw_ops.RaggedCountSparseOutput\")(_ops.to_raw_op(ragged_count_sparse_output))\n\n\ndef ragged_count_sparse_output_eager_fallback(splits, values, weights, binary_output, minlength, maxlength, name, ctx):\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx)\n _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx)\n splits = _ops.convert_to_tensor(splits, _dtypes.int64)\n _inputs_flat = [splits, values, weights]\n _attrs = (\"T\", _attr_T, \"minlength\", minlength, \"maxlength\", maxlength,\n \"binary_output\", binary_output, \"output_type\", _attr_output_type)\n _result = _execute.execute(b\"RaggedCountSparseOutput\", 3,\n inputs=_inputs_flat, attrs=_attrs, ctx=ctx,\n name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"RaggedCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _RaggedCountSparseOutputOutput._make(_result)\n return _result\n\n_SparseCountSparseOutputOutput = collections.namedtuple(\n \"SparseCountSparseOutput\",\n [\"output_indices\", \"output_values\", \"output_dense_shape\"])\n\n\ndef sparse_count_sparse_output(indices, values, dense_shape, weights, binary_output, minlength=-1, maxlength=-1, name=None):\n r\"\"\"Performs sparse-output bin counting for a sparse tensor input.\n\n Counts the number of times each value occurs in the input.\n\n Args:\n indices: A `Tensor` of type `int64`.\n Tensor containing the indices of the sparse tensor to count.\n values: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Tensor containing values of the sparse tensor to count.\n dense_shape: A `Tensor` of type `int64`.\n Tensor containing the dense shape of the sparse tensor to count.\n weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`.\n A Tensor of the same shape as indices containing per-index weight values.\n May also be the empty tensor if no weights are used.\n binary_output: A `bool`.\n Whether to output the number of occurrences of each value or 1.\n minlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Minimum value to count. Can be set to -1 for no minimum.\n maxlength: An optional `int` that is `>= -1`. Defaults to `-1`.\n Maximum value to count. Can be set to -1 for no maximum.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape).\n\n output_indices: A `Tensor` of type `int64`.\n output_values: A `Tensor`. Has the same type as `weights`.\n output_dense_shape: A `Tensor` of type `int64`.\n \"\"\"\n _ctx = _context._context or _context.context()\n tld = _ctx._thread_local_data\n if tld.is_eager:\n try:\n _result = pywrap_tfe.TFE_Py_FastPathExecute(\n _ctx._context_handle, tld.device_name, \"SparseCountSparseOutput\",\n name, tld.op_callbacks, indices, values, dense_shape, weights,\n \"minlength\", minlength, \"maxlength\", maxlength, \"binary_output\",\n binary_output)\n _result = _SparseCountSparseOutputOutput._make(_result)\n return _result\n except _core._NotOkStatusException as e:\n _ops.raise_from_not_ok_status(e, name)\n except _core._FallbackException:\n pass\n try:\n return sparse_count_sparse_output_eager_fallback(\n indices, values, dense_shape, weights, minlength=minlength,\n maxlength=maxlength, binary_output=binary_output, name=name,\n ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n # Add nodes to the TensorFlow graph.\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _, _, _op, _outputs = _op_def_library._apply_op_helper(\n \"SparseCountSparseOutput\", indices=indices, values=values,\n dense_shape=dense_shape, weights=weights,\n binary_output=binary_output,\n minlength=minlength, maxlength=maxlength,\n name=name)\n _result = _outputs[:]\n if _execute.must_record_gradient():\n _attrs = (\"T\", _op._get_attr_type(\"T\"), \"minlength\",\n _op._get_attr_int(\"minlength\"), \"maxlength\",\n _op._get_attr_int(\"maxlength\"), \"binary_output\",\n _op._get_attr_bool(\"binary_output\"), \"output_type\",\n _op._get_attr_type(\"output_type\"))\n _inputs_flat = _op.inputs\n _execute.record_gradient(\n \"SparseCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _SparseCountSparseOutputOutput._make(_result)\n return _result\n\nSparseCountSparseOutput = tf_export(\"raw_ops.SparseCountSparseOutput\")(_ops.to_raw_op(sparse_count_sparse_output))\n\n\ndef sparse_count_sparse_output_eager_fallback(indices, values, dense_shape, weights, binary_output, minlength, maxlength, name, ctx):\n binary_output = _execute.make_bool(binary_output, \"binary_output\")\n if minlength is None:\n minlength = -1\n minlength = _execute.make_int(minlength, \"minlength\")\n if maxlength is None:\n maxlength = -1\n maxlength = _execute.make_int(maxlength, \"maxlength\")\n _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx)\n _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx)\n indices = _ops.convert_to_tensor(indices, _dtypes.int64)\n dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64)\n _inputs_flat = [indices, values, dense_shape, weights]\n _attrs = (\"T\", _attr_T, \"minlength\", minlength, \"maxlength\", maxlength,\n \"binary_output\", binary_output, \"output_type\", _attr_output_type)\n _result = _execute.execute(b\"SparseCountSparseOutput\", 3,\n inputs=_inputs_flat, attrs=_attrs, ctx=ctx,\n name=name)\n if _execute.must_record_gradient():\n _execute.record_gradient(\n \"SparseCountSparseOutput\", _inputs_flat, _attrs, _result)\n _result = _SparseCountSparseOutputOutput._make(_result)\n return _result\n\n" ]
[ [ "numpy.rollaxis", "numpy.ones" ], [ "tensorflow.math.abs", "pandas.Series", "numpy.linspace", "tensorflow.control_dependencies", "tensorflow.cast", "pandas.DataFrame", "tensorflow.compat.v1.test.mock.patch.object", "tensorflow.python.feature_column.feature_column.categorical_column_with_hash_bucket", "tensorflow.compat.v1.train.Optimizer", "numpy.exp", "tensorflow.compat.v1.train.Saver", "tensorflow.Graph", "tensorflow.Variable", "numpy.reshape", "tensorflow.compat.v1.io.parse_example", "tensorflow.queue.FIFOQueue", "tensorflow.train.list_variables", "tensorflow.compat.v1.get_variable_scope", "tensorflow.compat.v1.train.GradientDescentOptimizer", "tensorflow.compat.v1.initializers.random_uniform", "tensorflow.python.feature_column.feature_column.numeric_column", "tensorflow.compat.v1.get_variable", "tensorflow.feature_column.categorical_column_with_hash_bucket", "tensorflow.compat.v1.summary.FileWriterCache.clear", "tensorflow.compat.v1.fixed_size_partitioner", "tensorflow.train.load_variable", "tensorflow.compat.v1.get_collection", "tensorflow.feature_column.numeric_column", "tensorflow.compat.v1.feature_column.make_parse_example_spec", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.no_op", "tensorflow.sparse.SparseTensor", "tensorflow.compat.v1.data.Dataset.zip", "tensorflow.core.example.feature_pb2.Int64List", "numpy.array", "tensorflow.compat.v1.initializers.global_variables", "numpy.sum", "tensorflow.core.example.feature_pb2.FloatList", "tensorflow.compat.v1.gfile.Exists", "tensorflow.compat.v1.debugging.assert_less", "tensorflow.compat.v1.Session", "tensorflow.python.framework.ops.name_scope", "tensorflow.io.FixedLenFeature", "tensorflow.compat.v1.assign_add", "tensorflow.compat.v1.train.limit_epochs", "numpy.average", "tensorflow.compat.v1.test.mock.MagicMock", "tensorflow.compat.v1.feature_column.linear_model", "tensorflow.python.feature_column.feature_column_v2.LinearModel" ], [ "tensorflow.python.util.module_wrapper.TFModuleWrapper" ], [ "numpy.sqrt", "numpy.linspace", "numpy.asarray", "numpy.squeeze", "numpy.zeros_like", "numpy.mean", "numpy.exp", "numpy.hypot", "numpy.clip", "numpy.arange", "numpy.empty_like", "numpy.finfo", "numpy.diff", "numpy.zeros", "numpy.log", "numpy.nonzero", "numpy.ascontiguousarray", "numpy.meshgrid", "numpy.sum", "numpy.abs", "numpy.isscalar", "numpy.empty" ], [ "tensorflow.python.eager.execute.must_record_gradient", "tensorflow.python.eager.execute.args_to_matching_eager", "tensorflow.python.framework.ops.to_raw_op", "tensorflow.python.eager.execute.make_type", "tensorflow.python.eager.execute.make_bool", "tensorflow.python.framework.op_def_library._apply_op_helper", "tensorflow.python.pywrap_tfe.TFE_Py_FastPathExecute", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.eager.execute.make_str", "tensorflow.python.eager.execute.record_gradient", "tensorflow.python.framework.ops.raise_from_not_ok_status", "tensorflow.python.eager.execute.make_int", "tensorflow.python.eager.execute.make_float", "tensorflow.python.eager.context.context", "tensorflow.python.eager.execute.execute" ], [ "tensorflow.python.eager.execute.must_record_gradient", "tensorflow.python.eager.execute.args_to_matching_eager", "tensorflow.python.framework.ops.to_raw_op", "tensorflow.python.eager.execute.make_type", "tensorflow.python.eager.execute.make_bool", "tensorflow.python.framework.op_def_library._apply_op_helper", "tensorflow.python.pywrap_tfe.TFE_Py_FastPathExecute", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.eager.execute.record_gradient", "tensorflow.python.eager.execute.make_str", "tensorflow.python.framework.ops.raise_from_not_ok_status", "tensorflow.python.eager.execute.make_int", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.eager.context.context", "tensorflow.python.eager.execute.execute" ], [ "tensorflow.python.util.module_wrapper.TFModuleWrapper" ], [ "tensorflow.python.tools.module_util.get_parent_dir", "tensorflow.python.tools.module_util.get_parent_dir_for_name" ], [ "tensorflow.io.decode_image", "tensorflow.image.resize", "tensorflow.image.convert_image_dtype", "tensorflow.io.read_file", "tensorflow.image.ssim" ], [ "numpy.pad", "numpy.take", "numpy.ascontiguousarray", "scipy.ndimage.correlate", "scipy.ndimage.generate_binary_structure", "numpy.in1d", "scipy.ndimage.distance_transform_edt", "numpy.lexsort", "numpy.arange", "numpy.asanyarray", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.random.RandomState" ], [ "numpy.linalg.solve", "scipy.ndimage.gaussian_filter", "numpy.pad", "numpy.arctan", "numpy.gradient", "numpy.ascontiguousarray", "numpy.sum", "numpy.sqrt", "numpy.spacing", "scipy.ndimage.sobel", "numpy.linalg.eigvalsh", "numpy.linalg.det", "numpy.zeros_like", "scipy.spatial.cKDTree", "numpy.transpose", "scipy.stats.f.isf", "numpy.zeros", "numpy.isinf" ], [ "tensorflow.core.framework.summary_pb2.Summary" ], [ "tensorflow.python.util.module_wrapper.TFModuleWrapper" ], [ "tensorflow.python.eager.execute.must_record_gradient", "tensorflow.python.eager.execute.args_to_matching_eager", "tensorflow.python.framework.ops.to_raw_op", "tensorflow.python.eager.execute.make_bool", "tensorflow.python.framework.op_def_library._apply_op_helper", "tensorflow.python.pywrap_tfe.TFE_Py_FastPathExecute", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.eager.execute.record_gradient", "tensorflow.python.framework.ops.raise_from_not_ok_status", "tensorflow.python.eager.execute.make_int", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.eager.context.context", "tensorflow.python.eager.execute.execute" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "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": [ "1.13", "2.2", "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] } ]
Animatory/pytorch-image-models
[ "3ace100fcfdab3619dc71307613c42e53fb70221", "3ace100fcfdab3619dc71307613c42e53fb70221" ]
[ "timm/models/pit.py", "timm/models/layers/pool2d_same.py" ]
[ "\"\"\" Pooling-based Vision Transformer (PiT) in PyTorch\n\nA PyTorch implement of Pooling-based Vision Transformers as described in\n'Rethinking Spatial Dimensions of Vision Transformers' - https://arxiv.org/abs/2103.16302\n\nThis code was adapted from the original version at https://github.com/naver-ai/pit, original copyright below.\n\nModifications for timm by / Copyright 2020 Ross Wightman\n\"\"\"\n# PiT\n# Copyright 2021-present NAVER Corp.\n# Apache License v2.0\n\nimport math\nimport re\nfrom functools import partial\nfrom typing import Tuple\n\nimport torch\nfrom torch import nn\n\nfrom timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\nfrom .helpers import build_model_with_cfg\nfrom .layers import trunc_normal_, to_2tuple\nfrom .registry import register_model\nfrom .vision_transformer import Block\n\n\ndef _cfg(url='', **kwargs):\n return {\n 'url': url,\n 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,\n 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True,\n 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,\n 'first_conv': 'patch_embed.conv', 'classifier': 'head',\n **kwargs\n }\n\n\ndefault_cfgs = {\n # deit models (FB weights)\n 'pit_ti_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_ti_730.pth'),\n 'pit_xs_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_xs_781.pth'),\n 'pit_s_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_s_809.pth'),\n 'pit_b_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_b_820.pth'),\n 'pit_ti_distilled_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_ti_distill_746.pth',\n classifier=('head', 'head_dist')),\n 'pit_xs_distilled_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_xs_distill_791.pth',\n classifier=('head', 'head_dist')),\n 'pit_s_distilled_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_s_distill_819.pth',\n classifier=('head', 'head_dist')),\n 'pit_b_distilled_224': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_b_distill_840.pth',\n classifier=('head', 'head_dist')),\n}\n\n\nclass SequentialTuple(nn.Sequential):\n \"\"\" This module exists to work around torchscript typing issues list -> list\"\"\"\n\n def __init__(self, *args):\n super(SequentialTuple, self).__init__(*args)\n\n def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n for module in self:\n x = module(x)\n return x\n\n\nclass Transformer(nn.Module):\n def __init__(\n self, base_dim, depth, heads, mlp_ratio, pool=None, drop_rate=.0, attn_drop_rate=.0, drop_path_prob=None):\n super(Transformer, self).__init__()\n self.layers = nn.ModuleList([])\n embed_dim = base_dim * heads\n\n self.blocks = nn.Sequential(*[\n Block(\n dim=embed_dim,\n num_heads=heads,\n mlp_ratio=mlp_ratio,\n qkv_bias=True,\n drop=drop_rate,\n attn_drop=attn_drop_rate,\n drop_path=drop_path_prob[i],\n norm_layer=partial(nn.LayerNorm, eps=1e-6)\n )\n for i in range(depth)])\n\n self.pool = pool\n\n def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n x, cls_tokens = x\n B, C, H, W = x.shape\n token_length = cls_tokens.shape[1]\n\n x = x.flatten(2).transpose(1, 2)\n x = torch.cat((cls_tokens, x), dim=1)\n\n x = self.blocks(x)\n\n cls_tokens = x[:, :token_length]\n x = x[:, token_length:]\n x = x.transpose(1, 2).reshape(B, C, H, W)\n\n if self.pool is not None:\n x, cls_tokens = self.pool(x, cls_tokens)\n return x, cls_tokens\n\n\nclass ConvHeadPooling(nn.Module):\n def __init__(self, in_feature, out_feature, stride, padding_mode='zeros'):\n super(ConvHeadPooling, self).__init__()\n\n self.conv = nn.Conv2d(\n in_feature, out_feature, kernel_size=stride + 1, padding=stride // 2, stride=stride,\n padding_mode=padding_mode, groups=in_feature)\n self.fc = nn.Linear(in_feature, out_feature)\n\n def forward(self, x, cls_token) -> Tuple[torch.Tensor, torch.Tensor]:\n x = self.conv(x)\n cls_token = self.fc(cls_token)\n\n return x, cls_token\n\n\nclass ConvEmbedding(nn.Module):\n def __init__(self, in_channels, out_channels, patch_size, stride, padding):\n super(ConvEmbedding, self).__init__()\n self.conv = nn.Conv2d(\n in_channels, out_channels, kernel_size=patch_size, stride=stride, padding=padding, bias=True)\n\n def forward(self, x):\n x = self.conv(x)\n return x\n\n\nclass PoolingVisionTransformer(nn.Module):\n \"\"\" Pooling-based Vision Transformer\n\n A PyTorch implement of 'Rethinking Spatial Dimensions of Vision Transformers'\n - https://arxiv.org/abs/2103.16302\n \"\"\"\n\n def __init__(self, img_size, patch_size, stride, base_dims, depth, heads,\n mlp_ratio, num_classes=1000, in_chans=3, distilled=False,\n attn_drop_rate=.0, drop_rate=.0, drop_path_rate=.0):\n super(PoolingVisionTransformer, self).__init__()\n\n padding = 0\n img_size = to_2tuple(img_size)\n patch_size = to_2tuple(patch_size)\n height = math.floor((img_size[0] + 2 * padding - patch_size[0]) / stride + 1)\n width = math.floor((img_size[1] + 2 * padding - patch_size[1]) / stride + 1)\n\n self.base_dims = base_dims\n self.heads = heads\n self.num_classes = num_classes\n self.num_tokens = 2 if distilled else 1\n\n self.patch_size = patch_size\n self.pos_embed = nn.Parameter(torch.randn(1, base_dims[0] * heads[0], height, width))\n self.patch_embed = ConvEmbedding(in_chans, base_dims[0] * heads[0], patch_size, stride, padding)\n\n self.cls_token = nn.Parameter(torch.randn(1, self.num_tokens, base_dims[0] * heads[0]))\n self.pos_drop = nn.Dropout(p=drop_rate)\n\n transformers = []\n # stochastic depth decay rule\n dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(depth)).split(depth)]\n for stage in range(len(depth)):\n pool = None\n if stage < len(heads) - 1:\n pool = ConvHeadPooling(\n base_dims[stage] * heads[stage], base_dims[stage + 1] * heads[stage + 1], stride=2)\n transformers += [Transformer(\n base_dims[stage], depth[stage], heads[stage], mlp_ratio, pool=pool,\n drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, drop_path_prob=dpr[stage])\n ]\n self.transformers = SequentialTuple(*transformers)\n self.norm = nn.LayerNorm(base_dims[-1] * heads[-1], eps=1e-6)\n self.num_features = self.embed_dim = base_dims[-1] * heads[-1]\n\n # Classifier head\n self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n self.head_dist = None\n if distilled:\n self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()\n\n trunc_normal_(self.pos_embed, std=.02)\n trunc_normal_(self.cls_token, std=.02)\n self.apply(self._init_weights)\n\n def _init_weights(self, m):\n if isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n @torch.jit.ignore\n def no_weight_decay(self):\n return {'pos_embed', 'cls_token'}\n\n def get_classifier(self):\n if self.head_dist is not None:\n return self.head, self.head_dist\n else:\n return self.head\n\n def reset_classifier(self, num_classes, global_pool=''):\n self.num_classes = num_classes\n self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n if self.head_dist is not None:\n self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()\n\n def forward_features(self, x):\n x = self.patch_embed(x)\n x = self.pos_drop(x + self.pos_embed)\n cls_tokens = self.cls_token.expand(x.shape[0], -1, -1)\n x, cls_tokens = self.transformers((x, cls_tokens))\n cls_tokens = self.norm(cls_tokens)\n if self.head_dist is not None:\n return cls_tokens[:, 0], cls_tokens[:, 1]\n else:\n return cls_tokens[:, 0]\n\n def forward(self, x):\n x = self.forward_features(x)\n if self.head_dist is not None:\n x, x_dist = self.head(x[0]), self.head_dist(x[1]) # x must be a tuple\n if self.training and not torch.jit.is_scripting():\n return x, x_dist\n else:\n return (x + x_dist) / 2\n else:\n return self.head(x)\n\n\ndef checkpoint_filter_fn(state_dict, model):\n \"\"\" preprocess checkpoints \"\"\"\n out_dict = {}\n p_blocks = re.compile(r'pools\\.(\\d)\\.')\n for k, v in state_dict.items():\n # FIXME need to update resize for PiT impl\n # if k == 'pos_embed' and v.shape != model.pos_embed.shape:\n # # To resize pos embedding when using model at different size from pretrained weights\n # v = resize_pos_embed(v, model.pos_embed)\n k = p_blocks.sub(lambda exp: f'transformers.{int(exp.group(1))}.pool.', k)\n out_dict[k] = v\n return out_dict\n\n\ndef _create_pit(variant, pretrained=False, **kwargs):\n if kwargs.get('features_only', None):\n raise RuntimeError('features_only not implemented for Vision Transformer models.')\n\n model = build_model_with_cfg(\n PoolingVisionTransformer, variant, pretrained,\n default_cfg=default_cfgs[variant],\n pretrained_filter_fn=checkpoint_filter_fn,\n **kwargs)\n return model\n\n\n@register_model\ndef pit_b_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=14,\n stride=7,\n base_dims=[64, 64, 64],\n depth=[3, 6, 4],\n heads=[4, 8, 16],\n mlp_ratio=4,\n **kwargs\n )\n return _create_pit('pit_b_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_s_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[48, 48, 48],\n depth=[2, 6, 4],\n heads=[3, 6, 12],\n mlp_ratio=4,\n **kwargs\n )\n return _create_pit('pit_s_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_xs_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[48, 48, 48],\n depth=[2, 6, 4],\n heads=[2, 4, 8],\n mlp_ratio=4,\n **kwargs\n )\n return _create_pit('pit_xs_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_ti_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[32, 32, 32],\n depth=[2, 6, 4],\n heads=[2, 4, 8],\n mlp_ratio=4,\n **kwargs\n )\n return _create_pit('pit_ti_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_b_distilled_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=14,\n stride=7,\n base_dims=[64, 64, 64],\n depth=[3, 6, 4],\n heads=[4, 8, 16],\n mlp_ratio=4,\n distilled=True,\n **kwargs\n )\n return _create_pit('pit_b_distilled_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_s_distilled_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[48, 48, 48],\n depth=[2, 6, 4],\n heads=[3, 6, 12],\n mlp_ratio=4,\n distilled=True,\n **kwargs\n )\n return _create_pit('pit_s_distilled_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_xs_distilled_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[48, 48, 48],\n depth=[2, 6, 4],\n heads=[2, 4, 8],\n mlp_ratio=4,\n distilled=True,\n **kwargs\n )\n return _create_pit('pit_xs_distilled_224', pretrained, **model_kwargs)\n\n\n@register_model\ndef pit_ti_distilled_224(pretrained, **kwargs):\n model_kwargs = dict(\n patch_size=16,\n stride=8,\n base_dims=[32, 32, 32],\n depth=[2, 6, 4],\n heads=[2, 4, 8],\n mlp_ratio=4,\n distilled=True,\n **kwargs\n )\n return _create_pit('pit_ti_distilled_224', pretrained, **model_kwargs)\n", "\"\"\" AvgPool2d w/ Same Padding\n\nHacked together by / Copyright 2020 Ross Wightman\n\"\"\"\nfrom typing import List\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .helpers import to_2tuple\nfrom .padding import pad_same, get_padding_value\n\n\ndef avg_pool2d_same(x, kernel_size: List[int], stride: List[int], padding: List[int] = (0, 0),\n ceil_mode: bool = False, count_include_pad: bool = True):\n # FIXME how to deal with count_include_pad vs not for external padding?\n x = pad_same(x, kernel_size, stride)\n return F.avg_pool2d(x, kernel_size, stride, (0, 0), ceil_mode, count_include_pad)\n\n\nclass AvgPool2dSame(nn.AvgPool2d):\n \"\"\" Tensorflow like 'SAME' wrapper for 2D average pooling\n \"\"\"\n\n def __init__(self, kernel_size: int, stride=None, padding=0, ceil_mode=False, count_include_pad=True):\n kernel_size = to_2tuple(kernel_size)\n stride = to_2tuple(stride)\n super(AvgPool2dSame, self).__init__(kernel_size, stride, (0, 0), ceil_mode, count_include_pad)\n\n def forward(self, x):\n x = pad_same(x, self.kernel_size, self.stride)\n return F.avg_pool2d(\n x, self.kernel_size, self.stride, self.padding, self.ceil_mode, self.count_include_pad)\n\n\ndef max_pool2d_same(\n x, kernel_size: List[int], stride: List[int], padding: List[int] = (0, 0),\n dilation: List[int] = (1, 1), ceil_mode: bool = False):\n x = pad_same(x, kernel_size, stride, value=-float('inf'))\n return F.max_pool2d(x, kernel_size, stride, (0, 0), dilation, ceil_mode)\n\n\nclass MaxPool2dSame(nn.MaxPool2d):\n \"\"\" Tensorflow like 'SAME' wrapper for 2D max pooling\n \"\"\"\n\n def __init__(self, kernel_size: int, stride=None, padding=0, dilation=1, ceil_mode=False):\n kernel_size = to_2tuple(kernel_size)\n stride = to_2tuple(stride)\n dilation = to_2tuple(dilation)\n super(MaxPool2dSame, self).__init__(kernel_size, stride, (0, 0), dilation, ceil_mode)\n\n def forward(self, x):\n x = pad_same(x, self.kernel_size, self.stride, value=-float('inf'))\n return F.max_pool2d(x, self.kernel_size, self.stride, (0, 0), self.dilation, self.ceil_mode)\n\n\ndef create_pool2d(pool_type, kernel_size, stride=None, **kwargs):\n stride = stride or kernel_size\n padding = kwargs.pop('padding', '')\n padding, is_dynamic = get_padding_value(padding, kernel_size, stride=stride, **kwargs)\n if is_dynamic:\n if pool_type == 'avg':\n return AvgPool2dSame(kernel_size, stride=stride, **kwargs)\n elif pool_type == 'max':\n return MaxPool2dSame(kernel_size, stride=stride, **kwargs)\n else:\n assert False, f'Unsupported pool type {pool_type}'\n else:\n if pool_type == 'avg':\n return nn.AvgPool2d(kernel_size, stride=stride, padding=padding, **kwargs)\n elif pool_type == 'max':\n return nn.MaxPool2d(kernel_size, stride=stride, padding=padding, **kwargs)\n else:\n assert False, f'Unsupported pool type {pool_type}'\n" ]
[ [ "torch.nn.Dropout", "torch.cat", "torch.nn.init.constant_", "torch.randn", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.nn.Identity", "torch.jit.is_scripting" ], [ "torch.nn.MaxPool2d", "torch.nn.functional.avg_pool2d", "torch.nn.functional.max_pool2d", "torch.nn.AvgPool2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ningdez/Tianchi_Cancer_303
[ "59e9b6f906e48e7508f455ce29b97d430791fcf5" ]
[ "mmdet/models/necks/m2fpn.py" ]
[ "'''\nThis code is based on pytorch_ssd and RFBNet.\nDetails about the modules:\n TUM - Thinned U-shaped Module\n MLFPN - Multi-Level Feature Pyramid Network\n M2Det - Multi-level Multi-scale single-shot object Detector\n\nAuthor: Qijie Zhao ([email protected])\nFinished Date: 01/17/2019\n\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import xavier_init\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom ..registry import NECKS\nfrom ..utils import ConvModule\n\nclass TUM(nn.Module):\n def __init__(self, first_level=True, input_planes=128, is_smooth=True, side_channel=512, scales=6,\n conv_cfg=None,\n norm_cfg=None\n ):\n super(TUM, self).__init__()\n self.is_smooth = is_smooth\n self.side_channel = side_channel\n self.input_planes = input_planes\n self.planes = 2 * self.input_planes\n self.first_level = first_level\n self.scales = scales\n self.in1 = input_planes + side_channel if not first_level else input_planes\n\n self.layers = nn.Sequential()\n self.layers.add_module('{}'.format(len(self.layers)), ConvModule(self.in1, self.planes, 3, 2, 1,conv_cfg=conv_cfg,norm_cfg=norm_cfg))\n for i in range(self.scales - 2):\n if not i == self.scales - 3:\n self.layers.add_module(\n '{}'.format(len(self.layers)),\n ConvModule(self.planes, self.planes, 3, 2, 1,conv_cfg=conv_cfg,norm_cfg=norm_cfg)\n )\n else:\n self.layers.add_module(\n '{}'.format(len(self.layers)),\n ConvModule(self.planes, self.planes, 3, 1, 0,conv_cfg=conv_cfg,norm_cfg=norm_cfg)\n )\n self.toplayer = nn.Sequential(ConvModule(self.planes, self.planes, 1, 1, 0,conv_cfg=conv_cfg,norm_cfg=norm_cfg))\n\n self.latlayer = nn.Sequential()\n for i in range(self.scales - 2):\n self.latlayer.add_module(\n '{}'.format(len(self.latlayer)),\n ConvModule(self.planes, self.planes, 3, 1, 1,conv_cfg=conv_cfg,norm_cfg=norm_cfg)\n )\n self.latlayer.add_module('{}'.format(len(self.latlayer)), ConvModule(self.in1, self.planes, 3, 1, 1,conv_cfg=conv_cfg,norm_cfg=norm_cfg))\n\n if self.is_smooth:\n smooth = list()\n for i in range(self.scales - 1):\n smooth.append(\n ConvModule(self.planes, self.planes, 1, 1, 0,conv_cfg=conv_cfg,norm_cfg=norm_cfg)\n )\n self.smooth = nn.Sequential(*smooth)\n\n def _upsample_add(self, x, y, fuse_type='interp'):\n _, _, H, W = y.size()\n if fuse_type == 'interp':\n return F.interpolate(x, size=(H, W), mode='nearest') + y\n else:\n raise NotImplementedError\n # return nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1)\n\n def forward(self, x, y):\n if not self.first_level:\n x = torch.cat([x, y], 1)\n conved_feat = [x]\n for i in range(len(self.layers)):\n x = self.layers[i](x)\n conved_feat.append(x)\n\n deconved_feat = [self.toplayer[0](conved_feat[-1])]\n for i in range(len(self.latlayer)):\n deconved_feat.append(\n self._upsample_add(\n deconved_feat[i], self.latlayer[i](conved_feat[len(self.layers) - 1 - i])\n )\n )\n if self.is_smooth:\n smoothed_feat = [deconved_feat[0]]\n for i in range(len(self.smooth)):\n smoothed_feat.append(\n self.smooth[i](deconved_feat[i + 1])\n )\n return smoothed_feat\n return deconved_feat\n\nclass SFAM(nn.Module):\n def __init__(self, planes, num_levels, num_scales, compress_ratio=16):\n super(SFAM, self).__init__()\n self.planes = planes\n self.num_levels = num_levels\n self.num_scales = num_scales\n self.compress_ratio = compress_ratio\n\n self.fc1 = nn.ModuleList([nn.Conv2d(self.planes * self.num_levels,\n self.planes * self.num_levels // 16,\n 1, 1, 0)] * self.num_scales)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.ModuleList([nn.Conv2d(self.planes * self.num_levels // 16,\n self.planes * self.num_levels,\n 1, 1, 0)] * self.num_scales)\n self.sigmoid = nn.Sigmoid()\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n\n def forward(self, x):\n attention_feat = []\n for i, _mf in enumerate(x):\n _tmp_f = self.avgpool(_mf)\n _tmp_f = self.fc1[i](_tmp_f)\n _tmp_f = self.relu(_tmp_f)\n _tmp_f = self.fc2[i](_tmp_f)\n _tmp_f = self.sigmoid(_tmp_f)\n attention_feat.append(_mf * _tmp_f)\n return attention_feat\n\[email protected]_module\nclass M2FPN(nn.Module):\n def __init__(self,\n num_levels = 8,\n num_scales = 5,\n sfam=False,\n smooth=True,\n in_channels = [512,2048],\n out_channels=256, conv_cfg=None,\n norm_cfg=None):\n '''\n M2Det: Multi-level Multi-scale single-shot object Detector\n '''\n super(M2FPN,self).__init__()\n self.planes = out_channels\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n self.num_levels = num_levels\n self.num_scales = num_scales\n self.sfam = sfam\n self.smooth = smooth\n self.in_channels = in_channels\n self.shallow_out =256\n self.deep_out =512\n self.construct_modules()\n\n def construct_modules(self,):\n # construct tums\n for i in range(self.num_levels):\n if i == 0:\n setattr(self,\n 'unet{}'.format(i+1),\n TUM(first_level=True, \n input_planes=self.planes//2, \n is_smooth=self.smooth,\n scales=self.num_scales,\n side_channel=512)) #side channel isn't fixed.\n else:\n setattr(self,\n 'unet{}'.format(i+1),\n TUM(first_level=False, \n input_planes=self.planes//2, \n is_smooth=self.smooth, \n scales=self.num_scales,\n side_channel=self.planes))\n\n self.reduce= ConvModule(self.in_channels[0], self.shallow_out, kernel_size=3, stride=1, padding=1)\n self.up_reduce_1= ConvModule(self.in_channels[2], self.in_channels[1], kernel_size=1, stride=1)\n self.up_reduce_2= ConvModule(self.in_channels[1], self.deep_out, kernel_size=1, stride=1)\n\n self.Norm = nn.BatchNorm2d(256*8)\n self.leach = nn.ModuleList([ConvModule(\n self.deep_out+self.shallow_out,\n self.planes//2,\n kernel_size=(1,1),stride=(1,1))]*self.num_levels)\n\n # construct localization and recognition layers\n conv_out = nn.ModuleList()\n for i in range(self.num_scales):\n conv_out.append(nn.Conv2d(self.planes*self.num_levels,\n self.planes,\n 3, 1, 1))\n self.conv_out = nn.ModuleList(conv_out)\n\n # construct SFAM module\n if self.sfam:\n self.sfam_module = SFAM(self.planes, self.num_levels, self.num_scales, compress_ratio=16)\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n xavier_init(m, distribution='uniform')\n\n def forward(self,x):\n assert len(x)==len(self.in_channels)\n # loc,conf = list(),list()\n # base_feats = list()\n # if 'vgg' in self.net_family:\n # for k in range(len(self.base)):\n # x = self.base[k](x)\n # if k in self.base_out:\n # base_feats.append(x)\n # elif 'res' in self.net_family:\n # base_feats = self.base(x, self.base_out)\n up_feats = x[1] + F.interpolate(self.up_reduce_1(x[2]),scale_factor=2,mode='nearest')\n base_feature = torch.cat(\n (self.reduce(x[0]), F.interpolate(self.up_reduce_2(up_feats),scale_factor=2,mode='nearest')),1\n )\n\n # tum_outs is the multi-level multi-scale feature\n tum_outs = [getattr(self, 'unet{}'.format(1))(self.leach[0](base_feature), 'none')]\n for i in range(1,self.num_levels,1):\n tum_outs.append(\n getattr(self, 'unet{}'.format(i+1))(\n self.leach[i](base_feature), tum_outs[i-1][-1]\n )\n )\n # concat with same scales\n sources = [torch.cat([_fx[i-1] for _fx in tum_outs],1) for i in range(self.num_scales, 0, -1)]\n \n # forward_sfam\n if self.sfam:\n sources = self.sfam_module(sources)\n sources[0] = self.Norm(sources[0])\n output = []\n for (x,cout) in zip(sources, self.conv_out):\n output.append(cout(x))\n\n return tuple(output)\n" ]
[ [ "torch.nn.Sequential", "torch.cat", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Sigmoid", "torch.nn.AdaptiveAvgPool2d", "torch.nn.functional.interpolate", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wja30/cortex_0.31
[ "522ec6226526dee6b4f8c3ed67bdf2b913d25de3", "522ec6226526dee6b4f8c3ed67bdf2b913d25de3" ]
[ "test/apis/tensorflow/sound-classifier/predictor.py", "test/apis/pytorch/object-detector/predictor.py" ]
[ "from scipy.io.wavfile import read\nimport numpy as np\nimport io\nimport csv\n\n\nclass TensorFlowPredictor:\n def __init__(self, tensorflow_client, config):\n self.client = tensorflow_client\n self.class_names = self.class_names_from_csv(\"class_names.csv\")\n\n def class_names_from_csv(self, csv_file):\n class_names = []\n with open(csv_file, \"r\", newline=\"\") as f:\n for row in csv.reader(f, delimiter=\",\"):\n class_names.append(row[2])\n return class_names\n\n def predict(self, payload):\n rate, data = read(io.BytesIO(payload))\n assert rate == 16000\n\n result = self.client.predict({\"waveform\": np.array(data, dtype=np.float32)})\n scores = np.array(result[\"output_0\"]).reshape((-1, 521))\n\n predicted_class = self.class_names[scores.mean(axis=0).argmax() + 1]\n return predicted_class\n", "from io import BytesIO\n\nimport requests\nimport torch\nfrom PIL import Image\nfrom torchvision import models\nfrom torchvision import transforms\n\n\nclass PythonPredictor:\n def __init__(self, config):\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n print(f\"using device: {self.device}\")\n\n model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True).to(self.device)\n model.eval()\n\n self.preprocess = transforms.Compose([transforms.ToTensor()])\n\n with open(\"/mnt/project/coco_labels.txt\") as f:\n self.coco_labels = f.read().splitlines()\n\n self.model = model\n\n def predict(self, payload):\n threshold = float(payload[\"threshold\"])\n image = requests.get(payload[\"url\"]).content\n img_pil = Image.open(BytesIO(image))\n img_tensor = self.preprocess(img_pil).to(self.device)\n img_tensor.unsqueeze_(0)\n\n with torch.no_grad():\n pred = self.model(img_tensor)\n\n predicted_class = [self.coco_labels[i] for i in pred[0][\"labels\"].cpu().tolist()]\n predicted_boxes = [\n [(i[0], i[1]), (i[2], i[3])] for i in pred[0][\"boxes\"].detach().cpu().tolist()\n ]\n predicted_score = pred[0][\"scores\"].detach().cpu().tolist()\n predicted_t = [predicted_score.index(x) for x in predicted_score if x > threshold]\n if len(predicted_t) == 0:\n return [], []\n\n predicted_t = predicted_t[-1]\n predicted_boxes = predicted_boxes[: predicted_t + 1]\n predicted_class = predicted_class[: predicted_t + 1]\n return predicted_boxes, predicted_class\n" ]
[ [ "numpy.array" ], [ "torch.no_grad", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MattKrecicki/PYTHON-ISOTOPIC-DEPLETION-PACKAGE
[ "d9da8be6eff4ba301f9689ce5c38a5e50856d033" ]
[ "pyIsoDep/tests/read_csv.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"read_csv\n\nRead the different csv files\n\nCreated on Mon Oct 11 21:30:00 2021 @author: Dan Kotlyar\nLast updated on Mon Oct 11 21:45:00 2021 @author: Dan Kotlyar\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\ndef ReadCsv(csvFile):\n\n data = pd.read_csv('bootstrap.csv')\n ID = np.array(data['ZAID'], dtype=int)\n xsTypes = np.array(data['MT'], dtype=int)\n xsVals = np.array(data[\"XS [barns]\"], dtype=float)\n N0 = np.array(data[\"N0 [atoms/b-cm]\"], dtype=float)\n\n fullID = np.unique(ID) # unique isotopes\n nIsotopes = len(fullID)\n # 1-ID, 2-ND, 3-cap, 4-fiss, 5-(n,alpha)\n xsTable = np.zeros((nIsotopes, 5))\n xsTable[:, 0] = fullID\n\n # obtain all the cross section types\n numMTs = np.array([102, 18, 107])\n\n for idx, numMT in enumerate(numMTs):\n vals, idxFull, idx0 =\\\n np.intersect1d(fullID, ID[xsTypes == numMT], assume_unique=False,\n return_indices=True)\n if idx == 0:\n xsTable[idxFull, 1] = N0[xsTypes == numMT][idx0]\n xsTable[idxFull, idx+2] = xsVals[xsTypes == numMT][idx0]\n\n idxFields = {\"ID\": 0, \"N0\": 1, \"sig_c\": 2, \"sig_alpha\": 3, \"sig_f\": 4}\n\n return xsTable, idxFields\n" ]
[ [ "pandas.read_csv", "numpy.unique", "numpy.intersect1d", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Sonata-Wang/tensorflow
[ "3e21fe5faedab3a8258d344c8ad1cec2612a8aa8", "6aa83398ab03bfae822f36772757097bcb98b6ed", "83903c9dd9b5235996ec9158c30a1607fcfb4c73", "83903c9dd9b5235996ec9158c30a1607fcfb4c73", "6aa83398ab03bfae822f36772757097bcb98b6ed", "6aa83398ab03bfae822f36772757097bcb98b6ed", "6aa83398ab03bfae822f36772757097bcb98b6ed" ]
[ "tensorflow/python/data/experimental/__init__.py", "tensorflow/contrib/distribute/python/checkpoint_utils_test.py", "tensorflow/python/eager/wrap_function_test.py", "tensorflow/python/keras/engine/training_distributed.py", "tensorflow/python/ops/template.py", "tensorflow/python/tpu/tpu_system_metadata.py", "tensorflow/python/keras/mixed_precision/experimental/autocast_variable_test.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Experimental API for building input pipelines.\n\nThis module contains experimental `Dataset` sources and transformations that can\nbe used in conjunction with the `tf.data.Dataset` API. Note that the\n`tf.data.experimental` API is not subject to the same backwards compatibility\nguarantees as `tf.data`, but we will provide deprecation advice in advance of\nremoving existing functionality.\n\nSee [Importing Data](https://tensorflow.org/guide/datasets) for an overview.\n\n@@Counter\n@@CheckpointInputPipelineHook\n@@CsvDataset\n@@DatasetStructure\n@@NestedStructure\n@@OptimizationOptions\n@@Optional\n@@OptionalStructure\n@@RandomDataset\n@@Reducer\n@@SparseTensorStructure\n@@SqlDataset\n@@StatsAggregator\n@@StatsOptions\n@@Structure\n@@TFRecordWriter\n@@TensorStructure\n@@ThreadingOptions\n\n@@bucket_by_sequence_length\n@@bytes_produced_stats\n@@cardinality\n@@choose_from_datasets\n@@copy_to_device\n@@dense_to_sparse_batch\n@@enumerate_dataset\n@@filter_for_shard\n@@get_next_as_optional\n@@get_single_element\n@@group_by_reducer\n@@group_by_window\n@@ignore_errors\n@@latency_stats\n@@make_batched_features_dataset\n@@make_csv_dataset\n@@make_saveable_from_iterator\n@@map_and_batch\n@@map_and_batch_with_legacy_function\n@@parallel_interleave\n@@parse_example_dataset\n@@prefetch_to_device\n@@rejection_resample\n@@sample_from_datasets\n@@scan\n@@shuffle_and_repeat\n@@take_while\n@@unbatch\n@@unique\n\n@@AUTOTUNE\n@@INFINITE_CARDINALITY\n@@UNKNOWN_CARDINALITY\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint: disable=unused-import\n\nfrom tensorflow.python.data.experimental.ops.batching import dense_to_sparse_batch\nfrom tensorflow.python.data.experimental.ops.batching import map_and_batch\nfrom tensorflow.python.data.experimental.ops.batching import map_and_batch_with_legacy_function\nfrom tensorflow.python.data.experimental.ops.batching import unbatch\nfrom tensorflow.python.data.experimental.ops.cardinality import cardinality\nfrom tensorflow.python.data.experimental.ops.cardinality import INFINITE as INFINITE_CARDINALITY\nfrom tensorflow.python.data.experimental.ops.cardinality import UNKNOWN as UNKNOWN_CARDINALITY\nfrom tensorflow.python.data.experimental.ops.counter import Counter\nfrom tensorflow.python.data.experimental.ops.enumerate_ops import enumerate_dataset\nfrom tensorflow.python.data.experimental.ops.error_ops import ignore_errors\nfrom tensorflow.python.data.experimental.ops.filter_for_shard_ops import filter_for_shard\nfrom tensorflow.python.data.experimental.ops.get_single_element import get_single_element\nfrom tensorflow.python.data.experimental.ops.grouping import bucket_by_sequence_length\nfrom tensorflow.python.data.experimental.ops.grouping import group_by_reducer\nfrom tensorflow.python.data.experimental.ops.grouping import group_by_window\nfrom tensorflow.python.data.experimental.ops.grouping import Reducer\nfrom tensorflow.python.data.experimental.ops.interleave_ops import choose_from_datasets\nfrom tensorflow.python.data.experimental.ops.interleave_ops import parallel_interleave\nfrom tensorflow.python.data.experimental.ops.interleave_ops import sample_from_datasets\nfrom tensorflow.python.data.experimental.ops.iterator_ops import CheckpointInputPipelineHook\nfrom tensorflow.python.data.experimental.ops.iterator_ops import make_saveable_from_iterator\nfrom tensorflow.python.data.experimental.ops.optimization import AUTOTUNE\nfrom tensorflow.python.data.experimental.ops.optimization_options import OptimizationOptions\nfrom tensorflow.python.data.experimental.ops.parsing_ops import parse_example_dataset\nfrom tensorflow.python.data.experimental.ops.prefetching_ops import copy_to_device\nfrom tensorflow.python.data.experimental.ops.prefetching_ops import prefetch_to_device\nfrom tensorflow.python.data.experimental.ops.random_ops import RandomDataset\nfrom tensorflow.python.data.experimental.ops.readers import CsvDataset\nfrom tensorflow.python.data.experimental.ops.readers import make_batched_features_dataset\nfrom tensorflow.python.data.experimental.ops.readers import make_csv_dataset\nfrom tensorflow.python.data.experimental.ops.readers import SqlDataset\nfrom tensorflow.python.data.experimental.ops.resampling import rejection_resample\nfrom tensorflow.python.data.experimental.ops.scan_ops import scan\nfrom tensorflow.python.data.experimental.ops.shuffle_ops import shuffle_and_repeat\nfrom tensorflow.python.data.experimental.ops.stats_aggregator import StatsAggregator\nfrom tensorflow.python.data.experimental.ops.stats_ops import bytes_produced_stats\nfrom tensorflow.python.data.experimental.ops.stats_ops import latency_stats\nfrom tensorflow.python.data.experimental.ops.stats_options import StatsOptions\nfrom tensorflow.python.data.experimental.ops.take_while_ops import take_while\nfrom tensorflow.python.data.experimental.ops.threading_options import ThreadingOptions\nfrom tensorflow.python.data.experimental.ops.unique import unique\nfrom tensorflow.python.data.experimental.ops.writers import TFRecordWriter\nfrom tensorflow.python.data.ops.dataset_ops import DatasetStructure\nfrom tensorflow.python.data.ops.iterator_ops import get_next_as_optional\nfrom tensorflow.python.data.ops.optional_ops import Optional\nfrom tensorflow.python.data.ops.optional_ops import OptionalStructure\nfrom tensorflow.python.data.util.structure import NestedStructure\nfrom tensorflow.python.data.util.structure import SparseTensorStructure\nfrom tensorflow.python.data.util.structure import Structure\nfrom tensorflow.python.data.util.structure import TensorStructure\n# pylint: enable=unused-import\n\nfrom tensorflow.python.util.all_util import remove_undocumented\nremove_undocumented(__name__)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for checkpoint_utils.init_from_checkpoint with Distribution Strategy.\n\nThese tests are located here instead of as part of\n`python.training.CheckpointsTest` because they need access to distribution\nstrategies which are only present in contrib right now.\nTODO(priyag): Move the tests to core `python.training.CheckpointsTest` when\ndistribution strategy moves out of contrib.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom absl.testing import parameterized\n\nfrom tensorflow.contrib.distribute.python import combinations\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import checkpoint_utils\nfrom tensorflow.python.training import saver as saver_lib\n\n\ndef _create_checkpoints(sess, checkpoint_dir):\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n checkpoint_state_name = \"checkpoint\"\n v1 = variable_scope.get_variable(\"var1\", [1, 10])\n v2 = variable_scope.get_variable(\"var2\", [10, 10])\n sess.run(variables.global_variables_initializer())\n v1_value, v2_value = sess.run([v1, v2])\n saver = saver_lib.Saver()\n saver.save(\n sess,\n checkpoint_prefix,\n global_step=0,\n latest_filename=checkpoint_state_name)\n return v1_value, v2_value\n\n\nclass CheckpointUtilsWithDistributionStrategyTest(\n test.TestCase, parameterized.TestCase):\n\n def _get_test_object(self):\n checkpoint_dir = self.get_temp_dir()\n with self.cached_session() as session:\n v1, v2 = _create_checkpoints(session, checkpoint_dir)\n return checkpoint_dir, v1, v2\n\n @combinations.generate(combinations.combine(\n distribution=[combinations.default_strategy,\n combinations.one_device_strategy,\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus],\n in_replica_mode=[True, False],\n mode=[\"graph\"]))\n def testInitFromCheckpoint(self, distribution, in_replica_mode):\n checkpoint_dir, v1_value, v2_value = self._get_test_object()\n\n def init_and_verify(g):\n v1 = variable_scope.get_variable(\"new_var1\", [1, 10])\n v2 = variable_scope.get_variable(\n \"new_var2\", [10, 10],\n synchronization=variable_scope.VariableSynchronization.ON_READ,\n aggregation=variable_scope.VariableAggregation.MEAN)\n checkpoint_utils.init_from_checkpoint(checkpoint_dir, {\n \"var1\": \"new_var1\",\n \"var2\": \"new_var2\"\n })\n with self.session(graph=g) as session:\n session.run(variables.global_variables_initializer())\n self.assertAllEqual(v1_value, self.evaluate(v1))\n self.assertAllEqual(v2_value, self.evaluate(v2))\n\n with ops.Graph().as_default() as g, distribution.scope():\n if in_replica_mode:\n distribution.extended.call_for_each_replica(init_and_verify, args=[g])\n else:\n init_and_verify(g)\n\n @combinations.generate(\n combinations.combine(\n distribution=[\n combinations.default_strategy, combinations.one_device_strategy,\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus\n ],\n in_replica_mode=[True, False],\n mode=[\"graph\"]))\n def testInitFromDifferentNameObject(self, distribution, in_replica_mode):\n checkpoint_dir, v1_value, _ = self._get_test_object()\n\n def init_and_verify(g):\n v1 = variable_scope.get_variable(\"new_var1\", [1, 10])\n # Use string add to create new object in each replica\n prefix = \"new_\"\n suffix = \"var1\"\n new_var1 = prefix + suffix\n checkpoint_utils.init_from_checkpoint(checkpoint_dir, {\n \"var1\": new_var1,\n })\n with self.test_session(graph=g) as session:\n session.run(variables.global_variables_initializer())\n self.assertAllEqual(v1_value, self.evaluate(v1))\n\n with ops.Graph().as_default() as g, distribution.scope():\n if in_replica_mode:\n distribution.extended.call_for_each_replica(init_and_verify, [g])\n else:\n init_and_verify(g)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\nclass WrapFunctionTest(test.TestCase):\n\n def testDocString(self):\n\n def f(x, do_add):\n v = variables.Variable(5.0)\n if do_add:\n op = v.assign_add(x)\n else:\n op = v.assign_sub(x)\n with ops.control_dependencies([op]):\n return v.read_value()\n\n f_add = wrap_function.wrap_function(\n f, [tensor_spec.TensorSpec((), dtypes.float32), True])\n\n self.assertAllEqual(f_add(1.0), 6.0)\n self.assertAllEqual(f_add(1.0), 7.0)\n\n # Can call tf.compat.v1.wrap_function again to get a new trace, a new set\n # of variables, and possibly different non-template arguments.\n f_sub = wrap_function.wrap_function(\n f, [tensor_spec.TensorSpec((), dtypes.float32), False])\n\n self.assertAllEqual(f_sub(1.0), 4.0)\n self.assertAllEqual(f_sub(1.0), 3.0)\n\n def testPrune(self):\n\n x_in = []\n x_out = []\n\n def f(x, y):\n x_in.append(x)\n xx = x * x\n x_out.append(xx)\n return xx, 2 * y*y\n\n f_wrapped = wrap_function.wrap_function(\n f, [tensor_spec.TensorSpec((), dtypes.float32)] * 2)\n\n f_pruned = f_wrapped.prune(x_in[0], [x_out[0]])\n self.assertAllEqual(f_pruned(ops.convert_to_tensor(2.0)), [4.0])\n\n def testNoArguments(self):\n\n def f():\n return constant_op.constant(1.)\n\n f_wrapped = wrap_function.wrap_function(f, [])\n self.assertAllEqual(1.0, f_wrapped())\n\n def testPruneCaptures(self):\n\n v1 = variables.Variable(2.)\n\n def f():\n v2 = variables.Variable(3.)\n return array_ops.identity(v1 * v2 * constant_op.constant(1.), 'fetch')\n\n f_wrapped = wrap_function.wrap_function(f, [])\n self.assertAllEqual(6.0, f_wrapped())\n\n # Test pruning directly on the inputs\n pruned = f_wrapped.prune(\n feeds=f_wrapped.inputs,\n fetches=f_wrapped.graph.get_tensor_by_name('fetch:0'))\n self.assertAllEqual(6.0, pruned())\n\n # Test pruning with no inputs\n pruned = f_wrapped.prune(\n feeds=(),\n fetches=f_wrapped.graph.get_tensor_by_name('fetch:0'))\n self.assertAllEqual(6.0, pruned())\n\n def testCollectionsIsolation(self):\n\n v1 = variables.Variable(2.)\n v2_holder = []\n def f():\n v2 = variables.Variable(3.)\n v2_holder.append(v2)\n ops.add_to_collection(ops.GraphKeys.LOSSES, v2 * constant_op.constant(3.))\n return array_ops.identity(v1 * v2 * constant_op.constant(1.), 'fetch')\n\n f_wrapped = wrap_function.wrap_function(f, [])\n self.assertAllEqual(6.0, f_wrapped())\n self.assertEqual(\n len(f_wrapped.graph.get_collection(ops.GraphKeys.LOSSES)), 1)\n f_var_collection = f_wrapped.graph.get_collection(\n ops.GraphKeys.TRAINABLE_VARIABLES)\n self.assertEqual(len(f_var_collection), 1)\n self.assertIs(f_var_collection[0], v2_holder[0])\n\n v3_holder = []\n def g():\n v3 = variables.Variable(4.)\n v3_holder.append(v3)\n ops.add_to_collection(ops.GraphKeys.LOSSES, v3 * constant_op.constant(3.))\n return array_ops.identity(v1 * v3 * constant_op.constant(1.), 'fetch')\n\n g_wrapped = wrap_function.wrap_function(g, [])\n self.assertAllEqual(8.0, g_wrapped())\n self.assertEqual(\n len(g_wrapped.graph.get_collection(ops.GraphKeys.LOSSES)), 1)\n g_var_collection = g_wrapped.graph.get_collection(\n ops.GraphKeys.TRAINABLE_VARIABLES)\n self.assertEqual(len(g_var_collection), 1)\n self.assertIs(g_var_collection[0], v3_holder[0])\n\n # Both have only one value, and their values aren't equal. So no sharing.\n self.assertNotEqual(g_wrapped.graph.get_collection(ops.GraphKeys.LOSSES),\n f_wrapped.graph.get_collection(ops.GraphKeys.LOSSES))\n\n def testGradientsOfPrune(self):\n\n v1 = variables.Variable(2.)\n v2_holder = []\n\n def f(z):\n v2 = variables.Variable(3.)\n v2_holder.append(v2)\n return array_ops.identity(v1 * v2 * z, 'fetch')\n\n f_wrapped = wrap_function.wrap_function(\n f, [tensor_spec.TensorSpec((), dtype=dtypes.float32)])\n\n x = constant_op.constant(1.)\n with backprop.GradientTape() as tape:\n tape.watch(x)\n out = f_wrapped(x)\n grads = tape.gradient(out, [x, v1, v2_holder[0]])\n\n self.assertAllEqual(6.0, out)\n self.assertAllEqual([6.0, 3.0, 2.0], grads)\n\n pruned = f_wrapped.prune(\n feeds=f_wrapped.inputs,\n fetches=f_wrapped.graph.get_tensor_by_name('fetch:0'))\n\n x = constant_op.constant(1.)\n with backprop.GradientTape() as tape:\n tape.watch(x)\n out = pruned(x)\n grads = tape.gradient(out, [x, v1, v2_holder[0]])\n\n self.assertAllEqual(6.0, out)\n self.assertAllEqual([6.0, 3.0, 2.0], grads)\n\n def testPruneOperations(self):\n\n v = variables.Variable(0)\n\n def f():\n v.assign_add(1, name='increment', read_value=False)\n\n f_wrapped = wrap_function.wrap_function(f, [])\n pruned = f_wrapped.prune(\n feeds=(),\n fetches=(f_wrapped.graph.get_operation_by_name('increment'),))\n self.assertEqual((None,), pruned())\n self.assertEqual(1, self.evaluate(v))\n\n del f, f_wrapped\n\n def f1():\n v.assign_add(\n array_ops.placeholder(shape=[], dtype=dtypes.int32, name='step'),\n name='increment', read_value=False)\n return constant_op.constant(1, name='other')\n\n f_wrapped = wrap_function.wrap_function(f1, [])\n increments = f_wrapped.prune(\n feeds=(f_wrapped.graph.get_tensor_by_name('step:0')),\n fetches=(f_wrapped.graph.get_operation_by_name('increment'),\n f_wrapped.graph.get_tensor_by_name('other:0')))\n first_output, second_output = increments(constant_op.constant(2))\n self.assertEqual(['step:0', 'increment/resource:0'],\n [t.name for t in increments.inputs])\n self.assertIs(None, first_output)\n self.assertEqual(1, second_output.numpy())\n self.assertEqual(3, v.numpy())\n does_not_increment = f_wrapped.prune(\n feeds=(f_wrapped.graph.get_tensor_by_name('step:0')),\n fetches=f_wrapped.graph.get_tensor_by_name('other:0'))\n self.assertEqual(1, does_not_increment(constant_op.constant(3)).numpy())\n self.assertEqual(3, v.numpy())\n\n def testPruneStatefulOpsFromWrappedFunc(self):\n\n v0 = variables.Variable(0)\n v1 = variables.Variable(0)\n\n # When we wrap a function, we expect it to be executed with 'tf.Graph`\n # rules: it's allowed to prune all ops that are not in transitive fanin of\n # the fetches.\n def f(x):\n v0.assign_add(1, name='increment_v0')\n v1.assign_add(1, name='increment_v1')\n return x\n\n f_wrapped = wrap_function.wrap_function(f, [1])\n\n self.assertEqual(1, f_wrapped().numpy())\n self.assertEqual(0, v0.numpy())\n self.assertEqual(0, v1.numpy())\n\n f_wrapped_with_name = wrap_function.wrap_function(f, [2], name='func')\n\n self.assertEqual(2, f_wrapped_with_name().numpy())\n self.assertEqual(0, v0.numpy())\n self.assertEqual(0, v1.numpy())\n\n def test_function_from_graph_def(self):\n @def_function.function\n def make_graph_def(x):\n return x + 1.\n\n original_func_graph = make_graph_def.get_concrete_function(\n tensor_spec.TensorSpec([None, 2], dtypes.float32)).graph\n graph_def = original_func_graph.as_graph_def()\n revived_function = wrap_function.function_from_graph_def(\n graph_def, inputs=original_func_graph.inputs[0].name,\n outputs=original_func_graph.outputs[0].name)\n self.assertEqual(2., revived_function(constant_op.constant(1.)).numpy())\n\n\nif __name__ == '__main__':\n ops.enable_eager_execution()\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Part of the Keras training engine related to distributed training.\n\"\"\"\n# pylint: disable=protected-access\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.distribute import input_lib\nfrom tensorflow.python.distribute import reduce_util as ds_reduce_util\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import callbacks as cbks\nfrom tensorflow.python.keras.engine import distributed_training_utils\nfrom tensorflow.python.keras.engine import partial_batch_padding_handler as padding_util\nfrom tensorflow.python.keras.engine import training_arrays\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.utils.generic_utils import Progbar\nfrom tensorflow.python.keras.utils.mode_keys import ModeKeys\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import nest\n\n\ndef fit_distributed(model,\n x=None,\n y=None,\n batch_size=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_split=0.,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None,\n validation_freq=1):\n \"\"\"Fit loop for Distribution Strategies.\"\"\"\n distributed_training_utils.validate_callbacks(callbacks, model.optimizer)\n distributed_training_utils.validate_inputs(\n x, y, model._distribution_strategy)\n\n first_x_value = nest.flatten(x)[0]\n if isinstance(first_x_value, np.ndarray):\n # Until support for partial batch is implemented across all\n # functions and distribution strategy, we pass `mode` to selectively\n # relax the costraint to consume all the training samples.\n steps_per_epoch, batch_size = (\n distributed_training_utils.get_input_params(\n model._distribution_strategy, first_x_value, steps_per_epoch,\n batch_size, mode=ModeKeys.TRAIN))\n batch_size = model._validate_or_infer_batch_size(\n batch_size, steps_per_epoch, x)\n dataset = model._distribution_standardize_user_data(\n x, y,\n sample_weight=sample_weight,\n class_weight=class_weight,\n batch_size=batch_size,\n validation_split=validation_split,\n shuffle=shuffle)\n\n val_dataset = None\n if validation_data:\n val_x, val_y, val_sample_weights = model._unpack_validation_data(\n validation_data)\n distributed_training_utils.validate_inputs(\n val_x, val_y, model._distribution_strategy)\n first_valx_value = nest.flatten(val_x)[0]\n if isinstance(first_valx_value, np.ndarray):\n validation_steps, _ = distributed_training_utils.get_input_params(\n model._distribution_strategy, first_valx_value, validation_steps,\n batch_size)\n val_dataset = model._distribution_standardize_user_data(\n val_x, val_y,\n sample_weight=val_sample_weights,\n class_weight=None,\n batch_size=batch_size,\n validation_split=validation_split,\n shuffle=shuffle)\n elif validation_split:\n raise ValueError('validation_split argument is not supported with '\n 'distribution strategies.')\n\n if distributed_training_utils.is_tpu_strategy(model._distribution_strategy):\n return experimental_tpu_fit_loop(\n model,\n dataset,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n val_dataset=val_dataset,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps,\n validation_freq=validation_freq)\n else:\n return training_arrays.fit_loop(\n model,\n dataset,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n val_inputs=val_dataset,\n shuffle=shuffle,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps,\n validation_freq=validation_freq,\n steps_name='steps_per_epoch')\n\n\ndef evaluate_distributed(model,\n x=None,\n y=None,\n batch_size=None,\n verbose=1,\n sample_weight=None,\n steps=None,\n callbacks=None):\n \"\"\"Evaluate loop for Distribution Strategies.\"\"\"\n distributed_training_utils.validate_inputs(x, y, model._distribution_strategy)\n first_x_value = nest.flatten(x)[0]\n if isinstance(first_x_value, np.ndarray):\n steps, batch_size = distributed_training_utils.get_input_params(\n model._distribution_strategy, first_x_value, steps, batch_size)\n batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)\n dataset = model._distribution_standardize_user_data(\n x, y,\n sample_weight=sample_weight,\n batch_size=batch_size)\n\n if distributed_training_utils.is_tpu_strategy(model._distribution_strategy):\n return experimental_tpu_test_loop(\n model, dataset, verbose=verbose, steps=steps, callbacks=callbacks)\n else:\n return training_arrays.test_loop(\n model,\n inputs=dataset,\n batch_size=batch_size,\n verbose=verbose,\n steps=steps,\n callbacks=callbacks)\n\n\ndef predict_distributed(model,\n x=None,\n batch_size=None,\n verbose=0,\n steps=None,\n callbacks=None):\n \"\"\"Predict loop for Distribution Strategies.\"\"\"\n distributed_training_utils.validate_inputs(\n x, None, model._distribution_strategy, allow_partial_batch=True)\n first_x_value = nest.flatten(x)[0]\n if isinstance(first_x_value, np.ndarray):\n steps, batch_size = distributed_training_utils.get_input_params(\n model._distribution_strategy, first_x_value, steps,\n batch_size, mode=ModeKeys.PREDICT)\n batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)\n dataset = model._distribution_standardize_user_data(\n x,\n batch_size=batch_size,\n repeat=False,\n allow_partial_batch=True)\n if distributed_training_utils.is_tpu_strategy(model._distribution_strategy):\n return experimental_tpu_predict_loop(\n model, dataset, verbose=verbose, steps=steps, callbacks=callbacks)\n else:\n return training_arrays.predict_loop(\n model,\n dataset,\n batch_size=batch_size,\n verbose=verbose,\n steps=steps,\n callbacks=callbacks)\n\n\ndef _make_step_fn(model, mode, strategy, output_labels):\n \"\"\"Create step fn.\n\n Arguments:\n model: a Keras Model instance.\n mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.\n strategy: a `tf.distribute.Strategy` instance.\n output_labels: the output labels for the step function.\n\n Returns:\n A step function to run by `tf.distribute.Strategy`.\n \"\"\"\n\n def _per_device_execution_function(model):\n exec_func = model._make_execution_function(mode)\n return (exec_func.inputs, exec_func.outputs, exec_func.updates_op,\n exec_func.session_kwargs)\n\n def step_fn(ctx, inputs):\n \"\"\"A step fn that returns update ops.\"\"\"\n if mode == ModeKeys.PREDICT:\n targets = None\n else:\n inputs, targets = inputs\n\n if model._compile_distribution:\n distributed_training_utils.clone_model_on_replicas(\n model, strategy, mode, inputs=inputs, targets=targets)\n else:\n distributed_training_utils._build_distributed_network(\n model, strategy, mode, inputs, targets)\n\n (grouped_inputs, grouped_outputs, grouped_updates,\n grouped_session_args) = strategy.extended.call_for_each_replica(\n _per_device_execution_function,\n args=(distributed_training_utils.get_distributed_model(model, mode),))\n (all_inputs, all_outputs, all_updates,\n all_session_args) = distributed_training_utils.unwrap_values(\n strategy, grouped_inputs, grouped_outputs, grouped_updates,\n grouped_session_args)\n combined_fn = K.function(\n all_inputs,\n all_outputs,\n updates=all_updates,\n name='distributed_' + str(mode) + '_function',\n **all_session_args)\n\n for label, output in zip(output_labels, combined_fn.outputs):\n if mode == ModeKeys.PREDICT:\n ctx.set_last_step_output(label, output)\n else:\n if label == 'loss':\n reduce_op = ds_reduce_util.ReduceOp.SUM\n else:\n # We reduce all other metrics using mean for now. This is temporary\n # workaround until new metrics are in place.\n reduce_op = ds_reduce_util.ReduceOp.MEAN\n ctx.set_last_step_output(label, output, reduce_op)\n\n # TODO(priyag, sourabhbajaj): Ignoring these things from the combined_fn:\n # feed_dict, session kwargs, run options, run_metadata for now. These should\n # be handled appropriately\n return combined_fn.updates_op\n\n return step_fn\n\n\ndef experimental_tpu_fit_loop(model,\n dataset,\n epochs=100,\n verbose=1,\n callbacks=None,\n initial_epoch=0,\n steps_per_epoch=None,\n val_dataset=None,\n validation_steps=None,\n validation_freq=1):\n \"\"\"Fit loop for training with TPU DistributionStrategy.\n\n Arguments:\n model: Keras Model instance.\n dataset: Dataset that returns inputs and targets\n epochs: Number of times to iterate over the data\n verbose: Integer, Verbosity mode, 0, 1 or 2\n callbacks: List of callbacks to be called during training\n initial_epoch: Epoch at which to start training\n (useful for resuming a previous training run)\n steps_per_epoch: Total number of steps (batches of samples)\n before declaring one epoch finished and starting the\n next epoch. Ignored with the default value of `None`.\n val_dataset: Dataset for validation data.\n validation_steps: Number of steps to run validation for\n (only if doing validation from data tensors).\n Ignored with the default value of `None`.\n validation_freq: Only relevant if validation data is provided. Integer or\n `collections.Container` instance (e.g. list, tuple, etc.). If an\n integer, specifies how many training epochs to run before a new\n validation run is performed, e.g. `validation_freq=2` runs\n validation every 2 epochs. If a Container, specifies the epochs on\n which to run validation, e.g. `validation_freq=[1, 2, 10]` runs\n validation at the end of the 1st, 2nd, and 10th epochs.\n\n Returns:\n Returns `None`.\n\n Raises:\n ValueError: in case of invalid arguments.\n \"\"\"\n mode = ModeKeys.TRAIN\n # TODO(fchollet): add support for `steps_per_epoch=None` in TPU loops.\n current_strategy = model._distribution_strategy\n iterator = distributed_training_utils.get_iterator(dataset, current_strategy)\n steps_per_epoch = training_utils.infer_steps_for_dataset(\n dataset, steps_per_epoch, epochs, steps_name='steps_per_epoch')\n if (current_strategy.extended.steps_per_run != 1 and\n steps_per_epoch is None):\n raise ValueError('`steps_per_epoch` should be specified when calling '\n '`fit` on the model with TPUStrategy when '\n '`steps_per_run` != 1 .')\n\n scope = distributed_training_utils.distributed_scope(\n strategy=current_strategy, learning_phase=1)\n scope.__enter__()\n\n out_labels = model.metrics_names or []\n\n step_fn = _make_step_fn(model, ModeKeys.TRAIN, current_strategy, out_labels)\n\n # Add initial dummy values for loss and other metric tensors.\n initial_loop_values = {}\n initial_loop_values['loss'] = constant_op.constant(1e7)\n for name in model.metrics_names[1:]:\n tensor = model._all_stateful_metrics_tensors[name]\n initial_loop_values[name] = array_ops.zeros(tensor.shape, tensor.dtype)\n\n use_steps = steps_per_epoch is not None\n if use_steps:\n iteration_value = min(steps_per_epoch,\n current_strategy.extended.steps_per_run)\n else:\n iteration_value = current_strategy.extended.steps_per_run\n\n steps_per_run = K.variable(\n value=iteration_value,\n dtype='int32',\n name='steps_per_run')\n ctx = current_strategy.extended.experimental_run_steps_on_iterator(\n step_fn, iterator, iterations=steps_per_run,\n initial_loop_values=initial_loop_values)\n train_op = ctx.run_op\n output_tensors = ctx.last_step_outputs\n\n do_validation = bool(validation_steps)\n\n if model._compile_distribution:\n distributed_training_utils._copy_weights_to_distributed_model(model, mode)\n\n callbacks = cbks.configure_callbacks(\n callbacks,\n model,\n do_validation=do_validation,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n verbose=verbose,\n count_mode='steps',\n mode=mode)\n\n # Calculate the steps each time on the device.\n if use_steps:\n steps_to_run = ([current_strategy.extended.steps_per_run] *\n (steps_per_epoch //\n current_strategy.extended.steps_per_run))\n if steps_per_epoch % current_strategy.extended.steps_per_run:\n steps_to_run.append(\n steps_per_epoch % current_strategy.extended.steps_per_run)\n target_steps = len(steps_to_run)\n else:\n target_steps = np.inf\n\n callbacks._call_begin_hook(mode)\n for epoch in range(initial_epoch, epochs):\n distributed_training_utils._reset_metrics(model)\n callbacks.on_epoch_begin(epoch)\n epoch_logs = {}\n step_index = 0\n prev_step_count = None\n current_step = 0\n while current_step < target_steps:\n step_count = steps_to_run[current_step] if use_steps else 1\n batch_logs = {'batch': step_index, 'size': 1, 'num_steps': step_count}\n callbacks._call_batch_hook(mode, 'begin', step_index, batch_logs)\n if prev_step_count is None or step_count != prev_step_count:\n steps_per_run.load(step_count, K.get_session())\n prev_step_count = step_count\n try:\n _, outputs = K.batch_get_value([train_op, output_tensors])\n except errors.OutOfRangeError:\n if use_steps:\n logging.warning('Your dataset iterator ran out of data; '\n 'interrupting training. Make sure that your dataset '\n 'can generate at least `steps_per_epoch * epochs` '\n 'batches (in this case, %d batches).' %\n steps_per_epoch * epochs)\n else:\n target_steps = current_step\n logging.info('Dataset iterator ran out of data. Inferring the '\n 'value of `steps_per_epoch` as %s .' % target_steps)\n distributed_training_utils.initialize_iterator(iterator,\n current_strategy)\n break\n\n batch_logs.update(outputs)\n callbacks._call_batch_hook(mode, 'end', step_index, batch_logs)\n step_index = step_index + step_count\n current_step += 1\n\n if callbacks.model.stop_training:\n break\n\n if (do_validation and\n training_utils.should_run_validation(validation_freq, epoch)):\n logging.info('Running validation at fit epoch: %s', epoch)\n\n if model._compile_distribution:\n # Since we create a new clone from the original model we need to copy\n # the weights back to the original model before we can run validation.\n distributed_training_utils._copy_weights_to_original_model(\n model, ModeKeys.TRAIN)\n\n val_outs = experimental_tpu_test_loop( # pylint: disable=undefined-variable\n model,\n val_dataset,\n steps=validation_steps,\n verbose=verbose,\n callbacks=callbacks)\n if not isinstance(val_outs, list):\n val_outs = [val_outs]\n # Same labels assumed.\n for label, val_out in zip(out_labels, val_outs):\n epoch_logs['val_' + label] = val_out\n\n callbacks.on_epoch_end(epoch, epoch_logs)\n if callbacks.model.stop_training:\n break\n callbacks._call_end_hook(mode)\n\n if model._compile_distribution:\n # Copy the weights back from the replicated model to the original model.\n distributed_training_utils._copy_weights_to_original_model(\n model, ModeKeys.TRAIN)\n scope.__exit__(None, None, None)\n return model.history\n\n\ndef experimental_tpu_test_loop(model,\n dataset,\n verbose=0,\n steps=None,\n callbacks=None):\n \"\"\"Test loop for evaluating with TPU DistributionStrategy.\n\n Arguments:\n model: Keras Model instance.\n dataset: Dataset for input data.\n verbose: Integer, Verbosity mode 0 or 1.\n steps: Total number of steps (batches of samples)\n before declaring predictions finished.\n Ignored with the default value of `None`.\n callbacks: List of callbacks to be called during training\n\n Returns:\n Scalar loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the outputs.\n \"\"\"\n mode = ModeKeys.TEST\n current_strategy = model._distribution_strategy\n iterator = distributed_training_utils.get_iterator(dataset,\n current_strategy)\n steps = training_utils.infer_steps_for_dataset(dataset, steps,\n steps_name='steps')\n\n scope = distributed_training_utils.distributed_scope(\n strategy=current_strategy, learning_phase=0)\n scope.__enter__()\n\n out_labels = model.metrics_names\n step_fn = _make_step_fn(model, ModeKeys.TEST, current_strategy, out_labels)\n\n # Add initial dummy values for loss and other metric tensors.\n initial_loop_values = {}\n initial_loop_values['loss'] = constant_op.constant(1e7)\n for name in model.metrics_names[1:]:\n tensor = model._all_stateful_metrics_tensors[name]\n initial_loop_values[name] = array_ops.zeros(tensor.shape, tensor.dtype)\n\n # TODO(priyag): Use steps_per_run when we use new metrics as they will\n # allow handling metric computation at each step using variables.\n ctx = current_strategy.extended.experimental_run_steps_on_iterator(\n step_fn, iterator, iterations=1,\n initial_loop_values=initial_loop_values)\n\n test_op = ctx.run_op\n output_tensors = ctx.last_step_outputs\n\n if verbose == 1:\n progbar = Progbar(target=steps)\n\n if model._compile_distribution:\n distributed_training_utils._copy_weights_to_distributed_model(model, mode)\n\n distributed_training_utils._reset_metrics(model)\n\n callbacks = cbks.configure_callbacks(\n callbacks,\n model,\n do_validation=False,\n epochs=1,\n steps_per_epoch=steps,\n verbose=verbose,\n count_mode='steps',\n mode=ModeKeys.TEST)\n callbacks._call_begin_hook(mode)\n\n outs = [0.] * len(model.metrics_names)\n if steps is not None:\n target_steps = steps\n else:\n target_steps = np.inf\n\n current_step = 0\n while current_step < target_steps:\n batch_logs = {'batch': current_step, 'size': 1}\n callbacks._call_batch_hook(mode, 'begin', current_step, batch_logs)\n try:\n _, batch_outs = K.batch_get_value([test_op, output_tensors])\n except errors.OutOfRangeError:\n if steps is not None:\n warning_msg = 'Make sure that your dataset can generate at least '\n '`steps` batches (in this case, {} batches).'.format(steps)\n else:\n warning_msg = 'Number of steps ran: {} steps'.format(current_step)\n\n logging.warning('Your dataset iterator ran out of data; '\n 'interrupting evaluation. ' + warning_msg)\n target_steps = current_step\n break\n for i, label in enumerate(model.metrics_names):\n if i == 0:\n # Loss is stateless metrics.\n outs[i] += batch_outs[label]\n else:\n # For all stateful metrics, the aggregation is handled by mirrored vars.\n outs[i] = batch_outs[label]\n\n batch_logs = cbks.make_logs(model, batch_logs, outs, mode)\n callbacks._call_batch_hook(mode, 'end', current_step, batch_logs)\n if verbose >= 1:\n progbar.update(current_step + 1)\n current_step += 1\n\n callbacks._call_end_hook(mode)\n\n scope.__exit__(None, None, None)\n if len(outs) >= 0:\n outs[0] /= (target_steps)\n\n if len(outs) == 1:\n return outs[0]\n return outs\n\n\ndef experimental_tpu_predict_loop(model,\n dataset,\n verbose=0,\n steps=None,\n callbacks=None):\n \"\"\"Predict loop for predicting with TPU DistributionStrategy.\n\n Arguments:\n model: Keras Model instance.\n dataset: Dataset for input data.\n verbose: Integer, Verbosity mode 0 or 1.\n steps: Total number of steps (batches of samples)\n before declaring `_predict_loop` finished.\n Ignored with the default value of `None`.\n callbacks: List of callbacks to be called during training\n\n Returns:\n Array of predictions (if the model has a single output)\n or list of arrays of predictions\n (if the model has multiple outputs).\n \"\"\"\n mode = ModeKeys.PREDICT\n steps = training_utils.infer_steps_for_dataset(dataset, steps,\n steps_name='steps')\n dataset_fully_shaped = (distributed_training_utils.\n is_dataset_shape_fully_defined(dataset))\n padding_handler = None\n if not dataset_fully_shaped:\n # TODO(hongjunchoi): Investigate whether operations from\n # PartialBatchPaddingHandler are unnecessarily pruned out\n # during graph optimization.\n padding_handler = padding_util.PartialBatchPaddingHandler(\n model._feed_output_shapes)\n batch_size, _, prefetch_buffer = input_lib._get_dataset_attributes(dataset)\n padding_handler.padded_batch_size = batch_size\n padding_handler.padding_mask = dataset.reduce(padding_handler.padding_mask,\n padding_handler.update_mask)\n\n dataset = dataset.map(padding_handler.pad_batch)\n dataset = dataset.apply(batching.unbatch())\n # Upon this point, it is guaranteed that the dataset does not\n # have partial batches. Thus, we set `drop_remainder=True` to\n # get static shape information about the elements in the dataset.\n dataset = dataset.batch(batch_size, drop_remainder=True)\n\n if prefetch_buffer is not None:\n dataset = dataset.prefetch(prefetch_buffer)\n\n current_strategy = model._distribution_strategy\n iterator = distributed_training_utils.get_iterator(dataset, current_strategy)\n\n scope = distributed_training_utils.distributed_scope(\n strategy=current_strategy, learning_phase=0)\n scope.__enter__()\n\n out_labels = model.output_names\n step_fn = _make_step_fn(model, ModeKeys.PREDICT, current_strategy, out_labels)\n\n # Add initial dummy values for outputs.\n initial_loop_values = {}\n batch_dimension = distributed_training_utils.get_batch_dimension(iterator)\n for name, tensor in zip(model.output_names, model.outputs):\n # TODO(priyag): This is a workaround as we do not know the batch dimension\n # of the model's output at this point.\n shape = tensor_shape.TensorShape(tensor.shape.dims)\n shape.dims = [batch_dimension] + shape.dims[1:]\n initial_loop_values[name] = array_ops.zeros(shape, tensor.dtype)\n\n # TODO(priyag, sourabhbajaj): Support steps_per_run if/when we add outfeed.\n ctx = current_strategy.extended.experimental_run_steps_on_iterator(\n step_fn, iterator, iterations=1,\n initial_loop_values=initial_loop_values)\n\n predict_op = ctx.run_op\n output_tensors = ctx.last_step_outputs\n\n if verbose == 1:\n progbar = Progbar(target=steps)\n\n if model._compile_distribution:\n distributed_training_utils._copy_weights_to_distributed_model(model, mode)\n\n distributed_training_utils._reset_metrics(model)\n\n callbacks = cbks.configure_callbacks(\n callbacks,\n model,\n do_validation=False,\n epochs=1,\n steps_per_epoch=steps,\n verbose=verbose,\n count_mode='steps',\n mode=mode)\n callbacks._call_begin_hook(mode)\n\n # Since we do not know how many samples we will see, we cannot pre-allocate\n # the returned Numpy arrays. Instead, we store one array per batch seen\n # and concatenate them upon returning.\n unconcatenated_outs = [[] for _ in model.outputs]\n if steps is not None:\n target_steps = steps\n else:\n target_steps = np.inf\n\n current_step = 0\n while current_step < target_steps:\n batch_logs = {'batch': current_step, 'size': 1}\n callbacks._call_batch_hook(mode, 'begin', current_step, batch_logs)\n try:\n _, batch_outs = K.batch_get_value([predict_op, output_tensors])\n except errors.OutOfRangeError:\n if steps is not None:\n warning_msg = 'Make sure that your dataset can generate at least '\n '`steps` batches (in this case, {} batches).'.format(steps)\n else:\n warning_msg = 'Number of steps ran: {} steps'.format(current_step)\n\n logging.warning('Your dataset iterator ran out of data; '\n 'interrupting evaluation. ' + warning_msg)\n break\n\n # TODO(priyag): maybe need to unwrap the outputs first for MirroredStrategy.\n for i, label in enumerate(model.output_names):\n unconcatenated_outs[i].extend(batch_outs[label])\n batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode)\n callbacks._call_batch_hook(mode, 'end', current_step, batch_logs)\n if verbose >= 1:\n progbar.update(current_step + 1)\n current_step += 1\n\n callbacks._call_end_hook(mode)\n\n scope.__exit__(None, None, None)\n\n if len(unconcatenated_outs) == 1:\n prediction_result = np.concatenate(unconcatenated_outs[0], axis=0)\n else:\n prediction_result = [\n np.concatenate(unconcatenated_outs[i], axis=0)\n for i in range(len(unconcatenated_outs))\n ]\n\n if padding_handler:\n prediction_result = padding_handler.apply_mask(prediction_result)\n\n return prediction_result\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Provides templates which allow variable sharing.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport traceback\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.training.tracking import util as trackable_util\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util.deprecation import deprecated\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n__all__ = [\"make_template\"]\n\n\n@tf_export(v1=[\"make_template\"])\ndef make_template(name_, func_, create_scope_now_=False, unique_name_=None,\n custom_getter_=None, **kwargs):\n \"\"\"Given an arbitrary function, wrap it so that it does variable sharing.\n\n This wraps `func_` in a Template and partially evaluates it. Templates are\n functions that create variables the first time they are called and reuse them\n thereafter. In order for `func_` to be compatible with a `Template` it must\n have the following properties:\n\n * The function should create all trainable variables and any variables that\n should be reused by calling `tf.get_variable`. If a trainable variable is\n created using `tf.Variable`, then a ValueError will be thrown. Variables\n that are intended to be locals can be created by specifying\n `tf.Variable(..., trainable=false)`.\n * The function may use variable scopes and other templates internally to\n create and reuse variables, but it shouldn't use `tf.global_variables` to\n capture variables that are defined outside of the scope of the function.\n * Internal scopes and variable names should not depend on any arguments that\n are not supplied to `make_template`. In general you will get a ValueError\n telling you that you are trying to reuse a variable that doesn't exist\n if you make a mistake.\n\n In the following example, both `z` and `w` will be scaled by the same `y`. It\n is important to note that if we didn't assign `scalar_name` and used a\n different name for z and w that a `ValueError` would be thrown because it\n couldn't reuse the variable.\n\n ```python\n def my_op(x, scalar_name):\n var1 = tf.get_variable(scalar_name,\n shape=[],\n initializer=tf.constant_initializer(1))\n return x * var1\n\n scale_by_y = tf.make_template('scale_by_y', my_op, scalar_name='y')\n\n z = scale_by_y(input1)\n w = scale_by_y(input2)\n ```\n\n As a safe-guard, the returned function will raise a `ValueError` after the\n first call if trainable variables are created by calling `tf.Variable`.\n\n If all of these are true, then 2 properties are enforced by the template:\n\n 1. Calling the same template multiple times will share all non-local\n variables.\n 2. Two different templates are guaranteed to be unique, unless you reenter the\n same variable scope as the initial definition of a template and redefine\n it. An examples of this exception:\n\n ```python\n def my_op(x, scalar_name):\n var1 = tf.get_variable(scalar_name,\n shape=[],\n initializer=tf.constant_initializer(1))\n return x * var1\n\n with tf.variable_scope('scope') as vs:\n scale_by_y = tf.make_template('scale_by_y', my_op, scalar_name='y')\n z = scale_by_y(input1)\n w = scale_by_y(input2)\n\n # Creates a template that reuses the variables above.\n with tf.variable_scope(vs, reuse=True):\n scale_by_y2 = tf.make_template('scale_by_y', my_op, scalar_name='y')\n z2 = scale_by_y2(input1)\n w2 = scale_by_y2(input2)\n ```\n\n Depending on the value of `create_scope_now_`, the full variable scope may be\n captured either at the time of first call or at the time of construction. If\n this option is set to True, then all Tensors created by repeated calls to the\n template will have an extra trailing _N+1 to their name, as the first time the\n scope is entered in the Template constructor no Tensors are created.\n\n Note: `name_`, `func_` and `create_scope_now_` have a trailing underscore to\n reduce the likelihood of collisions with kwargs.\n\n Args:\n name_: A name for the scope created by this template. If necessary, the name\n will be made unique by appending `_N` to the name.\n func_: The function to wrap.\n create_scope_now_: Boolean controlling whether the scope should be created\n when the template is constructed or when the template is called. Default\n is False, meaning the scope is created when the template is called.\n unique_name_: When used, it overrides name_ and is not made unique. If a\n template of the same scope/unique_name already exists and reuse is false,\n an error is raised. Defaults to None.\n custom_getter_: Optional custom getter for variables used in `func_`. See\n the `tf.get_variable` `custom_getter` documentation for\n more information.\n **kwargs: Keyword arguments to apply to `func_`.\n\n Returns:\n A function to encapsulate a set of variables which should be created once\n and reused. An enclosing scope will be created either when `make_template`\n is called or when the result is called, depending on the value of\n `create_scope_now_`. Regardless of the value, the first time the template\n is called it will enter the scope with no reuse, and call `func_` to create\n variables, which are guaranteed to be unique. All subsequent calls will\n re-enter the scope and reuse those variables.\n\n Raises:\n ValueError: if `name_` is None.\n \"\"\"\n return make_template_internal(\n name_,\n func_,\n create_scope_now_,\n unique_name_,\n custom_getter_,\n create_graph_function_=False,\n **kwargs)\n\n\ndef make_template_internal(name_,\n func_,\n create_scope_now_=False,\n unique_name_=None,\n custom_getter_=None,\n create_graph_function_=False,\n **kwargs):\n \"\"\"Make a template, optionally compiling func_ into a graph function.\n\n See `make_template` for full documentation.\n\n Args:\n name_: A name for the scope created by this template. If necessary, the name\n will be made unique by appending `_N` to the name.\n func_: The function to wrap.\n create_scope_now_: Boolean controlling whether the scope should be created\n when the template is constructed or when the template is called. Default\n is False, meaning the scope is created when the template is called.\n unique_name_: When used, it overrides name_ and is not made unique. If a\n template of the same scope/unique_name already exists and reuse is false,\n an error is raised. Defaults to None. If executing eagerly, must be None.\n custom_getter_: Optional custom getter for variables used in `func_`. See\n the `tf.get_variable` `custom_getter` documentation for\n more information.\n create_graph_function_: When True, `func_` will be executed as a graph\n function. This implies that `func_` must satisfy the properties that\n `function.defun` requires of functions: See the documentation of\n `function.defun` for details. When executing eagerly, setting this flag to\n True can improve performance. Regardless of whether eager execution is\n enabled, enabling this flag gives the caller access to graph-function\n semantics, i.e., accesses to variables are totally ordered and\n side-effecting ops are not pruned.\n **kwargs: Keyword arguments to apply to `func_`.\n\n Returns:\n A function to encapsulate a set of variables which should be created once\n and reused. An enclosing scope will be created either when `make_template`\n is called or when the result is called, depending on the value of\n `create_scope_now_`. Regardless of the value, the first time the template\n is called it will enter the scope with no reuse, and call `func_` to create\n variables, which are guaranteed to be unique. All subsequent calls will\n re-enter the scope and reuse those variables.\n\n Raises:\n ValueError: if `name_` is None.\n ValueError: if `unique_name_` is not None and eager execution is enabled.\n \"\"\"\n\n if kwargs:\n func_ = tf_decorator.make_decorator(func_, functools.partial(\n func_, **kwargs))\n if context.executing_eagerly():\n if unique_name_ is not None:\n raise ValueError(\n \"unique_name_ cannot be used when eager exeuction is enabled.\")\n return EagerTemplate(\n name_,\n func_,\n create_scope_now=create_scope_now_,\n custom_getter=custom_getter_,\n create_graph_function=create_graph_function_)\n return Template(\n name_,\n func_,\n create_scope_now=create_scope_now_,\n unique_name=unique_name_,\n custom_getter=custom_getter_,\n create_graph_function=create_graph_function_)\n\n\ndef _skip_common_stack_elements(stacktrace, base_case):\n \"\"\"Skips items that the target stacktrace shares with the base stacktrace.\"\"\"\n for i, (trace, base) in enumerate(zip(stacktrace, base_case)):\n if trace != base:\n return stacktrace[i:]\n return stacktrace[-1:]\n\n\nclass Template(trackable.Trackable):\n \"\"\"Wrap a function to aid in variable sharing.\n\n Templates are functions that create variables the first time they are called\n and reuse them thereafter. See `make_template` for full documentation.\n\n Note: By default, the full variable scope is captured at the time of first\n call. If `create_scope_now_` is passed as True to the constructor, the full\n scope will be captured there, but no variables will created until the first\n call.\n \"\"\"\n\n def __init__(self, name, func, create_scope_now=False, unique_name=None,\n custom_getter=None, create_graph_function=False):\n \"\"\"Creates a template for the given function.\n\n Args:\n name: A name for the scope created by this template. The\n name will be made unique by appending `_N` to the it (see how\n `tf.variable_scope` treats the `default_name` for details).\n func: The function to apply each time.\n create_scope_now: Whether to create the scope at Template construction\n time, rather than first call. Defaults to false. Creating the scope at\n construction time may be more convenient if the template is to passed\n through much lower level code, and you want to be sure of the scope\n name without knowing exactly where it will be first called. If set to\n True, the scope will be created in the constructor, and all subsequent\n times in `__call__`, leading to a trailing numeral being added to the\n names of all created Tensors. If set to False, the scope will be created\n at the first call location.\n unique_name: When used, it overrides `name` and is not made unique. If a\n template of the same scope/unique_name already exists and reuse is\n false, an error is raised. Defaults to None.\n custom_getter: optional custom getter to pass to `variable_scope()`\n create_graph_function: When True, `func` will be executed as a graph\n function. Enabling this flag gives the caller access to graph-function\n semantics, i.e., accesses to variables are totally ordered and\n side-effecting ops are not pruned.\n\n Raises:\n ValueError: if `name` is None.\n \"\"\"\n if create_graph_function:\n self._func = function.defun(func)\n else:\n self._func = func\n self._stacktrace = traceback.format_stack()[:-2]\n self._name = name\n self._unique_name = unique_name\n self._custom_getter = custom_getter\n if name is None:\n raise ValueError(\"name cannot be None.\")\n if create_scope_now:\n with variable_scope._pure_variable_scope( # pylint:disable=protected-access\n (self._unique_name or\n variable_scope._get_unique_variable_scope(self._name)), # pylint:disable=protected-access\n custom_getter=self._custom_getter) as vs:\n self._variable_scope = vs\n else:\n self._variable_scope = None\n # This variable keeps track of whether the template has been called yet,\n # which is not the same as whether the scope has been created.\n self._variables_created = False\n\n def _call_func(self, args, kwargs):\n try:\n vars_at_start = len(\n ops.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES))\n trainable_at_start = len(\n ops.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES))\n if self._variables_created:\n result = self._func(*args, **kwargs)\n else:\n # The first time we run, restore variables if necessary (via\n # Trackable).\n with trackable_util.capture_dependencies(template=self):\n result = self._func(*args, **kwargs)\n\n if self._variables_created:\n # Variables were previously created, implying this is not the first\n # time the template has been called. Check to make sure that no new\n # trainable variables were created this time around.\n trainable_variables = ops.get_collection_ref(\n ops.GraphKeys.TRAINABLE_VARIABLES)\n # If a variable that we intend to train is created as a side effect\n # of creating a template, then that is almost certainly an error.\n if trainable_at_start != len(trainable_variables):\n raise ValueError(\"Trainable variable created when calling a template \"\n \"after the first time, perhaps you used tf.Variable \"\n \"when you meant tf.get_variable: %s\" %\n (trainable_variables[trainable_at_start:],))\n\n # Non-trainable tracking variables are a legitimate reason why a new\n # variable would be created, but it is a relatively advanced use-case,\n # so log it.\n variables = ops.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES)\n if vars_at_start != len(variables):\n logging.info(\"New variables created when calling a template after \"\n \"the first time, perhaps you used tf.Variable when you \"\n \"meant tf.get_variable: %s\",\n variables[vars_at_start:])\n else:\n self._variables_created = True\n return result\n except Exception as exc:\n # Reraise the exception, but append the original definition to the\n # trace.\n args = exc.args\n if not args:\n arg0 = \"\"\n else:\n arg0 = args[0]\n trace = \"\".join(_skip_common_stack_elements(self._stacktrace,\n traceback.format_stack()))\n arg0 = \"%s\\n\\noriginally defined at:\\n%s\" % (arg0, trace)\n new_args = [arg0]\n new_args.extend(args[1:])\n exc.args = tuple(new_args)\n raise\n\n def __call__(self, *args, **kwargs):\n if self._variable_scope:\n # Only reuse variables if they were already created.\n with variable_scope.variable_scope(\n self._variable_scope, reuse=self._variables_created):\n return self._call_func(args, kwargs)\n else:\n # The scope was not created at construction time, so create it here.\n # Subsequent calls should reuse variables.\n with variable_scope.variable_scope(\n self._unique_name, self._name,\n custom_getter=self._custom_getter) as vs:\n self._variable_scope = vs\n return self._call_func(args, kwargs)\n\n @property\n def name(self):\n \"\"\"Returns the name given to this Template.\"\"\"\n return self._name\n\n @property\n def func(self):\n \"\"\"Returns the func given to this Template.\"\"\"\n return self._func\n\n @property\n def variable_scope(self):\n \"\"\"Returns the variable scope object created by this Template.\"\"\"\n return self._variable_scope\n\n @property\n def variable_scope_name(self):\n \"\"\"Returns the variable scope name created by this Template.\"\"\"\n if self._variable_scope:\n name = self._variable_scope.name\n if not name or name[-1] == \"/\":\n return name\n else:\n # To prevent partial matches on the scope_name, we add '/' at the end.\n return name + \"/\"\n\n @property\n def variables(self):\n \"\"\"Returns the list of global and local variables created by the Template.\n \"\"\"\n return self.global_variables + self.local_variables\n\n @property\n def trainable_variables(self):\n \"\"\"Returns the list of trainable variables created by the Template.\"\"\"\n if self._variables_created:\n return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES,\n self.variable_scope_name)\n else:\n return []\n\n @property\n def non_trainable_variables(self):\n \"\"\"Returns the list of non-trainable variables created by the Template.\"\"\"\n # TODO(apassos) Make sure it matches Eager when using local variables.\n global_variables = self.global_variables\n trainable_variables = set(self.trainable_variables)\n return [x for x in global_variables if x not in trainable_variables]\n\n @property\n def global_variables(self):\n \"\"\"Returns the list of global variables created by the Template.\"\"\"\n if self._variables_created:\n return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES,\n self.variable_scope_name)\n else:\n return []\n\n @property\n def local_variables(self):\n \"\"\"Returns the list of global variables created by the Template.\"\"\"\n if self._variables_created:\n return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES,\n self.variable_scope_name)\n else:\n return []\n\n @property\n def weights(self):\n \"\"\"List of weights/variables created by the Template.\"\"\"\n return self.variables\n\n @property\n def trainable_weights(self):\n \"\"\"List of trainable weights/variables created by the Template.\"\"\"\n return self.trainable_variables\n\n @property\n def non_trainable_weights(self):\n \"\"\"List of non-trainable weights/variables created by the Template.\"\"\"\n return self.non_trainable_variables\n\n @property\n @deprecated(\n \"2017-02-21\", \"The .var_scope property is deprecated. Please change your \"\n \"code to use the .variable_scope property\")\n def var_scope(self):\n \"\"\"Returns the variable scope object created by this Template.\"\"\"\n return self._variable_scope\n\n\nclass _EagerTemplateVariableStore(object):\n \"\"\"Wrapper around EagerVariableStore to support nesting EagerTemplates.\n \"\"\"\n\n def __init__(self, variable_scope_name):\n self._variable_scope_name = variable_scope_name\n default = variable_scope._get_default_variable_store() # pylint: disable=protected-access\n if default._store_eager_variables: # pylint: disable=protected-access\n self._eager_variable_store = variable_scope.EagerVariableStore(default)\n else:\n self._eager_variable_store = variable_scope.EagerVariableStore()\n\n def set_variable_scope_name(self, variable_scope_name):\n self._variable_scope_name = variable_scope_name\n\n @tf_contextlib.contextmanager\n def as_default(self):\n try:\n with self._eager_variable_store.as_default():\n yield\n finally:\n # Each _EagerTemplateVariableStore object lives underneath a variable\n # scope (see EagerTemplate.__call__). This variable scope's subscopes are\n # closed when the EagerTemplate object returns from __call__. For\n # top-level _EagerTemplateVariableStore objects, the variable store to\n # which the variable scope is attached is different from the\n # EagerVariableStore; as such it is necessary to close its subscopes\n # here as well.\n if self._variable_scope_name is None:\n raise RuntimeError(\"A variable scope must be set before an \"\n \"_EagerTemplateVariableStore object exits.\")\n variable_scope.get_variable_scope_store().close_variable_subscopes(\n self._variable_scope_name)\n\n def _variables_in_scope(self, variable_list):\n if self._variable_scope_name is None:\n raise RuntimeError(\n \"A variable scope must be set before variables can be accessed.\")\n return [\n v for v in variable_list\n if v.name.startswith(self._variable_scope_name + \"/\")\n ]\n\n def variables(self):\n return self._variables_in_scope(self._eager_variable_store.variables())\n\n def trainable_variables(self):\n return self._variables_in_scope(\n self._eager_variable_store.trainable_variables())\n\n def non_trainable_variables(self):\n return self._variables_in_scope(\n self._eager_variable_store.non_trainable_variables())\n\n\nclass EagerTemplate(Template):\n \"\"\"Wrap a function to aid in variable sharing in Eager mode.\n\n Templates are functions that create variables the first time they are called\n and reuse them thereafter. See `make_template` for full documentation.\n\n Note: By default, the full variable scope is captured at the time of first\n call. If `create_scope_now` is passed as True to the constructor, the full\n scope will be captured there, but no variables will be created until the first\n call.\n \"\"\"\n\n def __init__(self, name, func, create_scope_now=False, custom_getter=None,\n create_graph_function=False):\n \"\"\"Creates a template for the given function.\n\n Args:\n name: A name for the scope created by this template. The\n name will be made unique by appending `_N` to the it (see how\n `tf.variable_scope` treats the `default_name` for details).\n func: The function to apply each time.\n create_scope_now: Whether to create the scope at Template construction\n time, rather than first call. Defaults to false. Creating the scope at\n construction time may be more convenient if the template is passed\n through much lower level code, and you want to be sure of the scope\n name without knowing exactly where it will be first called. If set to\n True, the scope will be created in the constructor, and all subsequent\n times in `__call__`, leading to a trailing numeral being added to the\n names of all created Tensors. If set to False, the scope will be created\n at the first call location.\n custom_getter: optional custom getter to pass to `variable_scope()`\n create_graph_function: When True, `func` will be executed as a graph\n function. Enabling this flag allows the caller to reap the performance\n benefits associated with executing graphs, at the cost of sacrificing\n debuggability; however, not all Python functions can be compiled into\n graph functions. See the documentation for `function.defun` for details.\n\n Raises:\n RuntimeError: if eager execution is not enabled.\n \"\"\"\n if not context.executing_eagerly():\n raise RuntimeError(\n \"{} objects can only be used when eager execution is enabled, use \"\n \"tf.Template for graph construction\".\n format(type(self)))\n super(EagerTemplate, self).__init__(name, func, create_scope_now, None,\n custom_getter, create_graph_function)\n if self._variable_scope is not None:\n variable_scope_name = self._variable_scope.name\n else:\n # Defer setting the variable scope name until the variable scope\n # is created in __call__.\n variable_scope_name = None\n self._template_store = _EagerTemplateVariableStore(variable_scope_name)\n self._variable_scope_context_manager = None\n\n def _call_func(self, args, kwargs):\n try:\n vars_at_start = self._template_store.variables()\n trainable_at_start = self._template_store.trainable_variables()\n if self._variables_created:\n result = self._func(*args, **kwargs)\n else:\n # The first time we run, restore variables if necessary (via\n # Trackable).\n with trackable_util.capture_dependencies(template=self):\n result = self._func(*args, **kwargs)\n\n if self._variables_created:\n # Variables were previously created, implying this is not the first\n # time the template has been called. Check to make sure that no new\n # trainable variables were created this time around.\n trainable_variables = self._template_store.trainable_variables()\n # If a variable that we intend to train is created as a side effect\n # of creating a template, then that is almost certainly an error.\n if len(trainable_at_start) != len(trainable_variables):\n raise ValueError(\"Trainable variable created when calling a template \"\n \"after the first time, perhaps you used tf.Variable \"\n \"when you meant tf.get_variable: %s\" %\n list(set(trainable_variables) -\n set(trainable_at_start)))\n\n # Non-trainable tracking variables are a legitimate reason why a new\n # variable would be created, but it is a relatively advanced use-case,\n # so log it.\n variables = self._template_store.variables()\n if len(vars_at_start) != len(variables):\n logging.info(\"New variables created when calling a template after \"\n \"the first time, perhaps you used tf.Variable when you \"\n \"meant tf.get_variable: %s\",\n list(set(variables) - set(vars_at_start)))\n else:\n self._variables_created = True\n return result\n except Exception as exc:\n # Reraise the exception, but append the original definition to the\n # trace.\n args = exc.args\n if not args:\n arg0 = \"\"\n else:\n arg0 = args[0]\n trace = \"\".join(_skip_common_stack_elements(self._stacktrace,\n traceback.format_stack()))\n arg0 = \"%s\\n\\noriginally defined at:\\n%s\" % (arg0, trace)\n new_args = [arg0]\n new_args.extend(args[1:])\n exc.args = tuple(new_args)\n raise\n\n def __call__(self, *args, **kwargs):\n # In both branches below, the template store is installed as default after\n # the variable scope is opened in order to ensure that templates nested at\n # the same level correctly uniquify lower variable scope names.\n if self._variable_scope:\n # Create a cache for the variable scope context manager the first time\n # around so that we don't have to keep recreating it.\n if not self._variable_scope_context_manager:\n self._variable_scope_context_manager = variable_scope.variable_scope(\n self._variable_scope, reuse=variable_scope.AUTO_REUSE)\n with self._variable_scope_context_manager:\n with self._template_store.as_default():\n return self._call_func(args, kwargs)\n else:\n # The scope was not created at construction time, so create it here.\n # Subsequent calls should reuse variables.\n with variable_scope.variable_scope(\n self._unique_name, self._name,\n custom_getter=self._custom_getter) as vs:\n self._variable_scope = vs\n # Because the scope was not created at construction time, the template\n # store's variable scope name is unset; set it here.\n self._template_store.set_variable_scope_name(vs.name)\n with self._template_store.as_default():\n return self._call_func(args, kwargs)\n\n @property\n def variables(self):\n \"\"\"Returns the list of variables created by the Template.\"\"\"\n # Currently there is no local variable in Eager mode.\n if not self._variables_created:\n return []\n return self._template_store.variables()\n\n @property\n def trainable_variables(self):\n \"\"\"Returns the list of trainable variables created by the Template.\"\"\"\n # Currently there is no local variable in Eager mode.\n if not self._variables_created:\n return []\n return self._template_store.trainable_variables()\n\n @property\n def non_trainable_variables(self):\n \"\"\"Returns the list of non-trainable variables created by the Template.\"\"\"\n # Currently there is no local variable in Eager mode.\n if not self._variables_created:\n return []\n return self._template_store.non_trainable_variables()\n\n @property\n def global_variables(self):\n \"\"\"Returns the list of global variables created by the Template.\"\"\"\n # Currently there is no local variable in Eager mode.\n if not self._variables_created:\n return []\n return self.variables\n\n @property\n def local_variables(self):\n \"\"\"Returns the list of global variables created by the Template.\"\"\"\n # Currently there is no local variable in Eager mode.\n return []\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===================================================================\n\"\"\"TPU system metadata and associated tooling.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport re\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.tpu import tpu\n\n_PINGING_MASTER_TIMEOUT_IN_MS = 60 * 1000 # 1 min\n_RETRY_TIMES = 120\n_INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS = 300 * 1000 # 5 mins\n\n_TPU_DEVICE_REG = re.compile(r'.*task:(\\d+)/.*device:TPU:(\\d+)$')\n\n_DEFAULT_JOB_NAME = 'tpu_worker'\n_DEFAULT_COORDINATOR_JOB_NAME = 'coordinator'\n_LOCAL_MASTERS = ('', 'local')\n\n# _TPUSystemMetadata is used by TPUEstimator to hold TPU configuration,\n# including num_cores and num_hosts.\n_TPUSystemMetadata = collections.namedtuple('_TPUSystemMetadata', [\n 'num_cores',\n 'num_hosts',\n 'num_of_cores_per_host',\n 'topology',\n 'devices',\n])\n\n\ndef _query_tpu_system_metadata(master_address, cluster_def=None,\n query_topology=False):\n \"\"\"Automatically detects the TPU system metadata in the system.\"\"\"\n tpu_core_count = 0\n devices = []\n device_dict = collections.defaultdict(list)\n\n # TODO(b/120564445): Replace with standard library for retries.\n retry_count = 1\n while True:\n logging.info('Querying Tensorflow master (%s) for TPU system metadata.',\n master_address)\n try:\n with ops.Graph().as_default():\n with session_lib.Session(\n master_address,\n config=get_session_config_with_timeout(\n _PINGING_MASTER_TIMEOUT_IN_MS,\n cluster_def)) as sess:\n devices = sess.list_devices()\n for device in devices:\n match = _TPU_DEVICE_REG.match(device.name)\n if match:\n host_id = match.group(1)\n core_id = match.group(2)\n device_dict[host_id].append(core_id)\n tpu_core_count += 1\n break\n except errors.DeadlineExceededError:\n msg = ('Failed to connect to the Tensorflow master. The TPU worker may '\n 'not be ready (still scheduling) or the Tensorflow master address '\n 'is incorrect: got (%s).' %\n (master_address))\n\n # TODO(xiejw): For local or grpc master we might not need retry logic\n # here.\n if retry_count <= _RETRY_TIMES:\n logging.warning('%s', msg)\n logging.warning('Retrying (%d/%d).', retry_count, _RETRY_TIMES)\n retry_count += 1\n else:\n raise ValueError(msg)\n\n num_of_cores_per_host = 0\n if tpu_core_count:\n num_cores_per_host_set = set(\n [len(core_ids) for core_ids in device_dict.values()])\n if len(num_cores_per_host_set) != 1:\n raise RuntimeError(\n 'TPU cores on each host is not same. This should not happen!. '\n 'devices: {}'.format(devices))\n num_of_cores_per_host = num_cores_per_host_set.pop()\n\n topology = None\n if query_topology:\n if not tpu_core_count:\n raise RuntimeError(\n 'Cannot find any TPU cores in the system (master address {}). '\n 'This usually means the master address is incorrect or the '\n 'TPU worker has some problems. Available devices: {}'.format(\n master_address, devices))\n\n topology = _obtain_topology(master_address, cluster_def)\n\n metadata = _TPUSystemMetadata(\n num_cores=tpu_core_count,\n num_hosts=len(device_dict),\n num_of_cores_per_host=num_of_cores_per_host,\n topology=topology,\n devices=devices)\n\n if tpu_core_count:\n logging.info('Found TPU system:')\n logging.info('*** Num TPU Cores: %d', metadata.num_cores)\n logging.info('*** Num TPU Workers: %d', metadata.num_hosts)\n logging.info('*** Num TPU Cores Per Worker: %d',\n metadata.num_of_cores_per_host)\n for device in metadata.devices:\n logging.info('*** Available Device: %s', device)\n else:\n logging.info('Failed to find TPU: %s', metadata)\n return metadata\n\n\ndef _obtain_topology(master_address, cluster_def):\n \"\"\"Obtains TPU fabric topology.\"\"\"\n try:\n logging.info('Initializing TPU system (master: %s) to fetch topology '\n 'for model parallelism. This might take a while.',\n master_address)\n with ops.Graph().as_default():\n session_config = get_session_config_with_timeout(\n _INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS, cluster_def)\n with session_lib.Session(\n master_address, config=session_config) as sess:\n topology = sess.run(tpu.initialize_system())\n return topology\n except errors.DeadlineExceededError:\n raise ValueError(\n 'Fail to initialize TPU system with master (%s). '\n 'Please double check the TPU system is functional.' % (\n master_address))\n\n\ndef get_session_config_with_timeout(timeout_in_secs, cluster_def):\n \"\"\"Returns a session given a timeout and a cluster configuration.\"\"\"\n config = config_pb2.ConfigProto(\n operation_timeout_in_ms=timeout_in_secs, cluster_def=cluster_def)\n return config\n\n\ndef master_job(master, cluster_def):\n \"\"\"Returns the canonnical job name to use to place TPU computations on.\n\n Args:\n master: A `string` representing the TensorFlow master to use.\n cluster_def: A ClusterDef object describing the TPU cluster.\n\n\n Returns:\n A string containing the job name, or None if no job should be specified.\n\n Raises:\n ValueError: If the user needs to specify a tpu_job_name, because we are\n unable to infer the job name automatically, or if the user-specified job\n names are inappropriate.\n \"\"\"\n # If the user specifies the tpu_job_name, use that.\n\n if master in _LOCAL_MASTERS:\n return None\n\n if (not cluster_def or not cluster_def.job):\n return _DEFAULT_JOB_NAME\n job_names = set([job.name for job in cluster_def.job])\n if _DEFAULT_JOB_NAME in job_names:\n # b/37868888 tracks allowing ClusterSpec propagation to reuse job names.\n raise ValueError('Currently, tpu_worker is not an allowed job name.')\n if len(job_names) == 1:\n return cluster_def.job[0].name\n if len(job_names) == 2:\n if _DEFAULT_COORDINATOR_JOB_NAME in job_names:\n job_names.remove(_DEFAULT_COORDINATOR_JOB_NAME)\n return job_names.pop()\n # TODO(b/67716447): Include more sophisticated heuristics.\n raise ValueError(\n 'Could not infer TPU job name. Please specify a tpu_job_name as part '\n 'of your TPUConfig.')\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for AutoCastVariable.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.distribute import mirrored_strategy\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.mixed_precision.experimental import autocast_variable\n\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\nTESTCASES = ({\n 'testcase_name': 'base',\n 'distribute': False\n}, {\n 'testcase_name': 'distribute',\n 'distribute': True\n})\n\n\ndef get_distribute_scope(distribute):\n\n class DummyContextManager(object):\n\n def __enter__(self):\n pass\n\n def __exit__(self, *args):\n pass\n\n if distribute:\n return mirrored_strategy.MirroredStrategy(['cpu:0']).scope()\n else:\n return DummyContextManager()\n\n\ndef get_autocast_var(var, distribute):\n if distribute:\n return autocast_variable.AutoCastDistributedVariable(var)\n else:\n return autocast_variable.AutoCastVariable(var)\n\n\ndef get_var(val, dtype):\n return variables.VariableV1(val, use_resource=True, dtype=dtype)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass AutoCastVariableTest(test.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(*TESTCASES)\n def test_read(self, distribute):\n with get_distribute_scope(distribute):\n x = get_var(1., dtypes.float32)\n x = get_autocast_var(x, distribute)\n self.evaluate(x.initializer)\n\n # outside of auto cast scope.\n self.assertEqual(x.dtype, dtypes.float32)\n self.assertEqual(x.value().dtype, dtypes.float32)\n self.assertEqual(x.read_value().dtype, dtypes.float32)\n self.assertEqual(array_ops.identity(x).dtype, dtypes.float32)\n\n # within auto cast scope of different dtype\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n self.assertEqual(x.dtype, dtypes.float16)\n self.assertEqual(x.value().dtype, dtypes.float16)\n self.assertEqual(x.read_value().dtype, dtypes.float16)\n self.assertEqual(array_ops.identity(x).dtype, dtypes.float16)\n\n # within auto cast scope of same dtype\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float32):\n self.assertEqual(x.dtype, dtypes.float32)\n self.assertEqual(x.value().dtype, dtypes.float32)\n self.assertEqual(x.read_value().dtype, dtypes.float32)\n self.assertEqual(array_ops.identity(x).dtype, dtypes.float32)\n\n @parameterized.named_parameters(*TESTCASES)\n def test_read_nested_scopes(self, distribute):\n with get_distribute_scope(distribute):\n x = get_var(1., dtypes.float32)\n x = get_autocast_var(x, distribute)\n self.evaluate(x.initializer)\n\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n self.assertEqual(x.dtype, dtypes.float16)\n self.assertEqual(x.read_value().dtype, dtypes.float16)\n\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float32):\n self.assertEqual(x.dtype, dtypes.float32)\n self.assertEqual(x.read_value().dtype, dtypes.float32)\n\n self.assertEqual(x.dtype, dtypes.float16)\n self.assertEqual(x.read_value().dtype, dtypes.float16)\n\n @parameterized.named_parameters(*TESTCASES)\n def test_operator_overloads(self, distribute):\n with get_distribute_scope(distribute):\n x = get_var(1., dtypes.float32)\n x = get_autocast_var(x, distribute)\n self.evaluate(x.initializer)\n\n v1 = constant_op.constant(2., dtype=dtypes.float32)\n v2 = constant_op.constant(2., dtype=dtypes.float16)\n\n # Because autocast variables do not yet define operator overloads, the\n # operator is defined by the non-variable tensor\n\n # Test variable as the LHS. Currently, this is not supported with\n # distributed autocast variables\n if not distribute:\n self.assertEqual(self.evaluate(x + v1), 3.)\n\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n self.assertEqual(self.evaluate(x + v2), 3.)\n\n # Test variable as the RHS\n self.assertEqual(self.evaluate(v1 + x), 3.)\n\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n self.assertEqual(self.evaluate(v2 + x), 3.)\n\n @parameterized.named_parameters(*TESTCASES)\n def test_assign(self, distribute):\n with get_distribute_scope(distribute):\n x = get_var(0., dtypes.float32)\n x = get_autocast_var(x, distribute)\n self.evaluate(x.initializer)\n\n # outside of auto cast scope.\n v1 = constant_op.constant(3.14, dtype=dtypes.float32)\n v2 = constant_op.constant(3.14, dtype=dtypes.float16)\n\n def run_and_check():\n # Assign float32 values\n self.assertAllClose(3.14, self.evaluate(x.assign(v1)))\n self.assertAllClose(3.14 * 2, self.evaluate(x.assign_add(v1)))\n self.assertAllClose(3.14, self.evaluate(x.assign_sub(v1)))\n\n # Attempt to assign float16 values\n with self.assertRaisesRegexp(\n ValueError,\n 'conversion requested dtype float32 for Tensor with dtype float16'):\n self.evaluate(x.assign(v2))\n with self.assertRaisesRegexp(\n ValueError,\n 'conversion requested dtype float32 for Tensor with dtype float16'):\n self.evaluate(x.assign_add(v2))\n with self.assertRaisesRegexp(\n ValueError,\n 'conversion requested dtype float32 for Tensor with dtype float16'):\n self.evaluate(x.assign_sub(v2))\n\n # Assign Python floats\n self.assertAllClose(3.14, self.evaluate(x.assign(3.14)))\n self.assertAllClose(3.14 * 2, self.evaluate(x.assign_add(3.14)))\n self.assertAllClose(3.14, self.evaluate(x.assign_sub(3.14)))\n\n run_and_check()\n # reset x\n self.evaluate(x.assign(0.))\n # within auto cast scope.\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n # assign still expect float32 value even if in float16 scope\n run_and_check()\n\n @parameterized.named_parameters(*TESTCASES)\n def test_assign_stays_in_true_dtype(self, distribute):\n with get_distribute_scope(distribute):\n x = get_var(1., dtypes.float32)\n x = get_autocast_var(x, distribute)\n self.evaluate(x.initializer)\n # small_val is a value such that 1.0 + small_val == 1.0 in fp16, but not\n # in fp32\n small_val = np.finfo('float16').eps / 2\n small_tensor = constant_op.constant(small_val, dtype=dtypes.float32)\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n # Variable should be increased, despite it appearing to be the same\n # float16 value.\n self.assertEqual(1. + small_val,\n self.evaluate(x.assign(1. + small_tensor)))\n self.assertEqual(1., self.evaluate(x.value()))\n self.assertEqual(1. + small_val, self.evaluate(x.value()))\n\n self.evaluate(x.assign(1.))\n with ops.get_default_graph()._enable_auto_casting_variables(\n dtypes.float16):\n self.assertEqual(1. + small_val,\n self.evaluate(x.assign_add(small_tensor)))\n self.assertEqual(1., self.evaluate(x.value()))\n self.assertEqual(1. + small_val, self.evaluate(x.value()))\n\n @parameterized.named_parameters(*TESTCASES)\n def test_invalid_wrapped_variable(self, distribute):\n with get_distribute_scope(distribute):\n # Wrap a non-variable\n with self.assertRaisesRegexp(ValueError, 'variable must be of type'):\n x = constant_op.constant([1.], dtype=dtypes.float32)\n get_autocast_var(x, distribute)\n\n # Wrap a non-floating point variable\n with self.assertRaisesRegexp(ValueError,\n 'variable must be a floating point'):\n x = get_var(1, dtypes.int32)\n get_autocast_var(x, distribute)\n\n if distribute:\n # Wrap a non-distributed variable with AutoCastDistributedVariable\n with self.assertRaisesRegexp(ValueError, 'variable must be of type'):\n x = get_var(1., dtypes.float32)\n get_autocast_var(x, distribute)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.util.all_util.remove_undocumented" ], [ "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.variable_scope.get_variable", "tensorflow.python.platform.test.main", "tensorflow.contrib.distribute.python.combinations.combine", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.training.checkpoint_utils.init_from_checkpoint", "tensorflow.python.training.saver.Saver" ], [ "tensorflow.python.framework.ops.enable_eager_execution", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.eager.wrap_function.function_from_graph_def", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.eager.wrap_function.wrap_function", "tensorflow.python.platform.test.main", "tensorflow.python.eager.backprop.GradientTape", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.keras.backend.batch_get_value", "tensorflow.python.data.experimental.ops.batching.unbatch", "tensorflow.python.keras.engine.distributed_training_utils.is_dataset_shape_fully_defined", "tensorflow.python.keras.backend.variable", "numpy.concatenate", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.keras.engine.training_arrays.predict_loop", "tensorflow.python.keras.engine.distributed_training_utils.initialize_iterator", "tensorflow.python.keras.engine.partial_batch_padding_handler.PartialBatchPaddingHandler", "tensorflow.python.keras.utils.generic_utils.Progbar", "tensorflow.python.keras.engine.training_arrays.fit_loop", "tensorflow.python.keras.callbacks.make_logs", "tensorflow.python.keras.engine.distributed_training_utils.clone_model_on_replicas", "tensorflow.python.keras.engine.training_utils.infer_steps_for_dataset", "tensorflow.python.keras.backend.get_session", "tensorflow.python.keras.engine.distributed_training_utils.get_distributed_model", "tensorflow.python.keras.engine.distributed_training_utils.get_batch_dimension", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.keras.engine.distributed_training_utils.get_input_params", "tensorflow.python.keras.engine.distributed_training_utils.distributed_scope", "tensorflow.python.keras.engine.distributed_training_utils._copy_weights_to_original_model", "tensorflow.python.keras.engine.training_utils.should_run_validation", "tensorflow.python.keras.engine.distributed_training_utils._build_distributed_network", "tensorflow.python.keras.callbacks.configure_callbacks", "tensorflow.python.distribute.input_lib._get_dataset_attributes", "tensorflow.python.keras.engine.distributed_training_utils.is_tpu_strategy", "tensorflow.python.keras.engine.distributed_training_utils._copy_weights_to_distributed_model", "tensorflow.python.keras.engine.distributed_training_utils.validate_callbacks", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.keras.engine.distributed_training_utils.validate_inputs", "tensorflow.python.keras.engine.distributed_training_utils.unwrap_values", "tensorflow.python.keras.engine.distributed_training_utils.get_iterator", "tensorflow.python.keras.engine.training_arrays.test_loop", "tensorflow.python.keras.engine.distributed_training_utils._reset_metrics", "tensorflow.python.util.nest.flatten", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.framework.ops.get_collection_ref", "tensorflow.python.ops.variable_scope.get_variable_scope_store", "tensorflow.python.ops.variable_scope.EagerVariableStore", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.training.tracking.util.capture_dependencies", "tensorflow.python.eager.function.defun", "tensorflow.python.ops.variable_scope._get_default_variable_store", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.variable_scope._get_unique_variable_scope", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.util.deprecation.deprecated" ], [ "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.client.session.Session", "tensorflow.python.tpu.tpu.initialize_system", "tensorflow.core.protobuf.config_pb2.ConfigProto" ], [ "tensorflow.python.keras.mixed_precision.experimental.autocast_variable.AutoCastDistributedVariable", "numpy.finfo", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.keras.mixed_precision.experimental.autocast_variable.AutoCastVariable", "tensorflow.python.ops.variables.VariableV1", "tensorflow.python.platform.test.main", "tensorflow.python.distribute.mirrored_strategy.MirroredStrategy", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.framework.constant_op.constant" ] ]
[ { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "1.4", "1.13", "2.3", "2.4", "2.2", "2.9", "1.5", "1.7", "2.5", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "2.7", "1.4", "2.6", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "1.7", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.3", "2.2" ] } ]
DoranLyong/DeepFish
[ "3ea3e13653f708d4a8dcb54b990dcc2997edf4e9" ]
[ "trainval.py" ]
[ "import torch\nimport numpy as np\nimport argparse\nimport pandas as pd\nimport sys\nimport os\nfrom torch import nn\nfrom torch.nn import functional as F\nimport tqdm\nimport pprint\nfrom src import utils as ut\nimport torchvision\nfrom haven import haven_utils as hu\nfrom haven import haven_chk as hc\n\nfrom src import datasets, models\nfrom torch.utils.data import DataLoader\nimport exp_configs\nfrom torch.utils.data.sampler import RandomSampler\nfrom src import wrappers\n\n\n\ndef trainval(exp_dict, savedir_base, reset, metrics_flag=True, datadir=None, cuda=False):\n # bookkeeping\n # ---------------\n\n # get experiment directory\n exp_id = hu.hash_dict(exp_dict)\n savedir = os.path.join(savedir_base, exp_id)\n\n if reset:\n # delete and backup experiment\n hc.delete_experiment(savedir, backup_flag=True)\n \n # create folder and save the experiment dictionary\n os.makedirs(savedir, exist_ok=True)\n hu.save_json(os.path.join(savedir, 'exp_dict.json'), exp_dict)\n print(pprint.pprint(exp_dict))\n print('Experiment saved in %s' % savedir)\n\n\n # set seed\n # ==================\n seed = 42\n np.random.seed(seed)\n torch.manual_seed(seed)\n if cuda:\n device = 'cuda'\n torch.cuda.manual_seed_all(seed)\n assert torch.cuda.is_available(), 'cuda is not, available please run with \"-c 0\"'\n else:\n device = 'cpu'\n\n print('Running on device: %s' % device)\n \n # Dataset\n # Load val set and train set\n val_set = datasets.get_dataset(dataset_name=exp_dict[\"dataset\"], split=\"val\",\n transform=exp_dict.get(\"transform\"),\n datadir=datadir)\n train_set = datasets.get_dataset(dataset_name=exp_dict[\"dataset\"],\n split=\"train\", \n transform=exp_dict.get(\"transform\"),\n datadir=datadir)\n \n # Load train loader, val loader, and vis loader\n train_loader = DataLoader(train_set, \n sampler=RandomSampler(train_set,\n replacement=True, num_samples=max(min(500, \n len(train_set)), \n len(val_set))),\n batch_size=exp_dict[\"batch_size\"])\n\n val_loader = DataLoader(val_set, shuffle=False, batch_size=exp_dict[\"batch_size\"])\n vis_loader = DataLoader(val_set, sampler=ut.SubsetSampler(train_set,\n indices=[0, 1, 2]),\n batch_size=1)\n\n # Create model, opt, wrapper\n model_original = models.get_model(exp_dict[\"model\"], exp_dict=exp_dict).cuda()\n opt = torch.optim.Adam(model_original.parameters(), \n lr=1e-5, weight_decay=0.0005)\n\n model = wrappers.get_wrapper(exp_dict[\"wrapper\"], model=model_original, opt=opt).cuda()\n\n score_list = []\n\n # Checkpointing\n # =============\n score_list_path = os.path.join(savedir, \"score_list.pkl\")\n model_path = os.path.join(savedir, \"model_state_dict.pth\")\n opt_path = os.path.join(savedir, \"opt_state_dict.pth\")\n\n if os.path.exists(score_list_path):\n # resume experiment\n score_list = ut.load_pkl(score_list_path)\n model.load_state_dict(torch.load(model_path))\n opt.load_state_dict(torch.load(opt_path))\n s_epoch = score_list[-1][\"epoch\"] + 1\n else:\n # restart experiment\n score_list = []\n s_epoch = 0\n\n # Run training and validation\n for epoch in range(s_epoch, exp_dict[\"max_epoch\"]):\n score_dict = {\"epoch\": epoch}\n\n # visualize\n # model.vis_on_loader(vis_loader, savedir=os.path.join(savedir, \"images\"))\n\n # validate\n score_dict.update(model.val_on_loader(val_loader))\n \n # train\n score_dict.update(model.train_on_loader(train_loader))\n\n # Add score_dict to score_list\n score_list += [score_dict]\n\n # Report and save\n print(pd.DataFrame(score_list).tail())\n hu.save_pkl(score_list_path, score_list)\n hu.torch_save(model_path, model.state_dict())\n hu.torch_save(opt_path, opt.state_dict())\n print(\"Saved in %s\" % savedir)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-e', '--exp_group_list', nargs='+')\n parser.add_argument('-sb', '--savedir_base', required=True)\n parser.add_argument('-d', '--datadir', required=True)\n parser.add_argument('-r', '--reset', default=0, type=int)\n parser.add_argument('-ei', '--exp_id', default=None)\n parser.add_argument('-c', '--cuda', type=int, default=1)\n\n args = parser.parse_args()\n\n\n # Collect experiments\n # -------------------\n if args.exp_id is not None:\n # select one experiment\n savedir = os.path.join(args.savedir_base, args.exp_id)\n exp_dict = hu.load_json(os.path.join(savedir, 'exp_dict.json')) \n \n exp_list = [exp_dict]\n \n else:\n # select exp group\n exp_list = []\n for exp_group_name in args.exp_group_list:\n exp_list += exp_configs.EXP_GROUPS[exp_group_name]\n\n ####\n # Run experiments or View them\n # ----------------------------\n \n # run experiments\n for exp_dict in exp_list:\n # do trainval\n trainval(exp_dict=exp_dict,\n savedir_base=args.savedir_base,\n reset=args.reset,\n datadir=args.datadir,\n cuda=args.cuda)\n\n" ]
[ [ "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "pandas.DataFrame", "torch.cuda.is_available", "torch.cuda.manual_seed_all" ] ]
[ { "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": [] } ]
AshburnLee/models
[ "98fa58030f8ce352b3818f43897ac719ccffdffc", "98fa58030f8ce352b3818f43897ac719ccffdffc" ]
[ "PaddleAudio/paddleaudio/features/augment.py", "PaddleAudio/examples/audioset_training/evaluate.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Iterable, List, Optional, Tuple, TypeVar\n\nimport numpy as np\nfrom numpy import ndarray as array\nfrom paddleaudio.backends import depth_convert\nfrom paddleaudio.utils import ParameterError\n\n__all__ = [\n 'depth_augment',\n 'spect_augment',\n 'random_crop1d',\n 'random_crop2d',\n 'adaptive_spect_augment',\n]\n\n\ndef randint(high: int) -> int:\n \"\"\"Generate one random integer in range [0 high)\n\n This is a helper function for random data augmentaiton\n \"\"\"\n return int(np.random.randint(0, high=high))\n\n\ndef rand() -> float:\n \"\"\"Generate one floating-point number in range [0 1)\n\n This is a helper function for random data augmentaiton\n \"\"\"\n return float(np.random.rand(1))\n\n\ndef depth_augment(y: array,\n choices: List = ['int8', 'int16'],\n probs: List[float] = [0.5, 0.5]) -> array:\n \"\"\" Audio depth augmentation\n\n Do audio depth augmentation to simulate the distortion brought by quantization.\n \"\"\"\n assert len(probs) == len(\n choices\n ), 'number of choices {} must be equal to size of probs {}'.format(\n len(choices), len(probs))\n depth = np.random.choice(choices, p=probs)\n src_depth = y.dtype\n y1 = depth_convert(y, depth)\n y2 = depth_convert(y1, src_depth)\n\n return y2\n\n\ndef adaptive_spect_augment(spect: array,\n tempo_axis: int = 0,\n level: float = 0.1) -> array:\n \"\"\"Do adpative spectrogram augmentation\n\n The level of the augmentation is gowern by the paramter level,\n ranging from 0 to 1, with 0 represents no augmentation。\n\n \"\"\"\n assert spect.ndim == 2., 'only supports 2d tensor or numpy array'\n if tempo_axis == 0:\n nt, nf = spect.shape\n else:\n nf, nt = spect.shape\n\n time_mask_width = int(nt * level * 0.5)\n freq_mask_width = int(nf * level * 0.5)\n\n num_time_mask = int(10 * level)\n num_freq_mask = int(10 * level)\n\n if tempo_axis == 0:\n for _ in range(num_time_mask):\n start = randint(nt - time_mask_width)\n spect[start:start + time_mask_width, :] = 0\n for _ in range(num_freq_mask):\n start = randint(nf - freq_mask_width)\n spect[:, start:start + freq_mask_width] = 0\n else:\n for _ in range(num_time_mask):\n start = randint(nt - time_mask_width)\n spect[:, start:start + time_mask_width] = 0\n for _ in range(num_freq_mask):\n start = randint(nf - freq_mask_width)\n spect[start:start + freq_mask_width, :] = 0\n\n return spect\n\n\ndef spect_augment(spect: array,\n tempo_axis: int = 0,\n max_time_mask: int = 3,\n max_freq_mask: int = 3,\n max_time_mask_width: int = 30,\n max_freq_mask_width: int = 20) -> array:\n \"\"\"Do spectrogram augmentation in both time and freq axis\n\n Reference:\n\n \"\"\"\n assert spect.ndim == 2., 'only supports 2d tensor or numpy array'\n if tempo_axis == 0:\n nt, nf = spect.shape\n else:\n nf, nt = spect.shape\n\n num_time_mask = randint(max_time_mask)\n num_freq_mask = randint(max_freq_mask)\n\n time_mask_width = randint(max_time_mask_width)\n freq_mask_width = randint(max_freq_mask_width)\n\n if tempo_axis == 0:\n for _ in range(num_time_mask):\n start = randint(nt - time_mask_width)\n spect[start:start + time_mask_width, :] = 0\n for _ in range(num_freq_mask):\n start = randint(nf - freq_mask_width)\n spect[:, start:start + freq_mask_width] = 0\n else:\n for _ in range(num_time_mask):\n start = randint(nt - time_mask_width)\n spect[:, start:start + time_mask_width] = 0\n for _ in range(num_freq_mask):\n start = randint(nf - freq_mask_width)\n spect[start:start + freq_mask_width, :] = 0\n\n return spect\n\n\ndef random_crop1d(y: array, crop_len: int) -> array:\n \"\"\" Do random cropping on 1d input signal\n\n The input is a 1d signal, typically a sound waveform\n \"\"\"\n if y.ndim != 1:\n 'only accept 1d tensor or numpy array'\n n = len(y)\n idx = randint(n - crop_len)\n return y[idx:idx + crop_len]\n\n\ndef random_crop2d(s: array, crop_len: int, tempo_axis: int = 0) -> array:\n \"\"\" Do random cropping for 2D array, typically a spectrogram.\n\n The cropping is done in temporal direction on the time-freq input signal.\n \"\"\"\n if tempo_axis >= s.ndim:\n raise ParameterError('axis out of range')\n\n n = s.shape[tempo_axis]\n idx = randint(high=n - crop_len)\n sli = [slice(None) for i in range(s.ndim)]\n sli[tempo_axis] = slice(idx, idx + crop_len)\n out = s[tuple(sli)]\n return out\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 argparse\nimport os\n\nimport numpy as np\nimport paddle\nimport paddle.nn.functional as F\nimport paddleaudio as pa\nimport yaml\nfrom dataset import get_val_loader\nfrom model import resnet50\nfrom paddle.utils import download\nfrom sklearn.metrics import average_precision_score, roc_auc_score\nfrom utils import compute_dprime,download_assets\n\ncheckpoint_url = 'https://bj.bcebos.com/paddleaudio/paddleaudio/resnet50_weight_averaging_mAP0.416.pdparams'\n\ndef evaluate(epoch, val_loader, model, loss_fn):\n model.eval()\n avg_loss = 0.0\n all_labels = []\n all_preds = []\n for batch_id, (x, y) in enumerate(val_loader()):\n x = x.unsqueeze((1))\n label = y\n logits = model(x)\n loss_val = loss_fn(logits, label)\n\n pred = F.sigmoid(logits)\n all_labels += [label.numpy()]\n all_preds += [pred.numpy()]\n avg_loss = (avg_loss * batch_id + loss_val.numpy()[0]) / (1 + batch_id)\n msg = f'eval epoch:{epoch}, batch:{batch_id}'\n msg += f'|{len(val_loader)}'\n msg += f',loss:{avg_loss:.3}'\n if batch_id % 20 == 0:\n print(msg)\n\n all_preds = np.concatenate(all_preds, 0)\n all_labels = np.concatenate(all_labels, 0)\n mAP_score = np.mean(\n average_precision_score(all_labels, all_preds, average=None))\n auc_score = np.mean(roc_auc_score(all_labels, all_preds, average=None))\n dprime = compute_dprime(auc_score)\n return avg_loss, mAP_score, auc_score, dprime\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Audioset inference')\n parser.add_argument('--config',\n type=str,\n required=False,\n default='./assets/config.yaml')\n parser.add_argument('--device',\n help='set the gpu device number',\n type=int,\n required=False,\n default=0)\n parser.add_argument('--weight', type=str, required=False, default='')\n args = parser.parse_args()\n download_assets()\n with open(args.config) as f:\n c = yaml.safe_load(f)\n paddle.set_device('gpu:{}'.format(args.device))\n ModelClass = eval(c['model_type'])\n model = ModelClass(pretrained=False,\n num_classes=c['num_classes'],\n dropout=c['dropout'])\n if args.weight.strip() == '':\n print(f'Using pretrained weight: {checkpoint_url}')\n args.weight = download.get_weights_path_from_url(checkpoint_url)\n model.load_dict(paddle.load(args.weight))\n model.eval()\n\n val_loader = get_val_loader(c)\n\n print(f'Evaluating...')\n avg_loss, mAP_score, auc_score, dprime = evaluate(\n 0, val_loader, model, F.binary_cross_entropy_with_logits)\n\n print(f'mAP: {mAP_score:.3}')\n print(f'auc: {auc_score:.3}')\n print(f'd-prime: {dprime:.3}')\n" ]
[ [ "numpy.random.randint", "numpy.random.rand", "numpy.random.choice" ], [ "numpy.concatenate", "sklearn.metrics.roc_auc_score", "sklearn.metrics.average_precision_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bahia14/Fedot_Times_Series_Forecast
[ "995751068733541ba2f546065082709ce0fb63ae", "995751068733541ba2f546065082709ce0fb63ae" ]
[ "fedot/core/pipelines/tuning/unified.py", "test/unit/tasks/test_forecasting.py" ]
[ "from datetime import timedelta\nfrom functools import partial\n\nimport numpy as np\nfrom hyperopt import fmin, space_eval, tpe\n\nfrom fedot.core.data.data_split import train_test_data_setup\nfrom fedot.core.log import Log\nfrom fedot.core.pipelines.tuning.hyperparams import convert_params, get_node_params\nfrom fedot.core.pipelines.tuning.tuner_interface import HyperoptTuner, _greater_is_better\n\nMAX_METRIC_VALUE = 10e6\n\n\nclass PipelineTuner(HyperoptTuner):\n \"\"\"\n Class for hyperparameters optimization for all nodes simultaneously\n \"\"\"\n\n def __init__(self, pipeline, task, iterations=100,\n timeout: timedelta = timedelta(minutes=5),\n log: Log = None):\n super().__init__(pipeline, task, iterations, timeout, log)\n\n def tune_pipeline(self, input_data, loss_function, loss_params=None):\n \"\"\" Function for hyperparameters tuning on the entire pipeline \"\"\"\n\n parameters_dict = self._get_parameters_for_tune(self.pipeline)\n\n # Train test split\n train_input, predict_input = train_test_data_setup(input_data)\n test_target = np.array(predict_input.target)\n\n is_need_to_maximize = _greater_is_better(target=test_target,\n loss_function=loss_function,\n loss_params=loss_params)\n self.is_need_to_maximize = is_need_to_maximize\n\n # Check source metrics for data\n self.init_check(train_input, predict_input, test_target,\n loss_function, loss_params)\n\n best = fmin(partial(self._objective,\n pipeline=self.pipeline,\n train_input=train_input,\n predict_input=predict_input,\n test_target=test_target,\n loss_function=loss_function,\n loss_params=loss_params),\n parameters_dict,\n algo=tpe.suggest,\n max_evals=self.iterations,\n timeout=self.max_seconds)\n\n best = space_eval(space=parameters_dict, hp_assignment=best)\n\n tuned_pipeline = self.set_arg_pipeline(pipeline=self.pipeline,\n parameters=best)\n\n # Validation is the optimization do well\n final_pipeline = self.final_check(train_input=train_input,\n predict_input=predict_input,\n test_target=test_target,\n tuned_pipeline=tuned_pipeline,\n loss_function=loss_function,\n loss_params=loss_params)\n\n return final_pipeline\n\n @staticmethod\n def set_arg_pipeline(pipeline, parameters):\n \"\"\" Method for parameters setting to a pipeline\n\n :param pipeline: pipeline to which parameters should ba assigned\n :param parameters: dictionary with parameters to set\n :return pipeline: pipeline with new hyperparameters in each node\n \"\"\"\n\n # Set hyperparameters for every node\n for node_id, _ in enumerate(pipeline.nodes):\n node_params = parameters.get(node_id)\n\n if node_params is not None:\n # Delete all prefix strings to get appropriate parameters names\n new_params = convert_params(node_params)\n\n # Update parameters in nodes\n pipeline.nodes[node_id].custom_params = new_params\n\n return pipeline\n\n @staticmethod\n def _get_parameters_for_tune(pipeline):\n \"\"\"\n Function for defining the search space\n\n :param pipeline: pipeline to optimize\n :return parameters_dict: dictionary with operation names and parameters\n \"\"\"\n\n parameters_dict = {}\n for node_id, node in enumerate(pipeline.nodes):\n operation_name = str(node.operation)\n\n # Assign unique prefix for each model hyperparameter\n # label - number of node in the pipeline\n node_params = get_node_params(node_id=node_id,\n operation_name=operation_name)\n\n parameters_dict.update({node_id: node_params})\n\n return parameters_dict\n\n def _objective(self, parameters_dict, pipeline, train_input, predict_input,\n test_target, loss_function, loss_params: dict):\n \"\"\"\n Objective function for minimization / maximization problem\n\n :param parameters_dict: dictionary with operation names and parameters\n :param pipeline: pipeline to optimize\n :param train_input: input for train pipeline model\n :param predict_input: input for test pipeline model\n :param test_target: target for validation\n :param loss_function: loss function to optimize\n :param loss_params: parameters for loss function\n\n :return metric_value: value of objective function\n \"\"\"\n\n # Set hyperparameters for every node\n pipeline = PipelineTuner.set_arg_pipeline(pipeline=pipeline, parameters=parameters_dict)\n\n try:\n metric_value = PipelineTuner.get_metric_value(train_input=train_input,\n predict_input=predict_input,\n test_target=test_target,\n pipeline=pipeline,\n loss_function=loss_function,\n loss_params=loss_params)\n except Exception:\n if self.is_need_to_maximize is True:\n metric_value = -MAX_METRIC_VALUE\n else:\n metric_value = MAX_METRIC_VALUE\n\n if self.is_need_to_maximize is True:\n return -metric_value\n else:\n return metric_value\n", "from random import seed\n\nimport numpy as np\nimport pytest\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom statsmodels.tsa.arima_process import ArmaProcess\n\nfrom fedot.core.data.data import InputData\nfrom fedot.core.data.data_split import train_test_data_setup\nfrom fedot.core.pipelines.node import PrimaryNode, SecondaryNode\nfrom fedot.core.pipelines.pipeline import Pipeline\nfrom fedot.core.pipelines.ts_wrappers import in_sample_ts_forecast, out_of_sample_ts_forecast\nfrom fedot.core.repository.dataset_types import DataTypesEnum\nfrom fedot.core.repository.tasks import Task, TaskTypesEnum, TsForecastingParams\nfrom fedot.utilities.synth_dataset_generator import generate_synthetic_data\n\nnp.random.seed(42)\nseed(42)\n\n\ndef _max_rmse_threshold_by_std(values, is_strict=True):\n tolerance_coeff = 3.0 if is_strict else 5.0\n return np.std(values) * tolerance_coeff\n\n\ndef get_synthetic_ts_data_period(n_steps=1000, forecast_length=5):\n simulated_data = ArmaProcess().generate_sample(nsample=n_steps)\n x1 = np.arange(0, n_steps)\n x2 = np.arange(0, n_steps) + 1\n\n simulated_data = simulated_data + x1 * 0.0005 - x2 * 0.0001\n\n periodicity = np.sin(x1 / 50)\n\n simulated_data = simulated_data + periodicity\n\n task = Task(TaskTypesEnum.ts_forecasting,\n TsForecastingParams(forecast_length=forecast_length))\n\n data = InputData(idx=np.arange(0, n_steps),\n features=simulated_data,\n target=simulated_data,\n task=task,\n data_type=DataTypesEnum.ts)\n return train_test_data_setup(data)\n\n\ndef get_multiscale_pipeline():\n # First branch\n node_lagged_1 = PrimaryNode('lagged')\n node_lagged_1.custom_params = {'window_size': 20}\n node_ridge_1 = SecondaryNode('ridge', nodes_from=[node_lagged_1])\n\n # Second branch, which will try to make prediction based on smoothed ts\n node_filtering = PrimaryNode('gaussian_filter')\n node_filtering.custom_params = {'sigma': 3}\n node_lagged_2 = SecondaryNode('lagged', nodes_from=[node_filtering])\n node_lagged_2.custom_params = {'window_size': 100}\n node_ridge_2 = SecondaryNode('ridge', nodes_from=[node_lagged_2])\n\n node_final = SecondaryNode('linear', nodes_from=[node_ridge_1, node_ridge_2])\n\n pipeline = Pipeline(node_final)\n\n return pipeline\n\n\ndef get_simple_ts_pipeline(model_root: str = 'ridge', window_size: int = 20):\n node_lagged = PrimaryNode('lagged')\n node_lagged.custom_params = {'window_size': window_size}\n node_root = SecondaryNode(model_root, nodes_from=[node_lagged])\n\n pipeline = Pipeline(node_root)\n\n return pipeline\n\n\ndef get_statsmodels_pipeline():\n node_ar = PrimaryNode('ar')\n node_ar.custom_params = {'lag_1': 20, 'lag_2': 100}\n pipeline = Pipeline(node_ar)\n return pipeline\n\n\ndef test_arima_pipeline_fit_correct():\n train_data, test_data = get_synthetic_ts_data_period(forecast_length=12)\n\n pipeline = get_statsmodels_pipeline()\n\n pipeline.fit(input_data=train_data)\n test_pred = pipeline.predict(input_data=test_data)\n\n # Calculate metric\n test_pred = np.ravel(np.array(test_pred.predict))\n test_target = np.ravel(np.array(test_data.target))\n\n rmse_test = mean_squared_error(test_target, test_pred, squared=False)\n\n rmse_threshold = _max_rmse_threshold_by_std(test_data.target)\n\n assert rmse_test < rmse_threshold\n\n\ndef test_simple_pipeline_forecast_correct():\n train_data, test_data = get_synthetic_ts_data_period(forecast_length=5)\n\n pipeline = get_simple_ts_pipeline()\n\n pipeline.fit(input_data=train_data)\n test_pred = pipeline.predict(input_data=test_data)\n\n # Calculate metric\n test_pred = np.ravel(np.array(test_pred.predict))\n test_target = np.ravel(np.array(test_data.target))\n rmse_test = mean_squared_error(test_target, test_pred, squared=False)\n\n rmse_threshold = _max_rmse_threshold_by_std(test_data.target, is_strict=True)\n\n assert rmse_test < rmse_threshold\n\n\ndef test_regression_multiscale_pipeline_forecast_correct():\n train_data, test_data = get_synthetic_ts_data_period(forecast_length=5)\n\n pipeline = get_multiscale_pipeline()\n\n pipeline.fit(input_data=train_data)\n test_pred = pipeline.predict(input_data=test_data)\n\n # Calculate metric\n test_pred = np.ravel(np.array(test_pred.predict))\n test_target = np.ravel(np.array(test_data.target))\n rmse_test = mean_squared_error(test_target, test_pred, squared=False)\n\n rmse_threshold = _max_rmse_threshold_by_std(test_data.target,\n is_strict=True)\n\n assert rmse_test < rmse_threshold\n\n\ndef test_ts_single_pipeline_model_without_multiotput_support():\n time_series = generate_synthetic_data(20)\n len_forecast = 2\n train_part = time_series[:-len_forecast]\n test_part = time_series[-len_forecast:]\n\n task = Task(TaskTypesEnum.ts_forecasting,\n TsForecastingParams(forecast_length=len_forecast))\n\n train_data = InputData(idx=np.arange(0, len(train_part)),\n features=train_part,\n target=train_part,\n task=task,\n data_type=DataTypesEnum.ts)\n\n start_forecast = len(train_part)\n end_forecast = start_forecast + len_forecast\n idx_for_predict = np.arange(start_forecast, end_forecast)\n\n # Data for making prediction for a specific length\n test_data = InputData(idx=idx_for_predict,\n features=train_part,\n target=test_part,\n task=task,\n data_type=DataTypesEnum.ts)\n\n for model_id in ['xgbreg', 'gbr', 'adareg', 'svr', 'sgdr']:\n pipeline = get_simple_ts_pipeline(model_root=model_id, window_size=2)\n\n # making predictions for the missing part in the time series\n pipeline.fit_from_scratch(train_data)\n predicted_values = pipeline.predict(test_data)\n pipeline_forecast = np.ravel(np.array(predicted_values.predict))\n\n test_part = np.ravel(np.array(test_part))\n mae = mean_absolute_error(test_part, pipeline_forecast)\n assert mae < 50\n\n\ndef test_exception_if_incorrect_forecast_length():\n with pytest.raises(ValueError) as exc:\n _, _ = get_synthetic_ts_data_period(forecast_length=0)\n assert str(exc.value) == f'Forecast length should be more then 0'\n\n\ndef test_multistep_out_of_sample_forecasting():\n horizon = 12\n train_data, test_data = get_synthetic_ts_data_period(forecast_length=5)\n\n pipeline = get_multiscale_pipeline()\n\n # Fit pipeline to make forecasts 5 elements above\n pipeline.fit(input_data=train_data)\n\n # Make prediction for 12 elements\n predicted = out_of_sample_ts_forecast(pipeline=pipeline,\n input_data=test_data,\n horizon=horizon)\n\n assert len(predicted) == horizon\n\n\ndef test_multistep_in_sample_forecasting():\n horizon = 12\n train_data, test_data = get_synthetic_ts_data_period(forecast_length=5)\n\n pipeline = get_multiscale_pipeline()\n\n # Fit pipeline to make forecasts 5 elements above\n pipeline.fit(input_data=train_data)\n\n # Make prediction for 12 elements\n predicted = in_sample_ts_forecast(pipeline=pipeline,\n input_data=test_data,\n horizon=horizon)\n\n assert len(predicted) == horizon\n" ]
[ [ "numpy.array" ], [ "numpy.random.seed", "numpy.arange", "sklearn.metrics.mean_absolute_error", "sklearn.metrics.mean_squared_error", "numpy.sin", "numpy.std", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zploskey/Theano
[ "9b3f6351d41d9f5e01b198e3de7538d7f032c409", "1985d4c73fabd5f08f54b922e73a9306e09c77a5" ]
[ "theano/tensor/signal/pool.py", "theano/gof/utils.py" ]
[ "\n\"\"\"\nOps for downsampling images.\nPlanned:\nPool, DownsampleAvg, DownsampleSoftmax.\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\n# This file should move along with conv.py\nimport warnings\nimport itertools\n\nimport numpy as np\nfrom six.moves import xrange\nimport six.moves.builtins as builtins\nimport theano\nfrom theano import gof, OpenMPOp, tensor, Variable, Apply\nfrom theano.gof import ParamsType, EnumList\nfrom theano.gradient import DisconnectedType\nfrom theano.scalar import bool as bool_t\n\n\ndef max_pool_2d_same_size(input, patch_size):\n \"\"\"\n Takes as input a 4-D tensor. It sets all non maximum values\n of non-overlapping patches of size (patch_size[0],patch_size[1]) to zero,\n keeping only the maximum values. The output has the same dimensions as\n the input.\n\n Parameters\n ----------\n input : 4-D theano tensor of input images\n Input images. Max pooling will be done over the 2 last dimensions.\n patch_size : tuple of length 2 or theano vector of ints of size 2.\n Size of the patch (patch height, patch width).\n (2,2) will retain only one non-zero value per patch of 4 values.\n\n \"\"\"\n output = Pool(True)(input, patch_size)\n outs = MaxPoolGrad(True)(input, output, output, patch_size)\n return outs\n\n\ndef pool_2d(input, ws=None, ignore_border=None, stride=None, pad=(0, 0),\n mode='max', ds=None, st=None, padding=None):\n \"\"\"Downscale the input by a specified factor\n\n Takes as input a N-D tensor, where N >= 2. It downscales the input image by\n the specified factor, by keeping only the maximum value of non-overlapping\n patches of size (ws[0],ws[1])\n\n Parameters\n ----------\n input : N-D theano tensor of input images\n Input images. Max pooling will be done over the 2 last dimensions.\n ws : tuple of length 2 or theano vector of ints of size 2.\n Factor by which to downscale (vertical ws, horizontal ws).\n (2,2) will halve the image in each dimension.\n ignore_border : bool (default None, will print a warning and set to False)\n When True, (5,5) input with ws=(2,2) will generate a (2,2) output.\n (3,3) otherwise.\n stride : tuple of two ints or theano vector of ints of size 2.\n Stride size, which is the number of shifts over rows/cols to get the\n next pool region. If stride is None, it is considered equal to ws\n (no overlap on pooling regions), eg: stride=(1,1) will shifts over\n one row and one col for every iteration.\n pad : tuple of two ints or theano vector of ints of size 2.\n (pad_h, pad_w), pad zeros to extend beyond four borders of the\n images, pad_h is the size of the top and bottom margins, and\n pad_w is the size of the left and right margins.\n mode : {'max', 'sum', 'average_inc_pad', 'average_exc_pad'}\n Operation executed on each window. `max` and `sum` always exclude\n the padding in the computation. `average` gives you the choice to\n include or exclude it.\n ds\n *deprecated*, use parameter ws instead.\n st\n *deprecated*, use parameter stride instead.\n padding\n *deprecated*, use parameter pad instead.\n\n \"\"\"\n # check for deprecated parameter names\n if ds is not None:\n if ws is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'ws' and 'ds'.\"\n \" Please provide a value only to 'ws'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'ds' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'ws'.\",\n stacklevel=2\n )\n ws = ds\n elif ds is None and ws is None:\n raise ValueError(\n \"You must provide a tuple value for the window size.\"\n )\n\n if st is not None:\n if stride is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'st and 'stride'.\"\n \" Please provide a value only to 'stride'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'st' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'stride'.\",\n stacklevel=2\n )\n stride = st\n\n if padding is not None:\n if pad not in {None, (0, 0)}:\n raise ValueError(\n \"You can't provide a tuple value to both 'padding' and pad.\"\n \" Please provide a value only to pad.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'padding' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'pad'.\",\n stacklevel=2\n )\n pad = padding\n\n if input.ndim < 2:\n raise NotImplementedError('pool_2d requires a dimension >= 2')\n if ignore_border is None:\n warnings.warn(\n \"pool_2d() will have the parameter ignore_border\"\n \" default value changed to True (currently\"\n \" False). To have consistent behavior with all Theano\"\n \" version, explicitly add the parameter ignore_border=True.\"\n \" On the GPU, using ignore_border=True is needed to use cuDNN.\"\n \" When using ignore_border=False and not using cuDNN, the only\"\n \" GPU combination supported is when\"\n \" `ws == stride and pad == (0, 0) and mode == 'max'`.\"\n \" Otherwise, the convolution will be executed on CPU.\",\n stacklevel=2)\n ignore_border = False\n op = Pool(ignore_border, ndim=2, mode=mode)\n output = op(input, ws, stride, pad)\n return output\n\n\ndef pool_3d(input, ws=None, ignore_border=None, stride=None, pad=(0, 0, 0),\n mode='max', ds=None, st=None, padding=None):\n \"\"\"Downscale the input by a specified factor\n\n Takes as input a N-D tensor, where N >= 3. It downscales the input image by\n the specified factor, by keeping only the maximum value of non-overlapping\n patches of size (ws[0],ws[1],ws[2])\n\n Parameters\n ----------\n input : N-D theano tensor of input images\n Input images. Max pooling will be done over the 3 last dimensions.\n ws : tuple of length 3 or theano vector of ints of size 3\n Factor by which to downscale (vertical ws, horizontal ws, depth ws).\n (2,2,2) will halve the image in each dimension.\n ignore_border : bool (default None, will print a warning and set to False)\n When True, (5,5,5) input with ws=(2,2,2) will generate a (2,2,2) output.\n (3,3,3) otherwise.\n st : tuple of three ints or theano vector of ints of size 3\n Stride size, which is the number of shifts over rows/cols/slices to get\n the next pool region. If st is None, it is considered equal to ws\n (no overlap on pooling regions).\n pad : tuple of two ints or theano vector of ints of size 3\n (pad_h, pad_w, pad_d), pad zeros to extend beyond six borders of the\n images, pad_h is the size of the top and bottom margins,\n pad_w is the size of the left and right margins, and pad_d is the size\n of the front and back margins\n mode : {'max', 'sum', 'average_inc_pad', 'average_exc_pad'}\n Operation executed on each window. `max` and `sum` always exclude\n the padding in the computation. `average` gives you the choice to\n include or exclude it.\n ds\n *deprecated*, use parameter ws instead.\n st\n *deprecated*, use parameter st instead.\n padding\n *deprecated*, use parameter pad instead.\n\n \"\"\"\n # check for deprecated parameter names\n if ds is not None:\n if ws is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'ws' and 'ds'.\"\n \" Please provide a value only to 'ws'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'ds' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'ws'.\",\n stacklevel=2\n )\n ws = ds\n elif ds is None and ws is None:\n raise ValueError(\n \"You must provide a tuple value for the window size.\"\n )\n\n if st is not None:\n if stride is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'st and 'stride'.\"\n \" Please provide a value only to 'stride'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'st' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'stride'.\",\n stacklevel=2\n )\n stride = st\n\n if padding is not None:\n if pad not in {None, (0, 0, 0)}:\n raise ValueError(\n \"You can't provide a tuple value to both 'padding' and pad.\"\n \" Please provide a value only to pad.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'padding' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'pad'.\",\n stacklevel=2\n )\n pad = padding\n\n if input.ndim < 3:\n raise NotImplementedError('pool_3d requires a dimension >= 3')\n if ignore_border is None:\n warnings.warn(\n \"pool_3d() will have the parameter ignore_border\"\n \" default value changed to True (currently\"\n \" False). To have consistent behavior with all Theano\"\n \" version, explicitly add the parameter ignore_border=True.\"\n \" On the GPU, using ignore_border=True is needed to use cuDNN.\"\n \" When using ignore_border=False and not using cuDNN, the only\"\n \" GPU combination supported is when\"\n \" `ws == stride and pad == (0, 0, 0) and mode == 'max'`.\"\n \" Otherwise, the convolution will be executed on CPU.\",\n stacklevel=2)\n ignore_border = False\n op = Pool(ignore_border, ndim=3, mode=mode)\n output = op(input, ws, stride, pad)\n return output\n\n\n# NB: This enum type is currently used in gpuarray/pool.py.\n# It may be used later as op param in this current file.\n# Enum name and constants names are inspired from cuDNN type `cudnnPoolingMode_t`\n# (cf. `theano/gpuarray/cudnn_defs.py`).\nPoolingMode_t = EnumList(('POOLING_MAX', 'max'),\n ('POOLING_SUM', 'sum'),\n ('POOLING_AVERAGE_COUNT_INCLUDE_PADDING', 'average_inc_pad'),\n ('POOLING_AVERAGE_COUNT_EXCLUDE_PADDING', 'average_exc_pad'))\n\n\nclass Pool(OpenMPOp):\n \"\"\"\n sum or average over different patches.\n\n Parameters\n ----------\n ws : list or tuple of N ints\n Downsample factor over rows, columns etc.\n ws indicates the size of the pooling region.\n ignore_border : bool\n If ws doesn't divide imgshape, do we include an extra row/col/slice\n of partial downsampling (False) or ignore it (True).\n stride : list or tuple of N ints or None\n Stride size, which is the number of shifts over rows/cols/slices to get the\n next pool region. If stride is None, it is considered equal to ws\n (no overlap on pooling regions).\n pad : tuple of N ints or None\n For each downsampling dimension, this specifies the number of zeros to\n add as padding on both sides. For 2D and (pad_h, pad_w), pad_h specifies the\n size of the top and bottom margins, pad_w specifies the size of the left and\n right margins. No padding is added if pad is None.\n mode : {'max', 'sum', 'average_inc_pad', 'average_exc_pad'}\n ('average_inc_pad' excludes the padding from the count,\n 'average_exc_pad' include it)\n ndim : int\n The number of pooling dimensions N.\n The default is 2.\n ds\n *deprecated*, use parameter ws instead.\n st\n *deprecated*, use parameter st instead.\n padding\n *deprecated*, use parameter pad instead.\n\n\n \"\"\"\n\n __props__ = ('ignore_border', 'mode', 'ndim')\n params_type = ParamsType(ignore_border=bool_t,)\n\n @staticmethod\n def out_shape(imgshape, ws=None, ignore_border=False, stride=None, pad=None,\n ndim=2, ds=None, st=None, padding=None):\n \"\"\"\n Return the shape of the output from this op, for input of given\n shape and flags.\n\n Parameters\n ----------\n imgshape : tuple, list, or similar of integer or scalar Theano variable\n The shape of a tensor of images. The last N elements are\n interpreted as the number of rows, and the number of cols.\n ws : list or tuple of N ints\n Downsample factor over rows and column.\n ws indicates the pool region size.\n ignore_border : bool\n If ws doesn't divide imgshape, do we include an extra row/col/slice\n of partial downsampling (False) or ignore it (True).\n stride : list or tuple of N ints or None\n Stride size, which is the number of shifts over rows/cols/slices to get the\n next pool region. If stride is None, it is considered equal to ws\n (no overlap on pooling regions).\n pad : tuple of N ints or None\n For each downsampling dimension, this specifies the number of zeros to\n add as padding on both sides. For 2D and (pad_h, pad_w), pad_h specifies the\n size of the top and bottom margins, pad_w specifies the size of the left and\n right margins. No padding is added if pad is None.\n ndim : int\n The number of pooling dimensions N.\n The default is 2.\n ds\n *deprecated*, use parameter ws instead.\n st\n *deprecated*, use parameter st instead.\n padding\n *deprecated*, use parameter pad instead.\n\n Returns\n -------\n list\n The shape of the output from this op, for input of given shape.\n This will have the same length as imgshape, but with last N\n elements reduced as per the downsampling & ignore_border flags.\n\n \"\"\"\n # check for deprecated parameter names\n if ds is not None:\n if ws is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'ws' and 'ds'.\"\n \" Please provide a value only to 'ws'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'ds' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'ws'.\",\n stacklevel=2\n )\n ws = ds\n elif ds is None and ws is None:\n raise ValueError(\n \"You must provide a tuple value for the window size.\"\n )\n\n if st is not None:\n if stride is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'st and 'stride'.\"\n \" Please provide a value only to 'stride'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'st' parameter is not going to exist\"\n \" anymore as it is going to be replaced by the parameter\"\n \" 'stride'.\",\n stacklevel=2\n )\n stride = st\n\n if padding is not None:\n zero_pad = (0,) * ndim\n if pad not in {None, zero_pad}:\n raise ValueError(\n \"You can't provide a tuple value to both 'padding' and pad.\"\n \" Please provide a value only to pad.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'padding' parameter is not going to\"\n \" exist anymore as it is going to be replaced by the\"\n \" parameter 'pad'.\",\n stacklevel=2\n )\n pad = padding\n\n if ndim is None:\n ndim = 2\n assert ndim > 0\n if len(imgshape) < ndim:\n raise TypeError('imgshape must have at least {} dimensions'.format(ndim))\n\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * ndim\n patch_shape = tuple(tensor.extract_constant(imgshape[-ndim + i]) + pad[i] * 2\n for i in xrange(ndim))\n\n def compute_out(v, downsample, stride):\n if ignore_border:\n if downsample == stride:\n return v // stride\n else:\n out = (v - downsample) // stride + 1\n if isinstance(out, theano.Variable):\n return tensor.maximum(out, 0)\n else:\n return np.maximum(out, 0)\n else:\n if isinstance(v, theano.Variable):\n return tensor.switch(tensor.ge(stride, downsample),\n (v - 1) // stride + 1,\n tensor.maximum(0, (v - 1 - downsample) //\n stride + 1) + 1)\n elif stride >= downsample:\n return (v - 1) // stride + 1\n else:\n return max(0, (v - 1 - downsample + stride) // stride) + 1\n\n out_shape = [compute_out(patch_shape[i], ws[i], stride[i]) for i in xrange(ndim)]\n\n rval = list(imgshape[:-ndim]) + out_shape\n return rval\n\n def __init__(self, ignore_border=False, mode='max', ndim=2, openmp=None):\n super(Pool, self).__init__(openmp=openmp)\n self.ndim = ndim\n self.ignore_border = ignore_border\n if mode == 'max_deterministic':\n # It seems max pool algo is already deterministic in CPU.\n mode = 'max'\n if mode not in ['max', 'average_inc_pad', 'average_exc_pad', 'sum']:\n raise ValueError(\n \"Pool mode parameter only support 'max', 'sum',\"\n \" 'average_inc_pad' and 'average_exc_pad'. Got %s\" % mode)\n self.mode = mode\n\n def prepare_node(self, node, storage_map, compute_map, impl):\n if len(node.inputs) == 1:\n # Old interface\n self.ndim = len(node.op.ds)\n self.mode = node.op.mode\n ws = theano.tensor.constant(node.op.ds)\n st = theano.tensor.constant(node.op.st)\n pad = theano.tensor.constant(node.op.padding)\n node.inputs.append(ws)\n node.inputs.append(st)\n node.inputs.append(pad)\n if isinstance(ws, theano.Constant):\n storage_map[ws] = [ws.data]\n compute_map[ws] = [True]\n else:\n storage_map[ws] = [None]\n compute_map[ws] = [False]\n if isinstance(st, theano.Constant):\n storage_map[st] = [st.data]\n compute_map[st] = [True]\n else:\n storage_map[st] = [None]\n compute_map[st] = [False]\n if isinstance(pad, theano.Constant):\n storage_map[pad] = [pad.data]\n compute_map[pad] = [True]\n else:\n storage_map[pad] = [None]\n compute_map[pad] = [False]\n\n def make_node(self, x, ws, stride=None, pad=None):\n # TODO: consider restricting the dtype?\n x = tensor.as_tensor_variable(x)\n nd = self.ndim\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * nd\n elif isinstance(pad, (tuple, list)):\n if max(pad) != 0 and not self.ignore_border:\n raise NotImplementedError(\n 'padding works only with ignore_border=True')\n if isinstance(ws, (tuple, list)):\n if any(pad[i] >= ws[i] for i in range(nd)):\n raise NotImplementedError(\n 'padding must be smaller than strides')\n ws = tensor.as_tensor_variable(ws)\n stride = tensor.as_tensor_variable(stride)\n pad = tensor.as_tensor_variable(pad)\n assert ws.ndim == 1\n assert stride.ndim == 1\n assert pad.ndim == 1\n if x.type.ndim < nd:\n raise TypeError()\n if ws.dtype not in tensor.int_dtypes:\n raise TypeError('Pool downsample parameters must be ints.')\n if stride.dtype not in tensor.int_dtypes:\n raise TypeError('Stride parameters must be ints.')\n if pad.dtype not in tensor.int_dtypes:\n raise TypeError('Padding parameters must be ints.')\n # If the input shape are broadcastable we can have 0 in the output shape\n broad = x.broadcastable[:-nd] + (False,) * nd\n out = tensor.TensorType(x.dtype, broad)\n return gof.Apply(self, [x, ws, stride, pad], [out()])\n\n def perform(self, node, inp, out, params):\n x, ws, stride, pad = inp\n z, = out\n nd = self.ndim\n assert ws.shape == stride.shape == pad.shape == (nd,)\n if len(x.shape) < nd:\n raise NotImplementedError(\n 'Pool requires input with {} or more dimensions'.format(nd))\n z_shape = self.out_shape(x.shape, ws, params.ignore_border, stride, pad, nd)\n if not params.ignore_border:\n assert all(z > 0 for z in z_shape[-nd:])\n if (z[0] is None) or (z[0].shape != z_shape):\n z[0] = np.empty(z_shape, dtype=x.dtype)\n zz = z[0]\n # size of pooling output\n pool_out_shp = zz.shape[-nd:]\n img_shp = tuple(x.shape[-nd + i] + 2 * pad[i] for i in xrange(nd))\n inc_pad = self.mode == 'average_inc_pad'\n\n # pad the image\n if max(pad) != 0:\n y = np.zeros(x.shape[:-nd] + img_shp, dtype=x.dtype)\n y[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = x\n else:\n y = x\n func = np.max\n if self.mode == 'sum':\n func = np.sum\n elif self.mode != 'max':\n func = np.average\n\n # precompute the region boundaries for each dimension\n region_slices = [[] for i in xrange(nd)]\n for i in xrange(nd):\n for j in xrange(pool_out_shp[i]):\n start = j * stride[i]\n end = builtins.min(start + ws[i], img_shp[i])\n if not inc_pad:\n start = builtins.max(start, pad[i])\n end = builtins.min(end, img_shp[i] - pad[i])\n region_slices[i].append(slice(start, end))\n\n # iterate over non-pooling dimensions\n for k in np.ndindex(*x.shape[:-nd]):\n zzk = zz[k]\n yk = y[k]\n # iterate over pooling regions\n for r in np.ndindex(*pool_out_shp):\n zzk[r] = func(\n yk[[region_slices[i][r[i]] for i in xrange(nd)]])\n\n def infer_shape(self, node, in_shapes):\n ws, stride, pad = [node.inputs[1], node.inputs[2], node.inputs[3]]\n shp = self.out_shape(in_shapes[0], ws, self.ignore_border, stride,\n pad, self.ndim)\n return [shp]\n\n def L_op(self, inputs, outputs, grads):\n x, ws, stride, pad = inputs\n gz, = grads\n disc = [DisconnectedType()() for i in inputs[1:]]\n if self.mode == 'max':\n return [MaxPoolGrad(ndim=self.ndim,\n ignore_border=self.ignore_border)(\n x, outputs[0], gz, ws=ws, stride=stride, pad=pad)] + disc\n else:\n return [AveragePoolGrad(ndim=self.ndim,\n ignore_border=self.ignore_border,\n mode=self.mode)(\n x, gz, ws=ws, stride=stride, pad=pad)] + disc\n\n def connection_pattern(self, node):\n return [[1], [0], [0], [0]]\n\n def R_op(self, inputs, eval_points):\n if self.mode != 'max':\n # Rop for average or sum is simply pooling evaluated at eval point\n eval_inputs = [eval_points[0]] + inputs[1:]\n return [self(*eval_inputs)]\n\n # R_op can receive None as eval_points.\n # That mean there is no diferientiable path through that input\n # If this imply that you cannot compute some outputs,\n # return None for those.\n if eval_points[0] is None:\n return [None]\n z = self(*inputs)\n x, ws, stride, pad = inputs\n return [\n DownsampleFactorMaxGradGrad(self.ignore_border, self.mode,\n self.ndim)(x, z, eval_points[0], ws,\n stride, pad)\n ]\n\n def c_headers(self):\n headers = ['<algorithm>']\n headers += super(Pool, self).c_headers()\n return headers\n\n def c_code(self, node, name, inp, out, sub):\n if self.mode not in ('max', 'sum', 'average_exc_pad', 'average_inc_pad'):\n raise theano.gof.utils.MethodNotDefined()\n x, ws, stride, pad = inp\n z, = out\n nd = self.ndim\n total_ndim = node.inputs[0].ndim\n non_pool_ndim = total_ndim - nd\n fail = sub['fail']\n params = sub['params']\n if self.openmp:\n # run in parallel over each pooling block\n omp_parallel = '#pragma omp parallel for private(r_st, r_end, r_idx, i_idx, o_idx, collector) schedule(static)'\n else:\n omp_parallel = ''\n ccode = \"\"\"\n int typenum = PyArray_ObjectType((PyObject*)%(x)s, 0);\n if(PyArray_NDIM(%(x)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"x must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_DIM(%(ws)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"ws must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(stride)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"stride must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(pad)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"pad must be a vector of size %(nd)s\");\n %(fail)s;\n }\n int z[%(nd)s]; // shape of the output\n int r[%(nd)s]; // shape of the padded_input\n int ws[%(nd)s];\n int st[%(nd)s];\n int pd[%(nd)s];\n int nonzero_padding;\n nonzero_padding = 0;\n for (int i=0; i<%(nd)s; i++)\n {\n ws[i] = *((npy_intp*)PyArray_GETPTR1(%(ws)s, i));\n st[i] = *((npy_intp*)PyArray_GETPTR1(%(stride)s, i));\n pd[i] = *((npy_intp*)PyArray_GETPTR1(%(pad)s, i));\n r[i] = PyArray_DIMS(%(x)s)[%(non_pool_ndim)s + i] + 2 * pd[i];\n if (pd[i]>0)\n nonzero_padding = 1;\n }\n if (!%(params)s->ignore_border && nonzero_padding)\n {\n PyErr_SetString(PyExc_ValueError,\n \"padding must be zero when ignore border is False\");\n %(fail)s;\n }\n if (%(params)s->ignore_border)\n {\n for (int i=0; i<%(nd)s; i++)\n {\n // '/' in C is different from '/' in python\n if (r[i] - ws[i] < 0)\n {\n z[i] = 0;\n }\n else\n {\n z[i] = (r[i] - ws[i]) / st[i] + 1;\n }\n }\n }\n else\n {\n for (int i=0; i<%(nd)s; i++)\n {\n // decide how many rows/cols the output has\n if (st[i] >= ws[i])\n {\n z[i] = (r[i] - 1) / st[i] + 1;\n }\n else\n {\n z[i] = std::max(0, (r[i] - 1 - ws[i] + st[i]) / st[i]) + 1;\n }\n assert(z[i] > 0);\n }\n }\n // memory allocation of z if necessary\n int mem_nec;\n mem_nec = 0;\n if ((!%(z)s) || *PyArray_DIMS(%(z)s)!=%(total_ndim)s)\n {\n mem_nec = 1;\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n if (PyArray_DIMS(%(z)s)[i] != PyArray_DIMS(%(x)s)[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(nd)s; i++)\n {\n if (PyArray_DIMS(%(z)s)[%(non_pool_ndim)s + i] != z[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (mem_nec)\n {\n if (%(z)s) Py_XDECREF(%(z)s);\n npy_intp dims[%(total_ndim)s];\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n dims[i] = PyArray_DIMS(%(x)s)[i];\n }\n for (int i=0; i<%(nd)s; i++)\n {\n dims[%(non_pool_ndim)s + i] = z[i];\n }\n //TODO: zeros not necessary\n %(z)s = (PyArrayObject*) PyArray_ZEROS(%(total_ndim)s, dims, typenum,0);\n }\n // initialize temp var for the value in a region\n dtype_%(x)s collector;\n int z_prod;\n // do not run if any z[i] is zero\n z_prod = 1;\n for (int i=0; i<%(nd)s; i++)\n {\n z_prod *= z[i];\n }\n if (z_prod)\n {\n // will be used to hold start and end index of a region\n int r_st[%(nd)s];\n int r_end[%(nd)s];\n // index for iterating over the pooling regions\n int r_idx[%(nd)s];\n // placeholder for PyArray indexing (output)\n npy_intp o_idx[%(total_ndim)s];\n // placeholder for PyArray indexing (input)\n npy_intp i_idx[%(total_ndim)s];\n // loop over non-pooling dimensions\n int non_pooling_prod = 1;\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n non_pooling_prod *= PyArray_DIMS(%(x)s)[i];\n }\n %(omp_parallel)s\n // first loop over non-pooling dimensions\n for (int t=0; t<non_pooling_prod; t++)\n {\n // compute the non-pooling index in each dimension\n if (%(non_pool_ndim)s!=0)\n {\n o_idx[0] = t;\n i_idx[0] = t;\n for (int i=1; i<%(non_pool_ndim)s; i++)\n {\n o_idx[i] = o_idx[i - 1] / PyArray_DIMS(%(x)s)[i - 1];\n o_idx[i - 1] = o_idx[i - 1] %% PyArray_DIMS(%(x)s)[i - 1];\n i_idx[i] = o_idx[i];\n i_idx[i - 1] = o_idx[i - 1];\n }\n }\n\n // then loop over each region in each pooling dimension\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n for (r_idx[%(i)s]=0; r_idx[%(i)s] < z[%(i)s]; r_idx[%(i)s]++) {\n r_st[%(i)s] = r_idx[%(i)s] * st[%(i)s];\n r_end[%(i)s] = r_st[%(i)s] + ws[%(i)s];\n // skip the padding\n r_st[%(i)s] = r_st[%(i)s] < pd[%(i)s] ? pd[%(i)s] : r_st[%(i)s];\n r_end[%(i)s] = r_end[%(i)s] > (r[%(i)s] - pd[%(i)s]) ? r[%(i)s] - pd[%(i)s] : r_end[%(i)s];\n // from padded_img space to img space\n r_st[%(i)s] -= pd[%(i)s];\n r_end[%(i)s] -= pd[%(i)s];\n // handle the case where no padding, ignore border is True\n if (%(params)s->ignore_border)\n {\n r_end[%(i)s] = r_end[%(i)s] > r[%(i)s] ? r[%(i)s] : r_end[%(i)s];\n }\n // use the index to find the correct position in the output\n o_idx[%(non_pool_ndim)s + %(i)s] = r_idx[%(i)s];\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim, params=sub['params'])\n\n ccode += \"\"\"\n // get a pointer to the correct position in the output\n dtype_%(z)s * z;\n if (%(total_ndim)s == 4)\n z = ((dtype_%(z)s*)(PyArray_GETPTR4(%(z)s, o_idx[0], o_idx[1], o_idx[2], o_idx[3])));\n else\n z = ((dtype_%(z)s*)(PyArray_GetPtr(%(z)s, o_idx)));\n \"\"\"\n\n if self.mode == 'max':\n for i in xrange(nd):\n ccode += \"\"\"\n // set the first index of dimension %(i)s\n i_idx[%(non_pool_ndim)s + %(i)s] = r_st[%(i)s];\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n // use the first element as the initial value of collector\n if (%(total_ndim)s == 4)\n collector = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n else\n collector = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n // update maximum\n dtype_%(x)s a;\n if (%(total_ndim)s == 4)\n a = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n else\n a = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n collector = (a > collector) ? a : collector;\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n ccode += \"\"\"\n z[0] = collector;\n \"\"\"\n elif self.mode in ('sum', 'average_exc_pad', 'average_inc_pad'):\n ccode += \"\"\"\n // initialize the sum at zero\n collector = ((dtype_%(x)s)(0));\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n // update sum\n dtype_%(x)s a;\n if (%(total_ndim)s == 4)\n a = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n else\n a = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n collector += a;\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n if self.mode == \"sum\":\n ccode += \"\"\"\n z[0] = collector;\n \"\"\"\n elif self.mode == 'average_inc_pad' and self.ignore_border:\n # region size = product over all pooling dimensions\n region_size = ' * '.join('ws[%d]' % i for i in xrange(nd))\n ccode += \"\"\"\n z[0] = collector / (%(region_size)s);\n \"\"\" % dict(region_size=region_size)\n else:\n # region size = number elements of in this region\n region_size = ' * '.join('(r_end[%d]-r_st[%d])' % (i, i) for i in xrange(nd))\n ccode += \"\"\"\n z[0] = collector / (%(region_size)s);\n \"\"\" % dict(region_size=region_size)\n for i in xrange(nd):\n ccode += \"\"\"\n } // loop over pooling dimension\n \"\"\"\n\n ccode += \"\"\"\n } // for loop over non-pooling dimensions\n } // if z_prod\n \"\"\"\n return ccode % locals()\n\n def c_code_cache_version(self):\n return (9, self.openmp)\n\n\nclass PoolGrad(OpenMPOp):\n __props__ = ('ignore_border', 'mode', 'ndim')\n\n @staticmethod\n def out_shape(imgshape, ws=None, ignore_border=False, stride=None, pad=None, ndim=2,\n ds=None, st=None, padding=None):\n \"\"\"Return the shape of the output from this op, for input of given\n shape and flags.\n\n Parameters\n ----------\n imgshape : tuple of integers or scalar Theano variables\n the shape of a tensor of images. The last N elements are\n interpreted as the downsampling dimensions.\n ws : tuple of N ints\n downsample factor over rows and columns this parameter\n indicates the size of the pooling region\n ignore_border : bool\n If ws doesn't divide imgshape, do we include an extra row/col/slice\n of partial downsampling (False) or ignore it (True).\n stride : list or tuple of N ints or None\n Stride size, which is the number of shifts over rows/cols/slices to get the\n next pool region. If stride is None, it is considered equal to ws\n (no overlap on pooling regions).\n pad : tuple of N ints or None\n For each downsampling dimension, this specifies the number of zeros to\n add as padding on both sides. For 2D and (pad_h, pad_w), pad_h specifies the\n size of the top and bottom margins, pad_w specifies the size of the left and\n right margins. No padding is added if pad is None.\n ndim : int\n The number of pooling dimensions N.\n The default is 2.\n ds\n *deprecated*, use parameter ws instead.\n st\n *deprecated*, use parameter st instead.\n padding\n *deprecated*, use parameter pad instead.\n\n Returns\n -------\n list :\n the shape of the output from this op, for input of given\n shape. This will have the same length as imgshape, but\n with last N elements reduced as per the downsampling &\n ignore_border flags.\n\n \"\"\"\n # check for deprecated parameter names\n if ds is not None:\n if ws is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'ws' and 'ds'.\"\n \" Please provide a value only to 'ws'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'ds' parameter in PoolGrad is not going\"\n \" to exist anymore as it is going to be replaced by the\"\n \" parameter 'ws'.\",\n stacklevel=2\n )\n ws = ds\n elif ds is None and ws is None:\n raise ValueError(\n \"You must provide a tuple value for the window size.\"\n )\n\n if st is not None:\n if stride is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'st and 'stride'.\"\n \" Please provide a value only to 'stride'.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'st' parameter in PoolGrad is not going\"\n \" to exist anymore as it is going to be replaced by the\"\n \" parameter 'stride'.\",\n stacklevel=2\n )\n stride = st\n\n if padding is not None:\n if pad is not None:\n raise ValueError(\n \"You can't provide a tuple value to both 'padding' and pad.\"\n \" Please provide a value only to pad.\"\n )\n else:\n warnings.warn(\n \"DEPRECATION: the 'padding' parameter in PoolGrad is not\"\n \" going to exist anymore as it is going to be replaced\"\n \" by the parameter 'pad'.\",\n stacklevel=2\n )\n pad = padding\n\n if len(imgshape) < ndim:\n raise TypeError('imgshape must have at least {} dimensions'.format(ndim))\n\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * ndim\n patch_shape = tuple(tensor.extract_constant(imgshape[-ndim + i]) + pad[i] * 2\n for i in xrange(ndim))\n\n def compute_out(v, downsample, stride):\n if ignore_border:\n out = (v - downsample) // stride + 1\n if isinstance(out, theano.Variable):\n return tensor.maximum(out, 0)\n else:\n return np.maximum(out, 0)\n else:\n if isinstance(v, theano.Variable):\n return tensor.switch(tensor.ge(stride, downsample),\n (v - 1) // stride + 1,\n tensor.maximum(0, (v - 1 - downsample) //\n stride + 1) + 1)\n elif stride >= downsample:\n return (v - 1) // stride + 1\n else:\n return max(0, (v - 1 - downsample) // stride + 1) + 1\n\n out_shape = [compute_out(patch_shape[i], ws[i], stride[i]) for i in xrange(ndim)]\n\n rval = list(imgshape[:-ndim]) + out_shape\n return rval\n\n def __init__(self, ignore_border, mode='max', ndim=2, openmp=None):\n self.ndim = ndim\n self.ignore_border = ignore_border\n if mode == 'max_deterministic':\n # It seems max pool grad algo is already deterministic in CPU.\n mode = 'max'\n if mode not in ['max', 'sum', 'average_inc_pad', 'average_exc_pad']:\n raise ValueError(\n \"Pool mode parameter only support 'max', 'sum',\"\n \" 'average_inc_pad' and 'average_exc_pad'. Got %s\" % mode)\n self.mode = mode\n super(PoolGrad, self).__init__(openmp=openmp)\n\n def prepare_node(self, node, storage_map, compute_map, impl):\n if len(node.inputs) < 5: # 5 for AveragePoolGrad, 6 for MaxPoolGrad\n # Old interface\n self.ndim = len(node.op.ds)\n self.mode = node.op.mode\n ws = theano.tensor.constant(node.op.ds)\n st = theano.tensor.constant(node.op.st)\n pad = theano.tensor.constant(node.op.padding)\n node.inputs.append(ws)\n node.inputs.append(st)\n node.inputs.append(pad)\n if isinstance(ws, theano.Constant):\n storage_map[ws] = [ws.data]\n compute_map[ws] = [True]\n else:\n storage_map[ws] = [None]\n compute_map[ws] = [False]\n if isinstance(st, theano.Constant):\n storage_map[st] = [st.data]\n compute_map[st] = [True]\n else:\n storage_map[st] = [None]\n compute_map[st] = [False]\n if isinstance(pad, theano.Constant):\n storage_map[pad] = [pad.data]\n compute_map[pad] = [True]\n else:\n storage_map[pad] = [None]\n compute_map[pad] = [False]\n\n def infer_shape(self, node, in_shapes):\n return [in_shapes[0]]\n\n\nclass MaxPoolGrad(PoolGrad):\n # params_type ignore_border don't change c code\n\n def __init__(self, ignore_border, ndim=2, openmp=None):\n PoolGrad.__init__(self, ignore_border, mode='max', ndim=ndim, openmp=openmp)\n\n def make_node(self, x, maxout, gz, ws, stride=None, pad=None):\n # make_node should only be called by the grad function of\n # Pool, so these asserts should not fail.\n x = tensor.as_tensor_variable(x)\n maxout = tensor.as_tensor_variable(maxout)\n gz = tensor.as_tensor_variable(gz)\n nd = self.ndim\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * nd\n ws = tensor.as_tensor_variable(ws)\n stride = tensor.as_tensor_variable(stride)\n pad = tensor.as_tensor_variable(pad)\n assert isinstance(x, Variable) and x.ndim >= nd\n assert isinstance(maxout, Variable) and maxout.ndim >= nd\n assert isinstance(gz, Variable) and gz.ndim >= nd\n assert isinstance(ws, Variable) and ws.ndim == 1\n assert isinstance(stride, Variable) and stride.ndim == 1\n assert isinstance(pad, Variable) and pad.ndim == 1\n assert x.ndim == maxout.ndim == gz.ndim >= nd\n if ws.dtype not in tensor.int_dtypes:\n raise TypeError('Pool downsample parameters must be ints.')\n if stride.dtype not in tensor.int_dtypes:\n raise TypeError('Stride parameters must be ints.')\n if pad.dtype not in tensor.int_dtypes:\n raise TypeError('Padding parameters must be ints.')\n return Apply(self, [x, maxout, gz, ws, stride, pad], [x.type()])\n\n def perform(self, node, inp, out):\n assert self.mode == 'max'\n x, maxout, gz, ws, stride, pad = inp\n gx_stg, = out\n nd = self.ndim\n assert ws.shape == stride.shape == pad.shape == (nd,)\n if len(x.shape) < nd:\n raise NotImplementedError(\n 'MaxPoolGrad requires input with {} or more dimensions'.format(nd))\n pool_out_shp = maxout.shape[-nd:]\n img_shp = tuple(x.shape[-nd + i] + 2 * pad[i] for i in xrange(nd))\n\n # pad the image\n if max(pad) != 0:\n y = np.zeros(x.shape[:-nd] + img_shp, dtype=x.dtype)\n y[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = x\n else:\n y = x\n gx = np.zeros_like(y)\n\n # precompute the region boundaries for each dimension\n region_ranges = [[] for i in xrange(nd)]\n for i in xrange(nd):\n for j in xrange(pool_out_shp[i]):\n start = builtins.max(j * stride[i], pad[i])\n end = builtins.min(start + ws[i], img_shp[i])\n region_ranges[i].append(xrange(start, end))\n\n # iterate over non-pooling dimensions\n for k in np.ndindex(*x.shape[:-nd]):\n gxk = gx[k]\n gzk = gz[k]\n yk = y[k]\n maxoutk = maxout[k]\n # iterate over pooling regions\n for r in np.ndindex(*pool_out_shp):\n maxout_value = maxoutk[r]\n # iterate inside region\n for c in itertools.product(*[region_ranges[i][r[i]]\n for i in xrange(nd)]):\n if maxout_value == yk[c]:\n gxk[c] += gzk[r]\n\n # unpad the image\n gx = gx[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))]\n gx_stg[0] = gx\n\n def grad(self, inp, grads):\n x, maxout, gz, ws, stride, pad = inp\n ggx, = grads\n return ([theano.tensor.zeros_like(x),\n theano.tensor.zeros_like(maxout),\n DownsampleFactorMaxGradGrad(ndim=self.ndim,\n ignore_border=self.ignore_border)(\n x, maxout, ggx, ws, stride, pad)] +\n [DisconnectedType()() for i in inp[3:]])\n\n def connection_pattern(self, node):\n return [[1], [1], [1], [0], [0], [0]]\n\n def c_code(self, node, name, inp, out, sub):\n assert self.mode == 'max'\n x, z, gz, ws, stride, pad = inp\n gx, = out\n nd = self.ndim\n total_ndim = node.inputs[0].ndim\n non_pool_ndim = total_ndim - nd\n fail = sub['fail']\n\n if self.openmp:\n # run in parallel over each pooling block\n omp_parallel = '#pragma omp parallel for private(r_st, r_end, r_idx, i_idx, o_idx, maximum) schedule(static)'\n else:\n omp_parallel = ''\n\n ccode = \"\"\"\n // sanity checks\n int x_typenum = PyArray_ObjectType((PyObject*)%(x)s, 0);\n int z_typenum = PyArray_ObjectType((PyObject*)%(z)s, 0);\n int gz_typenum = PyArray_ObjectType((PyObject*)%(gz)s, 0);\n if ((x_typenum != z_typenum) || (x_typenum != gz_typenum))\n {\n PyErr_SetString(PyExc_ValueError, \"input types must all match\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(x)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"x must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(z)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"z must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(gz)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"gz must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_DIM(%(ws)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"ws must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(stride)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"stride must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(pad)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"pad must be a vector of size %(nd)s\");\n %(fail)s;\n }\n int z[%(nd)s]; // shape of the output\n int r[%(nd)s]; // shape of the padded_input\n int ws[%(nd)s];\n int st[%(nd)s];\n int pd[%(nd)s];\n int nonzero_padding;\n nonzero_padding = 0;\n for (int i=0; i<%(nd)s; i++)\n {\n ws[i] = *((npy_intp*)PyArray_GETPTR1(%(ws)s, i));\n st[i] = *((npy_intp*)PyArray_GETPTR1(%(stride)s, i));\n pd[i] = *((npy_intp*)PyArray_GETPTR1(%(pad)s, i));\n z[i] = PyArray_DIMS(%(z)s)[%(non_pool_ndim)s + i];\n r[i] = PyArray_DIMS(%(x)s)[%(non_pool_ndim)s + i] + 2 * pd[i];\n if (pd[i]>0)\n nonzero_padding = 1;\n }\n // allocating memory for output, if necessary\n int mem_nec;\n mem_nec = 0;\n if ((!%(gx)s) || !PyArray_ISCONTIGUOUS(%(gx)s)\n || *PyArray_DIMS(%(gx)s)!=%(total_ndim)s)\n {\n mem_nec = 1;\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(total_ndim)s; i++)\n {\n if (PyArray_DIMS(%(gx)s)[i] != PyArray_DIMS(%(x)s)[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (mem_nec)\n {\n Py_XDECREF(%(gx)s);\n %(gx)s = (PyArrayObject*) PyArray_ZEROS(%(total_ndim)s, PyArray_DIMS(%(x)s), x_typenum,0);\n }\n else {\n PyArray_FILLWBYTE(%(gx)s, 0);\n }\n dtype_%(z)s maximum; // temp var for maximum value in a region\n int z_prod;\n // do not run if any z[i] is zero\n z_prod = 1;\n for (int i=0; i<%(nd)s; i++)\n {\n z_prod *= z[i];\n }\n if (z_prod)\n {\n // will be used to hold start and end index of a region\n int r_st[%(nd)s];\n int r_end[%(nd)s];\n // index for iterating over the pooling regions\n int r_idx[%(nd)s];\n // placeholder for PyArray indexing (output)\n npy_intp o_idx[%(total_ndim)s];\n // placeholder for PyArray indexing (input)\n npy_intp i_idx[%(total_ndim)s];\n // loop over non-pooling dimensions\n int non_pooling_prod = 1;\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n non_pooling_prod *= PyArray_DIMS(%(x)s)[i];\n }\n %(omp_parallel)s\n // first loop over non-pooling dimensions\n for (int t=0; t<non_pooling_prod; t++)\n {\n // compute the non-pooling index in each dimension\n if (%(non_pool_ndim)s!=0)\n {\n o_idx[0] = t;\n i_idx[0] = t;\n for (int i=1; i<%(non_pool_ndim)s; i++)\n {\n o_idx[i] = o_idx[i - 1] / PyArray_DIMS(%(x)s)[i - 1];\n o_idx[i - 1] =o_idx[i - 1] %% PyArray_DIMS(%(x)s)[i - 1];\n i_idx[i] = o_idx[i];\n i_idx[i - 1] = o_idx[i - 1];\n }\n }\n\n // then loop over each region in each pooling dimension\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n for (r_idx[%(i)s]=0; r_idx[%(i)s] < z[%(i)s]; r_idx[%(i)s]++) {\n r_st[%(i)s] = r_idx[%(i)s] * st[%(i)s];\n r_end[%(i)s] = r_st[%(i)s] + ws[%(i)s];\n // skip the padding\n r_st[%(i)s] = r_st[%(i)s] < pd[%(i)s] ? pd[%(i)s] : r_st[%(i)s];\n r_end[%(i)s] = r_end[%(i)s] > (r[%(i)s] - pd[%(i)s]) ? r[%(i)s] - pd[%(i)s] : r_end[%(i)s];\n // from padded_img space to img space\n r_st[%(i)s] -= pd[%(i)s];\n r_end[%(i)s] -= pd[%(i)s];\n // use the index to find the correct position in the output\n o_idx[%(non_pool_ndim)s + %(i)s] = r_idx[%(i)s];\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n\n ccode += \"\"\"\n dtype_%(gz)s * gz;\n if (%(total_ndim)s == 4)\n {\n // the maximum value\n maximum = ((dtype_%(z)s*)(PyArray_GETPTR4(%(z)s,o_idx[0],o_idx[1],o_idx[2],o_idx[3])))[0];\n // the gradient corresponding to this maximum value in z\n gz = ((dtype_%(gz)s*)(PyArray_GETPTR4(%(gz)s, o_idx[0],o_idx[1],o_idx[2],o_idx[3])));\n }\n else\n {\n // the maximum value\n maximum = ((dtype_%(z)s*)(PyArray_GetPtr(%(z)s,o_idx)))[0];\n // the gradient corresponding to this maximum value in z\n gz = ((dtype_%(gz)s*)(PyArray_GetPtr(%(gz)s, o_idx)));\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n dtype_%(x)s a;\n dtype_%(gx)s * gx;\n if (%(total_ndim)s == 4)\n {\n a = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n gx = ((dtype_%(gx)s*)(PyArray_GETPTR4(%(gx)s, i_idx[0],i_idx[1],i_idx[2],i_idx[3])));\n }\n else\n {\n a = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n gx = ((dtype_%(gx)s*)(PyArray_GetPtr(%(gx)s, i_idx)));\n }\n if (a == maximum){\n gx[0] = gx[0] + gz[0];\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // loop over pooling dimension\n \"\"\"\n\n ccode += \"\"\"\n } // for loop over non-pooling dimensions\n } // if z_prod\n \"\"\"\n return ccode % locals()\n\n def c_code_cache_version(self):\n return (0, 10, self.openmp)\n\n\nclass AveragePoolGrad(PoolGrad):\n # ignore_border is used for perform, but not c code. No need in params_type\n\n def __init__(self, ignore_border, mode='average_inc_pad', ndim=2):\n assert mode in ['sum', 'average_inc_pad', 'average_exc_pad']\n PoolGrad.__init__(self, ignore_border, mode, ndim)\n\n # There is an extra dummy parameter to match the parameter count\n # of MaxPoolGrad. They have to keep the same interface because of\n # the DownsampleFactorMaxGrad trick to keep old scripts working\n # (see downsample.py for details on this).\n def make_node(self, x, gz, ws, stride=None, pad=None, dummy=None):\n # make_node should only be called by the grad function of\n # Pool, so these asserts should not fail.\n x = tensor.as_tensor_variable(x)\n gz = tensor.as_tensor_variable(gz)\n nd = self.ndim\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * nd\n ws = tensor.as_tensor_variable(ws)\n stride = tensor.as_tensor_variable(stride)\n pad = tensor.as_tensor_variable(pad)\n assert isinstance(x, Variable) and x.ndim >= nd\n assert isinstance(gz, Variable) and gz.ndim >= nd\n assert isinstance(ws, Variable) and ws.ndim == 1\n assert isinstance(stride, Variable) and stride.ndim == 1\n assert x.ndim == gz.ndim >= nd\n assert isinstance(pad, Variable) and pad.ndim == 1\n if ws.dtype not in tensor.int_dtypes:\n raise TypeError('Pool downsample parameters must be ints.')\n if stride.dtype not in tensor.int_dtypes:\n raise TypeError('Stride parameters must be ints.')\n if pad.dtype not in tensor.int_dtypes:\n raise TypeError('Padding parameters must be ints.')\n return Apply(self, [x, gz, ws, stride, pad], [x.type()])\n\n def perform(self, node, inp, out):\n x, gz, ws, stride, pad = inp\n gx_stg, = out\n nd = self.ndim\n assert ws.shape == stride.shape == pad.shape == (nd,)\n if len(x.shape) < nd:\n raise NotImplementedError(\n 'AveragePoolGrad requires input with {} or more dimensions'.format(nd))\n if self.mode == 'average_exc_pad' and max(pad) != 0:\n raise NotImplementedError()\n z_shape = self.out_shape(x.shape, ws, self.ignore_border, stride, pad, nd)\n if (gx_stg[0] is None) or (gx_stg[0].shape != z_shape):\n gx_stg[0] = np.empty(z_shape, dtype=x.dtype)\n zz = gx_stg[0]\n # size of pooling output\n pool_out_shp = zz.shape[-nd:]\n img_shp = tuple(x.shape[-nd + i] + 2 * pad[i] for i in xrange(nd))\n inc_pad = self.mode == 'average_inc_pad'\n sum_mode = self.mode == 'sum'\n\n # initialize the padded output\n gx = np.zeros((x.shape[:-nd] + img_shp), dtype=x.dtype)\n\n # precompute the region boundaries and sizes for each dimension\n region_slices = [[] for i in xrange(nd)]\n region_sizes = [[] for i in xrange(nd)]\n for i in xrange(nd):\n for j in xrange(pool_out_shp[i]):\n if sum_mode or inc_pad:\n start = j * stride[i]\n else:\n start = builtins.max(j * stride[i], pad[i])\n end = builtins.min(start + ws[i], img_shp[i])\n region_slices[i].append(slice(start, end))\n region_sizes[i].append(end - start)\n\n # iterate over non-pooling dimensions\n region_slice = [None] * nd\n for k in np.ndindex(*x.shape[:-nd]):\n gzk = gz[k]\n gxk = gx[k]\n # iterate over pooling regions\n for r in np.ndindex(*pool_out_shp):\n region_size = 1\n for i in xrange(nd):\n region_slice[i] = region_slices[i][r[i]]\n region_size *= region_sizes[i][r[i]]\n if sum_mode:\n val = gzk[r]\n else:\n # divide by region size\n val = gzk[r] / region_size\n gxk[region_slice] += val\n\n # unpad the image\n gx = gx[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))]\n gx_stg[0] = gx\n\n def grad(self, inp, grads):\n x, gz, ws, stride, pad = inp\n ggx, = grads\n return ([theano.tensor.zeros_like(x),\n Pool(ignore_border=self.ignore_border,\n ndim=self.ndim, mode=self.mode)(ggx,\n ws, stride, pad)] + [DisconnectedType()() for i in inp[2:]])\n\n def connection_pattern(self, node):\n return [[1], [1], [0], [0], [0]]\n\n def c_code(self, node, name, inp, out, sub):\n x, gz, ws, stride, pad = inp\n gx, = out\n nd = self.ndim\n total_ndim = node.inputs[0].ndim\n non_pool_ndim = total_ndim - nd\n fail = sub['fail']\n inc_pad = int(self.mode == 'average_inc_pad')\n sum_mode = int(self.mode == 'sum')\n if self.openmp:\n # run in parallel over each pooling block\n omp_parallel = '#pragma omp parallel for private(r_st, r_end, r_pad_width, r_idx, i_idx, o_idx) schedule(static)'\n else:\n omp_parallel = ''\n\n ccode = \"\"\"\n // sanity checks\n int x_typenum = PyArray_ObjectType((PyObject*)%(x)s, 0);\n int gz_typenum = PyArray_ObjectType((PyObject*)%(gz)s, 0);\n if (x_typenum != gz_typenum)\n {\n PyErr_SetString(PyExc_ValueError, \"input types must all match\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(x)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"x must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(gz)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"gz must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_DIM(%(ws)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"ws must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(stride)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"stride must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(pad)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"pad must be a vector of size %(nd)s\");\n %(fail)s;\n }\n int z[%(nd)s]; // shape of the output\n int r[%(nd)s]; // shape of the padded_input\n int ws[%(nd)s];\n int st[%(nd)s];\n int pd[%(nd)s];\n int nonzero_padding;\n nonzero_padding = 0;\n for (int i=0; i<%(nd)s; i++)\n {\n ws[i] = *((npy_intp*)PyArray_GETPTR1(%(ws)s, i));\n st[i] = *((npy_intp*)PyArray_GETPTR1(%(stride)s, i));\n pd[i] = *((npy_intp*)PyArray_GETPTR1(%(pad)s, i));\n z[i] = PyArray_DIMS(%(gz)s)[%(non_pool_ndim)s + i];\n r[i] = PyArray_DIMS(%(x)s)[%(non_pool_ndim)s + i] + 2 * pd[i];\n if (pd[i]>0)\n nonzero_padding = 1;\n }\n if (!%(inc_pad)s && !%(sum_mode)s && nonzero_padding)\n {\n PyErr_SetString(PyExc_ValueError,\n \"padding must be zero for average_exc_pad\");\n %(fail)s;\n }\n // allocating memory for output, if necessary\n int mem_nec;\n mem_nec = 0;\n if ((!%(gx)s) || !PyArray_ISCONTIGUOUS(%(gx)s)\n || *PyArray_DIMS(%(gx)s)!=%(total_ndim)s)\n {\n mem_nec = 1;\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(total_ndim)s; i++)\n {\n if (PyArray_DIMS(%(gx)s)[i] != PyArray_DIMS(%(x)s)[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (mem_nec)\n {\n Py_XDECREF(%(gx)s);\n %(gx)s = (PyArrayObject*) PyArray_ZEROS(%(total_ndim)s, PyArray_DIMS(%(x)s), x_typenum,0);\n }\n else {\n PyArray_FILLWBYTE(%(gx)s, 0);\n }\n int z_prod;\n // do not run if any z[i] is zero\n z_prod = 1;\n for (int i=0; i<%(nd)s; i++)\n {\n z_prod *= z[i];\n }\n if (z_prod)\n {\n // will be used to hold start and end index of a region\n int r_st[%(nd)s];\n int r_end[%(nd)s];\n // padded region size\n int r_pad_width[%(nd)s];\n // index for iterating over the pooling regions\n int r_idx[%(nd)s];\n // placeholder for PyArray indexing (output)\n npy_intp o_idx[%(total_ndim)s];\n // placeholder for PyArray indexing (input)\n npy_intp i_idx[%(total_ndim)s];\n // loop over non-pooling dimensions\n int non_pooling_prod = 1;\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n non_pooling_prod *= PyArray_DIMS(%(x)s)[i];\n }\n %(omp_parallel)s\n // first loop over non-pooling dimensions\n for (int t=0; t<non_pooling_prod; t++)\n {\n // compute the non-pooling index in each dimension\n if (%(non_pool_ndim)s!=0)\n {\n o_idx[0] = t;\n i_idx[0] = t;\n for (int i=1; i<%(non_pool_ndim)s; i++)\n {\n o_idx[i] = o_idx[i - 1] / PyArray_DIMS(%(x)s)[i - 1];\n o_idx[i - 1] =o_idx[i - 1] %% PyArray_DIMS(%(x)s)[i - 1];\n i_idx[i] = o_idx[i];\n i_idx[i - 1] = o_idx[i - 1];\n }\n }\n\n // then loop over each region in each pooling dimension\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n for (r_idx[%(i)s]=0; r_idx[%(i)s] < z[%(i)s]; r_idx[%(i)s]++) {\n r_st[%(i)s] = r_idx[%(i)s] * st[%(i)s];\n if (!%(sum_mode)s && !%(inc_pad)s && r_st[%(i)s] < pd[%(i)s])\n {\n r_st[%(i)s] = pd[%(i)s];\n }\n r_end[%(i)s] = r_st[%(i)s] + ws[%(i)s];\n r_end[%(i)s] = r_end[%(i)s] > r[%(i)s] ? r[%(i)s] : r_end[%(i)s];\n r_pad_width[%(i)s] = r_end[%(i)s] - r_st[%(i)s];\n // from padded_img space to img space\n r_st[%(i)s] = r_st[%(i)s] - pd[%(i)s] > 0 ? r_st[%(i)s] - pd[%(i)s] : 0;\n r_end[%(i)s] = r_end[%(i)s] > r[%(i)s] - pd[%(i)s] ? r[%(i)s] - 2 * pd[%(i)s] : r_end[%(i)s] - pd[%(i)s];\n\n // use the index to find the correct position in the output\n o_idx[%(non_pool_ndim)s + %(i)s] = r_idx[%(i)s];\n \"\"\" % dict(i=i, sum_mode=sum_mode, inc_pad=inc_pad, non_pool_ndim=non_pool_ndim)\n\n ccode += \"\"\"\n dtype_%(gz)s * gz;\n dtype_%(gz)s val;\n if (%(total_ndim)s == 4)\n {\n // the gradient for this region\n gz = ((dtype_%(gz)s*)(PyArray_GETPTR4(%(gz)s, o_idx[0],o_idx[1],o_idx[2],o_idx[3])));\n }\n else\n {\n // the gradient for this region\n gz = ((dtype_%(gz)s*)(PyArray_GetPtr(%(gz)s, o_idx)));\n }\n // compute the contribution\n if (%(sum_mode)s)\n {\n val = gz[0];\n }\n else\n {\n val = gz[0] / (%(region_size)s);\n }\n \"\"\"\n region_size = ' * '.join('r_pad_width[%d]' % i for i in xrange(nd))\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n dtype_%(gx)s * gx;\n if (%(total_ndim)s == 4)\n {\n gx = ((dtype_%(gx)s*)(PyArray_GETPTR4(%(gx)s, i_idx[0],i_idx[1],i_idx[2],i_idx[3])));\n }\n else\n {\n gx = ((dtype_%(gx)s*)(PyArray_GetPtr(%(gx)s, i_idx)));\n }\n gx[0] = gx[0] + val;\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // loop over pooling dimension\n \"\"\"\n\n ccode += \"\"\"\n } // for loop over non-pooling dimensions\n } // if z_prod\n \"\"\"\n return ccode % locals()\n\n def c_code_cache_version(self):\n return (0, 3, self.openmp)\n\n\nclass DownsampleFactorMaxGradGrad(OpenMPOp):\n __props__ = ('ignore_border', 'mode', 'ndim')\n\n def __init__(self, ignore_border, mode='max', ndim=2, openmp=None):\n self.ndim = ndim\n self.ignore_border = ignore_border\n self.mode = mode\n super(DownsampleFactorMaxGradGrad, self).__init__(openmp=openmp)\n assert self.mode == 'max'\n\n def make_node(self, x, maxout, gz, ws, stride=None, pad=None):\n # make_node should only be called by the grad function of\n # MaxPoolGrad, so these asserts should not fail.\n x = tensor.as_tensor_variable(x)\n maxout = tensor.as_tensor_variable(maxout)\n gz = tensor.as_tensor_variable(gz)\n nd = self.ndim\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * nd\n elif isinstance(pad, (tuple, list)):\n if max(pad) != 0 and not self.ignore_border:\n raise NotImplementedError(\n 'padding works only with ignore_border=True')\n if isinstance(ws, (tuple, list)):\n if any(pad[i] >= ws[i] for i in range(nd)):\n raise NotImplementedError(\n 'padding must be smaller than strides')\n ws = tensor.as_tensor_variable(ws)\n stride = tensor.as_tensor_variable(stride)\n pad = tensor.as_tensor_variable(pad)\n assert ws.ndim == 1\n assert stride.ndim == 1\n assert pad.ndim == 1\n assert x.ndim == maxout.ndim == gz.ndim >= nd\n if ws.dtype not in tensor.int_dtypes:\n raise TypeError('Pool downsample parameters must be ints.')\n if stride.dtype not in tensor.int_dtypes:\n raise TypeError('Stride parameters must be ints.')\n if pad.dtype not in tensor.int_dtypes:\n raise TypeError('Padding parameters must be ints.')\n return Apply(self, [x, maxout, gz, ws, stride, pad], [x.type()])\n\n def perform(self, node, inp, out):\n x, maxout, ggx, ws, stride, pad = inp\n z, = out\n nd = self.ndim\n assert ws.shape == stride.shape == pad.shape == (nd,)\n if len(x.shape) < nd:\n raise NotImplementedError(\n 'DownsampleFactorMaxGradGrad requires input '\n 'with {} or more dimensions'.format(nd))\n if (z[0] is None) or (z[0].shape != maxout.shape):\n z[0] = np.zeros(maxout.shape, dtype=x.dtype)\n ggz = z[0] # grad wrt maxout_grad has the same shape as maxout\n # size of pooling output\n pool_out_shp = ggz.shape[-nd:]\n img_shp = tuple(x.shape[-nd + i] + 2 * pad[i] for i in xrange(nd))\n\n # pad the image and its gradients\n if max(pad) > 0:\n y_padded = np.zeros(x.shape[:-nd] + img_shp, dtype=x.dtype)\n y_padded[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = x\n ggx_padded = np.zeros(x.shape[:-nd] + img_shp, dtype=x.dtype)\n ggx_padded[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = ggx\n\n else:\n y_padded = x\n ggx_padded = ggx\n\n # precompute the region boundaries for each dimension\n region_ranges = [[] for i in xrange(nd)]\n for i in xrange(nd):\n for j in xrange(pool_out_shp[i]):\n start = j * stride[i]\n end = builtins.min(start + ws[i], img_shp[i])\n region_ranges[i].append(xrange(start, end))\n\n # iterate over non-pooling dimensions\n for k in np.ndindex(*x.shape[:-nd]):\n ggxk = ggx_padded[k]\n ggzk = ggz[k]\n yk = y_padded[k]\n maxoutk = maxout[k]\n # iterate over pooling regions\n for r in np.ndindex(*pool_out_shp):\n # iterate inside region\n maxout_value = maxoutk[r]\n for c in itertools.product(*[region_ranges[i][r[i]]\n for i in xrange(nd)]):\n if maxout_value == yk[c]:\n ggzk[r] += ggxk[c]\n\n def infer_shape(self, node, in_shapes):\n return [in_shapes[1]]\n\n def grad(self, inp, grads):\n x, maxout, ggx, ws, stride, pad = inp\n gz, = grads\n return [theano.tensor.zeros_like(x),\n theano.tensor.zeros_like(maxout),\n MaxPoolGrad(ignore_border=self.ignore_border,\n ndim=self.ndim)(x, maxout, gz,\n ws, stride, pad),\n DisconnectedType()(),\n DisconnectedType()(),\n DisconnectedType()()]\n\n def connection_pattern(self, node):\n return [[1], [1], [1], [0], [0], [0]]\n\n def c_code(self, node, name, inp, out, sub):\n if self.mode != 'max':\n raise theano.gof.utils.MethodNotDefined()\n x, maxout, ggx, ws, stride, pad = inp\n z, = out # the grad of grad\n nd = self.ndim\n total_ndim = node.inputs[0].ndim\n non_pool_ndim = total_ndim - nd\n fail = sub['fail']\n\n if self.openmp:\n # run in parallel over each pooling block\n omp_parallel = '#pragma omp parallel for private(r_st, r_end, r_idx, i_idx, o_idx, maximum) schedule(static)'\n else:\n omp_parallel = ''\n ccode = \"\"\"\n int z_typenum = PyArray_ObjectType((PyObject*)%(maxout)s, 0);\n int z[%(nd)s]; // shape of the output\n int r[%(nd)s]; // shape of the padded_input\n int ws[%(nd)s];\n int st[%(nd)s];\n int pd[%(nd)s];\n if(PyArray_DIM(%(ws)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"ws must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(stride)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"stride must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(pad)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"pad must be a vector of size %(nd)s\");\n %(fail)s;\n }\n for (int i=0; i<%(nd)s; i++)\n {\n ws[i] = *((npy_intp*)PyArray_GETPTR1(%(ws)s, i));\n st[i] = *((npy_intp*)PyArray_GETPTR1(%(stride)s, i));\n pd[i] = *((npy_intp*)PyArray_GETPTR1(%(pad)s, i));\n z[i] = PyArray_DIMS(%(maxout)s)[%(non_pool_ndim)s + i];\n r[i] = PyArray_DIMS(%(x)s)[%(non_pool_ndim)s + i] + 2 * pd[i];\n }\n // allocating memory for output, if necessary\n int mem_nec;\n mem_nec = 0;\n if ((!%(z)s) || !PyArray_ISCONTIGUOUS(%(z)s)\n || *PyArray_DIMS(%(z)s)!=%(total_ndim)s)\n {\n mem_nec = 1;\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(total_ndim)s; i++)\n {\n if (PyArray_DIMS(%(z)s)[i] != PyArray_DIMS(%(maxout)s)[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (mem_nec)\n {\n Py_XDECREF(%(z)s);\n %(z)s = (PyArrayObject*) PyArray_ZEROS(%(total_ndim)s, PyArray_DIMS(%(maxout)s), z_typenum,0);\n }\n else {\n PyArray_FILLWBYTE(%(z)s, 0);\n }\n dtype_%(maxout)s maximum; // temp var for maximum value in a region\n // will be used to hold start and end index of a region\n int r_st[%(nd)s];\n int r_end[%(nd)s];\n // index for iterating over the pooling regions\n int r_idx[%(nd)s];\n // placeholder for PyArray indexing (output)\n npy_intp o_idx[%(total_ndim)s];\n // placeholder for PyArray indexing (input)\n npy_intp i_idx[%(total_ndim)s];\n // loop over non-pooling dimensions\n int non_pooling_prod;\n non_pooling_prod = 1;\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n non_pooling_prod *= PyArray_DIMS(%(x)s)[i];\n }\n %(omp_parallel)s\n // first loop over non-pooling dimensions\n for (int t=0; t<non_pooling_prod; t++)\n {\n // compute the non-pooling index in each dimension\n if (%(non_pool_ndim)s!=0)\n {\n o_idx[0] = t;\n i_idx[0] = t;\n for (int i=1; i<%(non_pool_ndim)s; i++)\n {\n o_idx[i] = o_idx[i - 1] / PyArray_DIMS(%(x)s)[i - 1];\n o_idx[i - 1] = o_idx[i - 1] %% PyArray_DIMS(%(x)s)[i - 1];\n i_idx[i] = o_idx[i];\n i_idx[i - 1] = o_idx[i - 1];\n }\n }\n\n // then loop over each region in each pooling dimension\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n for (r_idx[%(i)s]=0; r_idx[%(i)s] < z[%(i)s]; r_idx[%(i)s]++) {\n r_st[%(i)s] = r_idx[%(i)s] * st[%(i)s];\n r_end[%(i)s] = r_st[%(i)s] + ws[%(i)s];\n // skip the padding\n r_st[%(i)s] = r_st[%(i)s] < pd[%(i)s] ? pd[%(i)s] : r_st[%(i)s];\n r_end[%(i)s] = r_end[%(i)s] > (r[%(i)s] - pd[%(i)s]) ? r[%(i)s] - pd[%(i)s] : r_end[%(i)s];\n // from padded_img space to img space\n r_st[%(i)s] -= pd[%(i)s];\n r_end[%(i)s] -= pd[%(i)s];\n // use the index to find the correct position in the output\n o_idx[%(non_pool_ndim)s + %(i)s] = r_idx[%(i)s];\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n\n ccode += \"\"\"\n dtype_%(z)s * z;\n if (%(total_ndim)s == 4)\n {\n // the maximum value\n maximum = ((dtype_%(maxout)s*)(PyArray_GETPTR4(%(maxout)s,o_idx[0],o_idx[1],o_idx[2],o_idx[3])))[0];\n // z at this position\n z = ((dtype_%(z)s*)(PyArray_GETPTR4(%(z)s,o_idx[0],o_idx[1],o_idx[2],o_idx[3])));\n }\n else\n {\n // the maximum value\n maximum = ((dtype_%(maxout)s*)(PyArray_GetPtr(%(maxout)s,o_idx)))[0];\n // z at this position\n z = ((dtype_%(z)s*)(PyArray_GetPtr(%(z)s,o_idx)));\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n dtype_%(x)s a;\n dtype_%(ggx)s * ggx;\n if (%(total_ndim)s == 4)\n {\n a = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n ggx = ((dtype_%(ggx)s*)(PyArray_GETPTR4(%(ggx)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])));\n }\n else\n {\n a = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n ggx = ((dtype_%(ggx)s*)(PyArray_GetPtr(%(ggx)s,i_idx)));\n }\n if (a == maximum){\n z[0] += ggx[0];\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // loop over pooling dimension\n \"\"\"\n\n ccode += \"\"\"\n } // for loop over non-pooling dimensions\n \"\"\"\n return ccode % locals()\n\n def c_code_cache_version(self):\n return (0, 4, self.openmp)\n\n\nclass MaxPoolRop(OpenMPOp):\n \"\"\"\n Implements the R-operator for the downsample operation.\n\n Parameters\n ----------\n ws : list or tuple of N ints\n Downsample factor over rows, columns etc.\n ws indicates the size of the pooling region.\n ignore_border : bool\n If ws doesn't divide imgshape, do we include an extra row/col/slice\n of partial downsampling (False) or ignore it (True).\n stride : list or tuple of N ints or None\n Stride size, which is the number of shifts over rows/cols/slices to get the\n next pool region. If stride is None, it is considered equal to ws\n (no overlap on pooling regions).\n pad : tuple of N ints or None\n For each downsampling dimension, this specifies the number of zeros to\n add as padding on both sides. For 2D and (pad_h, pad_w), pad_h specifies the\n size of the top and bottom margins, pad_w specifies the size of the left and\n right margins. No padding is added if pad is None.\n mode : {'max', 'sum', 'average_inc_pad', 'average_exc_pad'}\n ('average_inc_pad' excludes the padding from the count,\n 'average_exc_pad' include it)\n ndim : int\n The number of pooling dimensions N.\n The default is 2.\n \"\"\"\n\n __props__ = ('ignore_border', 'mode', 'ndim')\n params_type = ParamsType(ignore_border=bool_t,)\n\n def __init__(self, ignore_border=False, mode='max', ndim=2, openmp=None):\n super(MaxPoolRop, self).__init__(openmp=openmp)\n self.ndim = ndim\n self.ignore_border = ignore_border\n self.mode = mode\n assert mode == 'max'\n\n def make_node(self, x, eval_point, ws, stride=None, pad=None):\n # TODO: consider restricting the dtype?\n x = tensor.as_tensor_variable(x)\n eval_point = tensor.as_tensor_variable(eval_point)\n nd = self.ndim\n if stride is None:\n stride = ws\n if pad is None:\n pad = (0,) * nd\n elif isinstance(pad, (tuple, list)):\n if max(pad) != 0 and not self.ignore_border:\n raise NotImplementedError(\n 'padding works only with ignore_border=True')\n if isinstance(ws, (tuple, list)):\n if any(pad[i] >= ws[i] for i in range(nd)):\n raise NotImplementedError(\n 'padding must be smaller than strides')\n ws = tensor.as_tensor_variable(ws)\n stride = tensor.as_tensor_variable(stride)\n pad = tensor.as_tensor_variable(pad)\n assert ws.ndim == 1\n assert stride.ndim == 1\n assert pad.ndim == 1\n if x.type.ndim < nd:\n raise TypeError()\n if not ws.dtype.startswith('int'):\n raise TypeError('Pool downsample parameters must be ints.')\n if not stride.dtype.startswith('int'):\n raise TypeError('Stride parameters must be ints.')\n if not pad.dtype.startswith('int'):\n raise TypeError('Padding parameters must be ints.')\n # If the input shape are broadcastable we can have 0 in the output shape\n broad = x.broadcastable[:-nd] + (False,) * nd\n out = tensor.TensorType(eval_point.dtype, broad)\n return gof.Apply(self, [x, eval_point, ws, stride, pad], [out()])\n\n def perform(self, node, inp, out, params):\n x, ex, ws, stride, pad = inp\n z, = out\n nd = self.ndim\n assert ws.shape == stride.shape == pad.shape == (nd,)\n if len(x.shape) < nd:\n raise NotImplementedError(\n 'Pool requires input with {} or more dimensions'.format(nd))\n z_shape = Pool.out_shape(x.shape, ws, params.ignore_border, stride, pad, nd)\n if not self.ignore_border:\n assert all(z > 0 for z in z_shape[-nd:])\n if (z[0] is None) or (z[0].shape != z_shape):\n z[0] = np.empty(z_shape, dtype=x.dtype)\n zz = z[0]\n # size of pooling output\n pool_out_shp = zz.shape[-nd:]\n img_shp = tuple(x.shape[-nd + i] + 2 * pad[i] for i in xrange(nd))\n inc_pad = self.mode == 'average_inc_pad'\n\n # pad the image and the eval point\n if max(pad) != 0:\n y = np.zeros(x.shape[:-nd] + img_shp, dtype=x.dtype)\n y[(slice(None),) * (len(x.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = x\n ey = np.zeros(ex.shape[:-nd] + img_shp, dtype=ex.dtype)\n ey[(slice(None),) * (len(ex.shape) - nd) +\n tuple(slice(pad[i], img_shp[i] - pad[i]) for i in xrange(nd))] = ex\n else:\n y = x\n ey = ex\n\n # precompute the region boundaries for each dimension\n region_slices = [[] for i in xrange(nd)]\n for i in xrange(nd):\n for j in xrange(pool_out_shp[i]):\n start = j * stride[i]\n end = builtins.min(start + ws[i], img_shp[i])\n if not inc_pad:\n start = builtins.max(start, pad[i])\n end = builtins.min(end, img_shp[i] - pad[i])\n region_slices[i].append(slice(start, end))\n\n # iterate over non-pooling dimensions\n for k in np.ndindex(*x.shape[:-nd]):\n zzk = zz[k]\n yk = y[k]\n eyk = ey[k]\n # iterate over pooling regions\n for r in np.ndindex(*pool_out_shp):\n # current slice in padded input\n ykslice = yk[[region_slices[i][r[i]] for i in xrange(nd)]]\n # current slice in eval points\n eykslice = eyk[[region_slices[i][r[i]] for i in xrange(nd)]]\n # indices of maximum\n idx = np.unravel_index(np.argmax(ykslice), ykslice.shape)\n zzk[r] = eykslice[idx]\n\n def c_headers(self):\n headers = ['<algorithm>']\n headers += super(MaxPoolRop, self).c_headers()\n return headers\n\n def c_code(self, node, name, inp, out, sub):\n if self.mode != 'max':\n raise theano.gof.utils.MethodNotDefined()\n x, ex, ws, stride, pad = inp\n z, = out\n nd = self.ndim\n total_ndim = node.inputs[0].ndim\n non_pool_ndim = total_ndim - nd\n fail = sub['fail']\n params = sub['params']\n\n if self.openmp:\n # run in parallel over each pooling block\n omp_parallel = '#pragma omp parallel for private(r_st, r_end, r_idx, i_idx, o_idx, collector, eval_collector) schedule(static)'\n else:\n omp_parallel = ''\n ccode = \"\"\"\n int typenum = PyArray_ObjectType((PyObject*)%(x)s, 0);\n if(PyArray_NDIM(%(x)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"x must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_NDIM(%(ex)s)!=%(total_ndim)s)\n {\n PyErr_SetString(PyExc_ValueError, \"eval_point must be a %(total_ndim)sD ndarray\");\n %(fail)s;\n }\n if(PyArray_DIM(%(ws)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"ws must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(stride)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"stride must be a vector of size %(nd)s\");\n %(fail)s;\n }\n if(PyArray_DIM(%(pad)s, 0)!=%(nd)s)\n {\n PyErr_SetString(PyExc_ValueError, \"pad must be a vector of size %(nd)s\");\n %(fail)s;\n }\n int z[%(nd)s]; // shape of the output\n int r[%(nd)s]; // shape of the padded_input\n int ws[%(nd)s];\n int st[%(nd)s];\n int pd[%(nd)s];\n int nonzero_padding;\n nonzero_padding = 0;\n for (int i=0; i<%(nd)s; i++)\n {\n ws[i] = *((npy_intp*)PyArray_GETPTR1(%(ws)s, i));\n st[i] = *((npy_intp*)PyArray_GETPTR1(%(stride)s, i));\n pd[i] = *((npy_intp*)PyArray_GETPTR1(%(pad)s, i));\n r[i] = PyArray_DIMS(%(x)s)[%(non_pool_ndim)s + i] + 2 * pd[i];\n if (pd[i]>0)\n nonzero_padding = 1;\n }\n if (!%(params)s->ignore_border && nonzero_padding)\n {\n PyErr_SetString(PyExc_ValueError,\n \"padding must be zero when ignore border is False\");\n %(fail)s;\n }\n if (%(params)s->ignore_border)\n {\n for (int i=0; i<%(nd)s; i++)\n {\n // '/' in C is different from '/' in python\n if (r[i] - ws[i] < 0)\n {\n z[i] = 0;\n }\n else\n {\n z[i] = (r[i] - ws[i]) / st[i] + 1;\n }\n }\n }\n else\n {\n for (int i=0; i<%(nd)s; i++)\n {\n // decide how many rows/cols the output has\n if (st[i] >= ws[i])\n {\n z[i] = (r[i] - 1) / st[i] + 1;\n }\n else\n {\n z[i] = std::max(0, (r[i] - 1 - ws[i] + st[i]) / st[i]) + 1;\n }\n assert(z[i] > 0);\n }\n }\n // memory allocation of z if necessary\n int mem_nec;\n mem_nec = 0;\n if ((!%(z)s) || *PyArray_DIMS(%(z)s)!=%(total_ndim)s)\n {\n mem_nec = 1;\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n if (PyArray_DIMS(%(z)s)[i] != PyArray_DIMS(%(x)s)[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (!mem_nec)\n {\n for (int i=0; i<%(nd)s; i++)\n {\n if (PyArray_DIMS(%(z)s)[%(non_pool_ndim)s + i] != z[i])\n {\n mem_nec = 1;\n break;\n }\n }\n }\n if (mem_nec)\n {\n if (%(z)s) Py_XDECREF(%(z)s);\n npy_intp dims[%(total_ndim)s];\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n dims[i] = PyArray_DIMS(%(x)s)[i];\n }\n for (int i=0; i<%(nd)s; i++)\n {\n dims[%(non_pool_ndim)s + i] = z[i];\n }\n //TODO: zeros not necessary\n %(z)s = (PyArrayObject*) PyArray_ZEROS(%(total_ndim)s, dims, typenum,0);\n }\n // initialize temp var for the value in a region\n dtype_%(x)s collector;\n dtype_%(ex)s eval_collector;\n int z_prod;\n // do not run if any z[i] is zero\n z_prod = 1;\n for (int i=0; i<%(nd)s; i++)\n {\n z_prod *= z[i];\n }\n if (z_prod)\n {\n // will be used to hold start and end index of a region\n int r_st[%(nd)s];\n int r_end[%(nd)s];\n // index for iterating over the pooling regions\n int r_idx[%(nd)s];\n // placeholder for PyArray indexing (output)\n npy_intp o_idx[%(total_ndim)s];\n // placeholder for PyArray indexing (input)\n npy_intp i_idx[%(total_ndim)s];\n // loop over non-pooling dimensions\n int non_pooling_prod = 1;\n for (int i=0; i<%(non_pool_ndim)s; i++)\n {\n non_pooling_prod *= PyArray_DIMS(%(x)s)[i];\n }\n %(omp_parallel)s\n // first loop over non-pooling dimensions\n for (int t=0; t<non_pooling_prod; t++)\n {\n // compute the non-pooling index in each dimension\n if (%(non_pool_ndim)s!=0)\n {\n o_idx[0] = t;\n i_idx[0] = t;\n for (int i=1; i<%(non_pool_ndim)s; i++)\n {\n o_idx[i] = o_idx[i - 1] / PyArray_DIMS(%(x)s)[i - 1];\n o_idx[i - 1] = o_idx[i - 1] %% PyArray_DIMS(%(x)s)[i - 1];\n i_idx[i] = o_idx[i];\n i_idx[i - 1] = o_idx[i - 1];\n }\n }\n\n // then loop over each region in each pooling dimension\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n for (r_idx[%(i)s]=0; r_idx[%(i)s] < z[%(i)s]; r_idx[%(i)s]++) {\n r_st[%(i)s] = r_idx[%(i)s] * st[%(i)s];\n r_end[%(i)s] = r_st[%(i)s] + ws[%(i)s];\n // skip the padding\n r_st[%(i)s] = r_st[%(i)s] < pd[%(i)s] ? pd[%(i)s] : r_st[%(i)s];\n r_end[%(i)s] = r_end[%(i)s] > (r[%(i)s] - pd[%(i)s]) ? r[%(i)s] - pd[%(i)s] : r_end[%(i)s];\n // from padded_img space to img space\n r_st[%(i)s] -= pd[%(i)s];\n r_end[%(i)s] -= pd[%(i)s];\n // handle the case where no padding, ignore border is True\n if (%(params)s->ignore_border)\n {\n r_end[%(i)s] = r_end[%(i)s] > r[%(i)s] ? r[%(i)s] : r_end[%(i)s];\n }\n // use the index to find the correct position in the output\n o_idx[%(non_pool_ndim)s + %(i)s] = r_idx[%(i)s];\n \"\"\" % dict(i=i, params=sub['params'], non_pool_ndim=non_pool_ndim)\n\n ccode += \"\"\"\n // get a pointer to the correct position in the output\n dtype_%(z)s * z;\n if (%(total_ndim)s == 4)\n z = ((dtype_%(z)s*)(PyArray_GETPTR4(%(z)s, o_idx[0], o_idx[1], o_idx[2], o_idx[3])));\n else\n z = ((dtype_%(z)s*)(PyArray_GetPtr(%(z)s, o_idx)));\n \"\"\"\n\n for i in xrange(nd):\n ccode += \"\"\"\n // set the first index of dimension %(i)s\n i_idx[%(non_pool_ndim)s + %(i)s] = r_st[%(i)s];\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n // use the first element as the initial value of collector\n if (%(total_ndim)s == 4) {\n collector = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n eval_collector = ((dtype_%(ex)s*)(PyArray_GETPTR4(%(ex)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n } else {\n collector = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n eval_collector = ((dtype_%(ex)s*)(PyArray_GetPtr(%(ex)s,i_idx)))[0];\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n // go through the pooled region in the unpadded input\n for(int m%(i)s=r_st[%(i)s]; m%(i)s<r_end[%(i)s]; m%(i)s++)\n {\n i_idx[%(non_pool_ndim)s + %(i)s] = m%(i)s;\n \"\"\" % dict(i=i, non_pool_ndim=non_pool_ndim)\n ccode += \"\"\"\n // update maximum\n dtype_%(x)s a;\n dtype_%(ex)s ea;\n if (%(total_ndim)s == 4) {\n a = ((dtype_%(x)s*)(PyArray_GETPTR4(%(x)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n ea = ((dtype_%(ex)s*)(PyArray_GETPTR4(%(ex)s,i_idx[0],i_idx[1],i_idx[2],i_idx[3])))[0];\n }\n else {\n a = ((dtype_%(x)s*)(PyArray_GetPtr(%(x)s,i_idx)))[0];\n ea = ((dtype_%(ex)s*)(PyArray_GetPtr(%(ex)s,i_idx)))[0];\n }\n if (a > collector) {\n collector = a;\n eval_collector = ea;\n }\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // for loop over region\n \"\"\"\n ccode += \"\"\"\n z[0] = eval_collector;\n \"\"\"\n for i in xrange(nd):\n ccode += \"\"\"\n } // loop over pooling dimension\n \"\"\"\n\n ccode += \"\"\"\n } // for loop over non-pooling dimensions\n } // if z_prod\n \"\"\"\n return ccode % locals()\n\n def c_code_cache_version(self):\n return (1, self.openmp)\n", "from __future__ import absolute_import, print_function, division\nimport linecache\nimport sys\nimport traceback\n\nimport numpy as np\nfrom six import iteritems, integer_types, string_types, with_metaclass\nfrom six.moves import StringIO\n\nfrom theano import config\nfrom theano.compat import PY3\n\n\ndef simple_extract_stack(f=None, limit=None, skips=[]):\n \"\"\"This is traceback.extract_stack from python 2.7 with this change:\n\n - Comment the update of the cache.\n - Skip internal stack trace level.\n\n The update of the cache call os.stat to verify is the cache is up\n to date. This take too much time on cluster.\n\n limit - The number of stack level we want to return. If None, mean\n all what we can.\n\n skips - partial path of stack level we don't want to keep and count.\n When we find one level that isn't skipped, we stop skipping.\n\n \"\"\"\n if f is None:\n try:\n raise ZeroDivisionError\n except ZeroDivisionError:\n f = sys.exc_info()[2].tb_frame.f_back\n if limit is None:\n if hasattr(sys, 'tracebacklimit'):\n limit = sys.tracebacklimit\n trace = []\n n = 0\n while f is not None and (limit is None or n < limit):\n lineno = f.f_lineno\n co = f.f_code\n filename = co.co_filename\n name = co.co_name\n# linecache.checkcache(filename)\n line = linecache.getline(filename, lineno, f.f_globals)\n if line:\n line = line.strip()\n else:\n line = None\n f = f.f_back\n\n # Just skip inner level\n if len(trace) == 0:\n rm = False\n for p in skips:\n # Julian: I added the 'tests' exception together with\n # Arnaud. Otherwise, we'd lose the stack trace during\n # in our test cases (e.g. in test_opt.py). We're not\n # sure this is the right way to do it though.\n if p in filename and 'tests' not in filename:\n rm = True\n break\n if rm:\n continue\n trace.append((filename, lineno, name, line))\n n = n + 1\n trace.reverse()\n return trace\n\n\ndef add_tag_trace(thing, user_line=None):\n \"\"\"\n Add tag.trace to an node or variable.\n\n The argument is returned after being affected (inplace).\n\n Parameters\n ----------\n thing\n The object where we add .tag.trace.\n user_line\n The max number of user line to keep.\n\n Notes\n -----\n We alse use config.traceback.limit for the maximum number of stack level\n we look.\n\n \"\"\"\n if user_line is None:\n user_line = config.traceback.limit\n\n if user_line == -1:\n user_line = None\n skips = [\"theano/tensor/\", \"theano\\\\tensor\\\\\",\n \"theano/compile/\", \"theano\\\\compile\\\\\",\n \"theano/gof/\", \"theano\\\\gof\\\\\",\n \"theano/scalar/basic.py\", \"theano\\\\scalar\\\\basic.py\",\n \"theano/sandbox/\", \"theano\\\\sandbox\\\\\",\n \"theano/scan_module/\", \"theano\\\\scan_module\\\\\",\n \"theano/sparse/\", \"theano\\\\sparse\\\\\",\n \"theano/typed_list/\", \"theano\\\\typed_list\\\\\"]\n\n if config.traceback.compile_limit > 0:\n skips = []\n\n tr = simple_extract_stack(limit=user_line, skips=skips)\n # Different python version use different sementic for\n # limit. python 2.7 include the call to extrack_stack. The -1 get\n # rid of it.\n\n if tr:\n thing.tag.trace = [tr]\n else:\n thing.tag.trace = tr\n return thing\n\n\ndef get_variable_trace_string(v):\n sio = StringIO()\n # For backward compatibility with old trace\n tr = getattr(v.tag, 'trace', [])\n if isinstance(tr, list) and len(tr) > 0:\n print(\" \\nBacktrace when that variable is created:\\n\", file=sio)\n # The isinstance is needed to handle old pickled trace\n if isinstance(tr[0], tuple):\n traceback.print_list(v.tag.trace, sio)\n else:\n # Print separate message for each element in the list of\n # batcktraces\n for subtr in tr:\n traceback.print_list(subtr, sio)\n return sio.getvalue()\n\n\ndef hashtype(self):\n t = type(self)\n return hash(t.__name__) ^ hash(t.__module__)\n\n\n# Object to mark that a parameter is undefined (useful in cases where\n# None is a valid value with defined semantics)\nundef = object()\n\n\nclass MethodNotDefined(Exception):\n \"\"\"\n To be raised by functions defined as part of an interface.\n\n When the user sees such an error, it is because an important interface\n function has been left out of an implementation class.\n\n \"\"\"\n pass\n\n\nclass MetaObject(type):\n def __new__(cls, name, bases, dct):\n props = dct.get('__props__', None)\n if props is not None:\n if not isinstance(props, tuple):\n raise TypeError(\"__props__ has to be a tuple\")\n if not all(isinstance(p, string_types) for p in props):\n raise TypeError(\"elements of __props__ have to be strings\")\n\n def _props(self):\n \"\"\"\n Tuple of properties of all attributes\n \"\"\"\n return tuple(getattr(self, a) for a in props)\n dct['_props'] = _props\n\n def _props_dict(self):\n \"\"\"This return a dict of all ``__props__`` key-> value.\n\n This is useful in optimization to swap op that should have the\n same props. This help detect error that the new op have at\n least all the original props.\n\n \"\"\"\n return dict([(a, getattr(self, a))\n for a in props])\n dct['_props_dict'] = _props_dict\n\n if '__hash__' not in dct:\n def __hash__(self):\n return hash((type(self),\n tuple(getattr(self, a) for a in props)))\n dct['__hash__'] = __hash__\n\n if '__eq__' not in dct:\n def __eq__(self, other):\n return (type(self) == type(other) and\n tuple(getattr(self, a) for a in props) ==\n tuple(getattr(other, a) for a in props))\n dct['__eq__'] = __eq__\n\n if '__str__' not in dct:\n if len(props) == 0:\n def __str__(self):\n return \"%s\" % (self.__class__.__name__,)\n else:\n def __str__(self):\n return \"%s{%s}\" % (\n self.__class__.__name__,\n \", \".join(\"%s=%r\" % (p, getattr(self, p))\n for p in props))\n dct['__str__'] = __str__\n\n return type.__new__(cls, name, bases, dct)\n\n\nclass object2(with_metaclass(MetaObject, object)):\n __slots__ = []\n\n def __ne__(self, other):\n return not self == other\n\n\nclass scratchpad(object):\n def clear(self):\n self.__dict__.clear()\n\n def __update__(self, other):\n self.__dict__.update(other.__dict__)\n return self\n\n def __str__(self):\n return \"scratchpad\" + str(self.__dict__)\n\n def __repr__(self):\n return \"scratchpad\" + str(self.__dict__)\n\n def info(self):\n print(\"<theano.gof.utils.scratchpad instance at %i>\" % id(self))\n for k, v in iteritems(self.__dict__):\n print(\" %s: %s\" % (k, v))\n\n\nclass D:\n def __init__(self, **d):\n self.__dict__.update(d)\n\n\ndef memoize(f):\n \"\"\"\n Cache the return value for each tuple of arguments (which must be hashable).\n\n \"\"\"\n cache = {}\n\n def rval(*args, **kwargs):\n kwtup = tuple(kwargs.items())\n key = (args, kwtup)\n if key not in cache:\n val = f(*args, **kwargs)\n cache[key] = val\n else:\n val = cache[key]\n return val\n\n return rval\n\n\ndef deprecated(filename, msg=''):\n \"\"\"\n Decorator which will print a warning message on the first call.\n\n Use it like this::\n\n @deprecated('myfile', 'do something different...')\n def fn_name(...)\n ...\n\n And it will print::\n\n WARNING myfile.fn_name deprecated. do something different...\n\n \"\"\"\n def _deprecated(f):\n printme = [True]\n\n def g(*args, **kwargs):\n if printme[0]:\n print('WARNING: %s.%s deprecated. %s' %\n (filename, f.__name__, msg))\n printme[0] = False\n return f(*args, **kwargs)\n return g\n\n return _deprecated\n\n\ndef uniq(seq):\n \"\"\"\n Do not use set, this must always return the same value at the same index.\n If we just exchange other values, but keep the same pattern of duplication,\n we must keep the same order.\n\n \"\"\"\n # TODO: consider building a set out of seq so that the if condition\n # is constant time -JB\n return [x for i, x in enumerate(seq) if seq.index(x) == i]\n\n\ndef difference(seq1, seq2):\n \"\"\"\n Returns all elements in seq1 which are not in seq2: i.e ``seq1\\seq2``.\n\n \"\"\"\n try:\n # try to use O(const * len(seq1)) algo\n if len(seq2) < 4: # I'm guessing this threshold -JB\n raise Exception('not worth it')\n set2 = set(seq2)\n return [x for x in seq1 if x not in set2]\n except Exception:\n # maybe a seq2 element is not hashable\n # maybe seq2 is too short\n # -> use O(len(seq1) * len(seq2)) algo\n return [x for x in seq1 if x not in seq2]\n\n\ndef to_return_values(values):\n if len(values) == 1:\n return values[0]\n else:\n return values\n\n\ndef from_return_values(values):\n if isinstance(values, (list, tuple)):\n return values\n else:\n return [values]\n\n\ndef toposort(prereqs_d):\n \"\"\"\n Sorts prereqs_d.keys() topologically.\n\n prereqs_d[x] contains all the elements that must come before x\n in the ordering.\n\n \"\"\"\n\n# all1 = set(prereqs_d.keys())\n# all2 = set()\n# for x, y in iteritems(prereqs_d):\n# all2.update(y)\n# print all1.difference(all2)\n\n seq = []\n done = set()\n postreqs_d = {}\n for x, prereqs in iteritems(prereqs_d):\n for prereq in prereqs:\n postreqs_d.setdefault(prereq, set()).add(x)\n next = set([k for k in prereqs_d if not prereqs_d[k]])\n while next:\n bases = next\n next = set()\n for x in bases:\n done.add(x)\n seq.append(x)\n for x in bases:\n for postreq in postreqs_d.get(x, []):\n if not prereqs_d[postreq].difference(done):\n next.add(postreq)\n if len(prereqs_d) != len(seq):\n raise Exception(\"Cannot sort topologically: there might be cycles, \"\n \"prereqs_d does not have a key for each element or \"\n \"some orderings contain invalid elements.\")\n return seq\n\n\nclass Keyword:\n\n def __init__(self, name, nonzero=True):\n self.name = name\n self.nonzero = nonzero\n\n def __nonzero__(self):\n # Python 2.x\n return self.__bool__()\n\n def __bool__(self):\n # Python 3.x\n return self.nonzero\n\n def __str__(self):\n return \"<%s>\" % self.name\n\n def __repr__(self):\n return \"<%s>\" % self.name\n\nABORT = Keyword(\"ABORT\", False)\nRETRY = Keyword(\"RETRY\", False)\nFAILURE = Keyword(\"FAILURE\", False)\n\n\nsimple_types = integer_types + string_types + (float, bool, None.__class__, Keyword)\n\n\nANY_TYPE = Keyword(\"ANY_TYPE\")\nFALL_THROUGH = Keyword(\"FALL_THROUGH\")\n\n\ndef comm_guard(type1, type2):\n def wrap(f):\n old_f = f.__globals__[f.__name__]\n\n def new_f(arg1, arg2, *rest):\n if ((type1 is ANY_TYPE or isinstance(arg1, type1)) and\n (type2 is ANY_TYPE or isinstance(arg2, type2))):\n pass\n elif ((type1 is ANY_TYPE or isinstance(arg2, type1)) and\n (type2 is ANY_TYPE or isinstance(arg1, type2))):\n arg1, arg2 = arg2, arg1\n else:\n return old_f(arg1, arg2, *rest)\n\n variable = f(arg1, arg2, *rest)\n if variable is FALL_THROUGH:\n return old_f(arg1, arg2, *rest)\n else:\n return variable\n\n new_f.__name__ = f.__name__\n\n def typename(type):\n if isinstance(type, Keyword):\n return str(type)\n elif isinstance(type, (tuple, list)):\n return \"(\" + \", \".join([x.__name__ for x in type]) + \")\"\n else:\n return type.__name__\n\n new_f.__doc__ = (str(old_f.__doc__) + \"\\n\" +\n \", \".join([typename(type)\n for type in (type1, type2)]) +\n \"\\n\" + str(f.__doc__ or \"\"))\n return new_f\n\n return wrap\n\n\ndef type_guard(type1):\n def wrap(f):\n old_f = f.__globals__[f.__name__]\n\n def new_f(arg1, *rest):\n if (type1 is ANY_TYPE or isinstance(arg1, type1)):\n variable = f(arg1, *rest)\n if variable is FALL_THROUGH:\n return old_f(arg1, *rest)\n else:\n return variable\n else:\n return old_f(arg1, *rest)\n\n new_f.__name__ = f.__name__\n\n def typename(type):\n if isinstance(type, Keyword):\n return str(type)\n elif isinstance(type, (tuple, list)):\n return \"(\" + \", \".join([x.__name__ for x in type]) + \")\"\n else:\n return type.__name__\n\n new_f.__doc__ = (str(old_f.__doc__) + \"\\n\" +\n \", \".join([typename(type) for type in (type1,)]) +\n \"\\n\" + str(f.__doc__ or \"\"))\n return new_f\n\n return wrap\n\n\ndef flatten(a):\n \"\"\"\n Recursively flatten tuple, list and set in a list.\n\n \"\"\"\n if isinstance(a, (tuple, list, set)):\n l = []\n for item in a:\n l.extend(flatten(item))\n return l\n else:\n return [a]\n\n\ndef unique(x):\n return len(set(x)) == len(x)\n\n\ndef hist(coll):\n counts = {}\n for elem in coll:\n counts[elem] = counts.get(elem, 0) + 1\n return counts\n\n\n@deprecated(\"theano.gof.utils\",\n msg=\"Use a_theano_variable.auto_name instead\")\ndef give_variables_names(variables):\n \"\"\"\n Gives unique names to an iterable of variables. Modifies input.\n\n This function is idempotent.\n\n \"\"\"\n names = [var.name for var in variables]\n h = hist(names)\n\n def bad_var(var):\n return not var.name or h[var.name] > 1\n\n for i, var in enumerate(filter(bad_var, variables)):\n var.name = (var.name or \"\") + \"_%d\" % i\n\n if not unique([str(v) for v in variables]):\n raise ValueError(\"Not all variables have unique names. Maybe you've \"\n \"named some of the variables identically\")\n return variables\n\n\ndef remove(predicate, coll):\n \"\"\"\n Return those items of collection for which predicate(item) is true.\n\n Examples\n --------\n >>> def even(x):\n ... return x % 2 == 0\n >>> remove(even, [1, 2, 3, 4])\n [1, 3]\n\n \"\"\"\n return [x for x in coll if not predicate(x)]\n\n\nif PY3:\n import hashlib\n\n def hash_from_code(msg):\n # hashlib.sha256() requires an object that supports buffer interface,\n # but Python 3 (unicode) strings don't.\n if isinstance(msg, str):\n msg = msg.encode()\n # Python 3 does not like module names that start with\n # a digit.\n return 'm' + hashlib.sha256(msg).hexdigest()\n\nelse:\n import hashlib\n\n def hash_from_code(msg):\n try:\n return hashlib.sha256(msg).hexdigest()\n except TypeError:\n assert isinstance(msg, np.ndarray)\n return hashlib.sha256(np.getbuffer(msg)).hexdigest()\n\n\ndef hash_from_file(file_path):\n \"\"\"\n Return the SHA256 hash of a file.\n\n \"\"\"\n with open(file_path, 'rb') as f:\n file_content = f.read()\n return hash_from_code(file_content)\n\n\n# Set of C and C++ keywords as defined (at March 2nd, 2017) in the pages below:\n# - http://fr.cppreference.com/w/c/keyword\n# - http://fr.cppreference.com/w/cpp/keyword\n# Added `NULL` and `_Pragma` keywords.\nc_cpp_keywords = {'_Alignas', '_Alignof', '_Atomic', '_Bool', '_Complex', '_Generic', '_Imaginary', '_Noreturn',\n '_Pragma', '_Static_assert', '_Thread_local', 'alignas', 'alignof', 'and', 'and_eq', 'asm', 'auto',\n 'bitand', 'bitor', 'bool', 'break', 'case', 'catch', 'char', 'char16_t', 'char32_t', 'class', 'compl',\n 'const', 'const_cast', 'constexpr', 'continue', 'decltype', 'default', 'delete', 'do', 'double',\n 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend',\n 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'noexcept', 'not', 'not_eq',\n 'NULL', 'nullptr', 'operator', 'or', 'or_eq', 'private', 'protected', 'public', 'register',\n 'reinterpret_cast', 'restrict', 'return', 'short', 'signed', 'sizeof', 'static', 'static_assert',\n 'static_cast', 'struct', 'switch', 'template', 'this', 'thread_local', 'throw', 'true', 'try',\n 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile',\n 'wchar_t', 'while', 'xor', 'xor_eq'}\n" ]
[ [ "numpy.maximum", "numpy.argmax", "numpy.zeros_like", "numpy.ndindex", "numpy.zeros", "numpy.empty" ], [ "numpy.getbuffer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
huangruizhe/espresso
[ "ee658bcc959bfbe8a7a61d7374d532d082d2aa26" ]
[ "examples/classify_names/rough_work.py" ]
[ "# Online Python compiler (interpreter) to run Python online.\n# Write Python 3 code in this online editor and run it.\nimport numpy as np\nlist_a = []\nfor i in range(2):\n for j in range(5):\n list_a.append(i)\n\nlist_a = np.random.permutation(list_a)\nprint('class labels')\nprint(list_a)\nlist_a = np.array(list_a)\n\n\nindex_i = 0\nclassid_of_index0=list_a[index_i]\nprint('class_of_index0: ', classid_of_index0)\nclassid_of_index0_locations = np.where(list_a == classid_of_index0)\nclassid_of_index0_locations = classid_of_index0_locations[0]\nprint('class_of_index0_locations', classid_of_index0_locations)\nprint(classid_of_index0_locations != index_i)\nsame_index_list = classid_of_index0_locations[classid_of_index0_locations != index_i]\nprint(same_index_list)\nprint(same_index_list[0:2])\n\nnum_tokens_vec = [5,6,7,5,4,3,5,4,6,7]\nfor pos in same_index_list[0:2]:\n print(num_tokens_vec[pos])\nmax_val = tuple(num_tokens_vec[pos] for pos in same_index_list[0:2])\nmax_val1 = max(max_val)\nprint(max_val)\nprint(max_val1)\n" ]
[ [ "numpy.array", "numpy.random.permutation", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jaedong27/calipy
[ "ed5b5af2654b2a25e16af4267683cafc83d72729" ]
[ "calipy/viewer.py" ]
[ "import vtk\nfrom vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor\nimport math\nimport numpy as np\nimport numpy.matlib\nimport os\nimport json\nimport cv2\n\n# Z\n# /\n# /\n# /\n# ---------- X\n# |\n# |\n# |\n# Y\n\nclass vtkRenderer():\n def __init__(self, widget=None):\n self.ren = vtk.vtkRenderer()\n\n if widget is not None:\n # Qt Widget Mode\n self.qtwidget_mode = True\n \n #### Init\n # self.vtkWidget = QVTKRenderWindowInteractor(self.centralwidget)\n # self.vtkWidget.setGeometry(0,0,200,200)\n # self.vtkRenderer = calipy.vtkRenderer(self.vtkWidget)\n\n # Qt Widget\n self.vtkWidget = widget\n self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)\n self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()\n self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())\n self.iren.Initialize()\n self.iren.Start()\n else:\n # Window Mode\n self.qtwidget_mode = False\n\n # Make empty window\n self.renWin = vtk.vtkRenderWindow()\n self.renWin.AddRenderer(self.ren)\n self.renWin.SetSize(960, 540)\n\n self.iren = vtk.vtkRenderWindowInteractor()\n self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())\n self.iren.SetRenderWindow(self.renWin)\n self.iren.Initialize()\n\n self.ren.SetBackground(0, 0.1, 0)\n\n self.actor_list = {}\n\n axes = vtk.vtkAxesActor()\n self.ren.AddActor(axes)\n self.actor_list[\"axes\"] = axes\n self.ren.ResetCamera()\n\n self.iren.AddObserver('LeftButtonPressEvent', self.pushLeftButtonPressEventOnVTK, 1.0)\n\n # Add Event for get Position\n def pushLeftButtonPressEventOnVTK(self, obj, ev):\n clickPos = self.iren.GetEventPosition()\n #print(clickPos)\n picker = vtk.vtkPropPicker()\n picker.Pick(clickPos[0], clickPos[1], 0, self.ren)\n print(picker.GetPickPosition())\n\n\n def setMainCamera(self, R = np.eye(3), t = np.zeros((3,1)), fov = 80):\n camera = vtk.vtkCamera()\n camera.SetPosition(t[0,0],t[1,0],t[2,0])\n #camera.SetFocalPoint(0,1,0)\n focalpoint = np.array([[0],[0],[1]])\n focalpoint = np.dot(R,focalpoint) + t\n camera.SetFocalPoint(focalpoint[0],focalpoint[1],focalpoint[2])\n ref = np.array([[0],[-1],[0]])\n cam_up = np.dot(R, ref)\n #camera.SetPosition(0,1,0)\n #camera.SetViewUp(0,1,0)\n camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])\n camera.SetViewAngle(fov)\n self.ren.SetActiveCamera(camera)\n\n def setMainCameraToSeeTarget(self, t = np.zeros((3,1)), target = np.zeros((3,1)), fov = 80):\n camera = vtk.vtkCamera()\n camera.SetPosition(t[0,0],t[1,0],t[2,0])\n #print(\"Position :\", t)\n #camera.SetFocalPoint(0,1,0)\n #focalpoint = np.array([[0],[0],[1]])\n #focalpoint = np.dot(R,focalpoint) + t\n target_focalpoint = (target - t).ravel()\n #print(target_focalpoint)\n target_focalpoint = target_focalpoint / np.linalg.norm(target_focalpoint)\n #print(\"focalpoint\", target)\n camera.SetFocalPoint(target[0],target[1],target[2])\n ref = np.array([[0],[-1],[0]]).ravel()\n #print(focalpoint, ref)\n ref_right = np.cross(target_focalpoint, ref)\n ref_right = ref_right / np.linalg.norm(ref_right)\n #print(ref_right, focalpoint)\n cam_up = np.cross(ref_right, target_focalpoint)\n cam_up = cam_up / np.linalg.norm(cam_up)\n print(\"Up\",cam_up)\n #cam_up = np.dot(R, ref)\n #camera.SetPosition(0,1,0)\n #camera.SetViewUp(0,1,0)\n camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])\n camera.SetViewAngle(fov)\n self.ren.SetActiveCamera(camera)\n\n def getActorList(self):\n return self.actor_list.keys()\n\n def removeActorByName(self, name):\n #print(self.actor_list)\n if name in self.actor_list.keys():\n actor = self.actor_list.pop(name)\n self.ren.RemoveActor(actor)\n #print(\"remove! \", name)\n \n def addText(self, name, text, pos_x, pos_y):\n self.removeActorByName(name)\n textActor = vtk.vtkTextActor()\n textActor.SetInput( text )\n textActor.SetPosition( pos_x, pos_y )\n textActor.GetTextProperty().SetFontSize ( 50 )\n textActor.GetTextProperty().SetColor ( 1.0, 1.0, 1.0 )\n self.ren.AddActor2D(textActor)\n self.actor_list[name] = textActor\n \n def addPlane(self, name, point1, point2, point3, color=np.array([255.0,255.0,255.0]), opacity=1.0):\n self.removeActorByName(name)\n\n # Create a plane\n planeSource = vtk.vtkPlaneSource()\n # planeSource.SetOrigin(center_point[0], center_point[1], center_point[2])\n # #planeSource.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])\n # #print(dir(planeSource))\n # planeSource.SetPoint1(top_left_point[0], top_left_point[1], top_left_point[2])\n # planeSource.SetPoint2(bot_right_point[0], bot_right_point[1], bot_right_point[2])\n # planeSource.SetXResolution(10)\n # planeSource.SetYResolution(340)\n planeSource.SetOrigin(point1[0], point1[1], point1[2])\n planeSource.SetPoint1(point2[0], point2[1], point2[2])\n planeSource.SetPoint2(point3[0], point3[1], point3[2])\n planeSource.SetXResolution(10)\n planeSource.SetYResolution(340)\n\n planeSource.Update()\n\n plane = planeSource.GetOutput()\n\n # Create a mapper and actor\n polygonMapper = vtk.vtkPolyDataMapper()\n if vtk.VTK_MAJOR_VERSION <= 5:\n polygonMapper.SetInputConnection(polygon.GetProducerPort())\n else:\n polygonMapper.SetInputData(plane)\n polygonMapper.Update()\n\n polygonActor = vtk.vtkActor()\n polygonActor.SetMapper(polygonMapper)\n polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])\n polygonActor.GetProperty().SetOpacity(opacity)\n #actor.GetProperty().SetColor(colors->GetColor3d(\"Cyan\").GetData());\n\n self.ren.AddActor(polygonActor)\n self.actor_list[name] = polygonActor\n\n def addPlanWithTexture(self, name, point1, point2, point3, path, opacity=1.0):\n self.removeActorByName(name)\n\n #png_file = vtk.vtkPNGReader()\n #print(png_file.CanReadFile(path))\n\n # Read the image which will be the texture\n #vtkSmartPointer<vtkJPEGReader> jPEGReader = vtkSmartPointer<vtkJPEGReader>::New();\n #jPEGReader->SetFileName ( inputFilename.c_str() );\n img = vtk.vtkJPEGReader()\n img.SetFileName(path)\n \n #print(img.CanReadFile(path))\n #print(path)\n\n # Create a plane\n #vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New();\n #plane->SetCenter(0.0, 0.0, 0.0);\n #plane->SetNormal(0.0, 0.0, 1.0);\n plane = vtk.vtkPlaneSource()\n # planeSource.SetOrigin(center_point[0], center_point[1], center_point[2])\n # #planeSource.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])\n # #print(dir(planeSource))\n # planeSource.SetPoint1(top_left_point[0], top_left_point[1], top_left_point[2])\n # planeSource.SetPoint2(bot_right_point[0], bot_right_point[1], bot_right_point[2])\n # planeSource.SetXResolution(10)\n # planeSource.SetYResolution(340)\n #plane.SetCenter(0.0,0.0,0.0)\n #plane.SetNormal(0.0,0.0,1.0)\n plane.SetOrigin(point1[0], point1[1], point1[2])\n plane.SetPoint1(point2[0], point2[1], point2[2])\n plane.SetPoint2(point3[0], point3[1], point3[2])\n plane.SetXResolution(1920)\n plane.SetYResolution(1080)\n\n # Apply the texture\n #vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New();\n #texture->SetInputConnection(jPEGReader->GetOutputPort());\n texture = vtk.vtkTexture()\n texture.SetInputConnection(img.GetOutputPort())\n\n #vtkSmartPointer<vtkTextureMapToPlane> texturePlane = vtkSmartPointer<vtkTextureMapToPlane>::New();\n #texturePlane->SetInputConnection(plane->GetOutputPort());\n texturePlane = vtk.vtkTextureMapToPlane()\n texturePlane.SetInputConnection(plane.GetOutputPort())\n\n #planeSource.Update()\n #plane = planeSource.GetOutput()\n\n #vtkSmartPointer<vtkPolyDataMapper> planeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n #planeMapper->SetInputConnection(texturePlane->GetOutputPort());\n planeMapper = vtk.vtkPolyDataMapper()\n planeMapper.SetInputConnection(texturePlane.GetOutputPort())\n\n #vtkSmartPointer<vtkActor> texturedPlane = vtkSmartPointer<vtkActor>::New();\n #texturedPlane->SetMapper(planeMapper);\n #texturedPlane->SetTexture(texture);\n texturedPlane = vtk.vtkActor()\n texturedPlane.SetMapper(planeMapper)\n texturedPlane.SetTexture(texture)\n\n # Create a mapper and actor\n #polygonMapper = vtk.vtkPolyDataMapper()\n #if vtk.VTK_MAJOR_VERSION <= 5:\n # polygonMapper.SetInputConnection(texturePlane.GetProducePort())\n #else:\n # polygonMapper.SetInputData(texturePlane.GetOutput())\n # polygonMapper.Update()\n\n #polygonActor = vtk.vtkActor()\n #polygonActor.SetMapper(polygonMapper)\n #polygonActor.SetTexture(texture)\n #polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])\n #polygonActor.GetProperty().SetOpacity(opacity)\n #actor.GetProperty().SetColor(colors->GetColor3d(\"Cyan\").GetData());\n\n self.ren.AddActor(texturedPlane)\n self.actor_list[name] = texturedPlane\n\n def addLines(self, name, points, idx_list = None, line_width = 1, color=np.array([255.0,255.0,255.0])): # points => numpy vector [3, 0~n]\n self.removeActorByName(name)\n vtkpoints = vtk.vtkPoints()\n vtklines = vtk.vtkCellArray()\n colors = vtk.vtkUnsignedCharArray()\n colors.SetNumberOfComponents(3)\n\n points_size = points.shape[0] \n vtkpoints.SetNumberOfPoints(points_size)\n for idx, point in enumerate(points):\n vtkpoints.SetPoint(idx, point[0], point[1], point[2])\n colors.InsertNextTuple(color)\n colors.SetName(name+\"_colors\")\n\n if idx_list is None:\n vtklines.InsertNextCell(points_size)\n for idx in range(points_size):\n vtklines.InsertCellPoint(idx)\n else:\n vtklines.InsertNextCell(len(idx_list))\n for idx in idx_list:\n vtklines.InsertCellPoint(idx)\n\n polygon = vtk.vtkPolyData()\n polygon.SetPoints(vtkpoints)\n polygon.SetLines(vtklines)\n polygon.GetCellData().SetScalars(colors)\n\n polygonMapper = vtk.vtkPolyDataMapper()\n if vtk.VTK_MAJOR_VERSION <= 5:\n polygonMapper.SetInputConnection(polygon.GetProducerPort())\n else:\n polygonMapper.SetInputData(polygon)\n polygonMapper.Update()\n\n polygonActor = vtk.vtkActor()\n polygonActor.SetMapper(polygonMapper)\n polygonActor.GetProperty().SetLineWidth(line_width)\n\n self.ren.AddActor(polygonActor)\n self.actor_list[name] = polygonActor\n\n def addCamera(self, name, R = np.eye(3), t = np.zeros((3,1)), cs = 0.1, line_width = 2, color=np.array([255,255,255])):\n self.removeActorByName(name)\n camera_points = np.zeros((12,3))\n camera_points[0,:] = np.array([-cs/2, -cs/2, cs])\n camera_points[1] = np.array([ cs/2, -cs/2, cs])\n camera_points[2] = np.array([-cs/2, cs/2, cs])\n camera_points[3] = np.array([ cs/2, cs/2, cs])\n camera_points[4] = np.array([-cs/4, -cs/4, cs/2])\n camera_points[5] = np.array([ cs/4, -cs/4, cs/2])\n camera_points[6] = np.array([-cs/4, cs/4, cs/2])\n camera_points[7] = np.array([ cs/4, cs/4, cs/2])\n camera_points[8] = np.array([-cs/4, -cs/4, 0])\n camera_points[9] = np.array([ cs/4, -cs/4, 0])\n camera_points[10] = np.array([-cs/4, cs/4, 0])\n camera_points[11] = np.array([ cs/4, cs/4, 0])\n\n camera_points = np.transpose(camera_points)\n camera_points = np.dot(R, camera_points) + np.matlib.repmat(t, 1, camera_points.shape[1])\n camera_points = np.transpose(camera_points)\n\n points = vtk.vtkPoints()\n points.SetNumberOfPoints(12)\n colors = vtk.vtkUnsignedCharArray()\n points.SetNumberOfPoints(12)\n colors.SetNumberOfComponents(3)\n\n for idx, point in enumerate(camera_points):\n points.SetPoint(idx, point[0], point[1], point[2])\n colors.InsertNextTuple(color)\n colors.SetName(name+\"_colors\")\n\n lines = vtk.vtkCellArray()\n lines.InsertNextCell(24)\n lines.InsertCellPoint(0)\n lines.InsertCellPoint(1)\n lines.InsertCellPoint(3)\n lines.InsertCellPoint(2)\n lines.InsertCellPoint(0)\n lines.InsertCellPoint(4)\n lines.InsertCellPoint(5)\n lines.InsertCellPoint(7)\n lines.InsertCellPoint(6)\n lines.InsertCellPoint(4)\n lines.InsertCellPoint(8)\n lines.InsertCellPoint(9)\n lines.InsertCellPoint(11)\n lines.InsertCellPoint(10)\n lines.InsertCellPoint(8)\n lines.InsertCellPoint(9)\n lines.InsertCellPoint(5)\n lines.InsertCellPoint(1)\n lines.InsertCellPoint(3)\n lines.InsertCellPoint(7)\n lines.InsertCellPoint(11)\n lines.InsertCellPoint(10)\n lines.InsertCellPoint(6)\n lines.InsertCellPoint(2)\n\n polygon = vtk.vtkPolyData()\n polygon.SetPoints(points)\n polygon.SetLines(lines)\n polygon.GetCellData().SetScalars(colors)\n\n polygonMapper = vtk.vtkPolyDataMapper()\n if vtk.VTK_MAJOR_VERSION <= 5:\n polygonMapper.SetInputConnection(polygon.GetProducerPort())\n else:\n polygonMapper.SetInputData(polygon)\n polygonMapper.Update()\n\n polygonActor = vtk.vtkActor()\n polygonActor.SetMapper(polygonMapper)\n polygonActor.GetProperty().SetPointSize(0.1)\n polygonActor.GetProperty().SetLineWidth(line_width)\n self.ren.AddActor(polygonActor)\n self.actor_list[name] = polygonActor\n\n def drawPoints(self, name, point_list, input_color=np.array([[255,0,0]]), point_size = 2):\n self.removeActorByName(name)\n points = vtk.vtkPoints()\n vertices = vtk.vtkCellArray()\n colors = vtk.vtkUnsignedCharArray()\n colors.SetNumberOfComponents(3)\n #colors.SetName(\"Colors\")\n #colors.SetNumberOfComponents(3)\n\n if input_color.shape[0] == 1:\n color_list = np.ones(point_list.shape) * input_color[0]\n else:\n color_list = input_color\n\n for point, color in zip(point_list, color_list):\n id = points.InsertNextPoint(point.tolist())\n vertices.InsertNextCell(1)\n vertices.InsertCellPoint(id)\n colors.InsertNextTuple(color)\n\n point = vtk.vtkPolyData()\n # Set the points and vertices we created as the geometry and topology of the polydata\n point.SetPoints(points)\n point.SetVerts(vertices)\n point.GetPointData().SetScalars(colors)\n\n polygonMapper = vtk.vtkPolyDataMapper()\n if vtk.VTK_MAJOR_VERSION <= 5:\n polygonMapper.SetInputConnection(ps.GetProducerPort())\n else:\n polygonMapper.SetInputData(point)\n polygonMapper.Update()\n polygonActor = vtk.vtkActor()\n polygonActor.SetMapper(polygonMapper)\n polygonActor.GetProperty().SetPointSize(point_size)\n self.ren.AddActor(polygonActor)\n self.actor_list[name] = polygonActor\n\n def render(self):\n self.iren.Render()\n if self.qtwidget_mode == False:\n self.iren.Start()\n\nif __name__ == \"__main__\":\n window_width = 1.18\n window_height = 0.75\n window_points = [[-window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],\n [ window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],\n [-window_width/2, 0, 0],\n [ window_width/2, 0, 0]]\n index = np.array([0,1,3,2,0])\n\n ren = vtkRenderer()\n ren.addLines(np.transpose(window_points), index)\n ren.showImage()" ]
[ [ "numpy.dot", "numpy.matlib.repmat", "numpy.eye", "numpy.linalg.norm", "numpy.transpose", "numpy.ones", "numpy.cross", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wdar/cdippy
[ "ef38b3445351ec8d9d7ea30b5b0d15825d794b0b" ]
[ "cdippy/stndata.py" ]
[ "from datetime import datetime, timedelta\nfrom bisect import bisect_left\n\nimport numpy.ma as ma\n\nfrom cdippy.cdippy import CDIPnc, Archive, Realtime, RealtimeXY, Historic\nimport cdippy.timestamp_utils as tsu\nimport cdippy.utils as cu\n\n\nclass StnData(CDIPnc):\n \"\"\" \n Returns data and metadata for the specified station. \n\n This class handles the problem that neither the Realtime \n nor the Historic .nc file may exist for either data or metadata,\n and the number of deployment files is unknown apriori.\n It tries to seam the multiple station files together.\n \"\"\"\n\n max_deployments = 99 # Checks at most this number of deployment nc files\n\n # Commonly requested sets of variables\n parameter_vars = ['waveHs', 'waveTp', 'waveDp', 'waveTa']\n xyz_vars = ['xyzXDisplacement', 'xyzYDisplacement', 'xyzZDisplacement']\n spectrum_vars = [\n 'waveEnergyDensity', 'waveMeanDirection', \n 'waveA1Value', 'waveB1Value', 'waveA2Value', 'waveB2Value',\n 'waveCheckFactor',]\n meta_vars = [\n 'metaStationName', \n 'metaDeployLatitude', 'metaDeployLongitude', 'metaWaterDepth',\n 'metaDeclilnation']\n meta_attributes = [\n 'wmo_id', \n 'geospatial_lat_min', 'geospatial_lat_max', 'geospatial_lat_units', 'geospatial_lat_resolution',\n 'geospatial_lon_min', 'geospatial_lon_max', 'geospatial_lon_units', 'geospatial_lon_resolution',\n 'geospatial_vertical_min', 'geospatial_vertical_max', 'geospatial_vertical_units', 'geospatial_vertical_resolution',\n 'time_coverage_start', 'time_coverage_end',\n 'date_created', 'date_modified' ]\n \n def __init__(cls, stn, data_dir=None, org=None):\n cls.nc = None\n cls.stn = stn\n cls.data_dir = data_dir\n cls.org = org\n cls.historic = Historic(cls.stn, cls.data_dir, cls.org)\n cls.realtime = Realtime(cls.stn, cls.data_dir, cls.org)\n if cls.historic and cls.historic.nc :\n cls.meta = cls.historic\n else: \n if cls.realtime and cls.realtime.nc :\n cls.meta = cls.realtime\n else:\n return None\n\n def get_parameters(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):\n return cls.get_series(start, end, cls.parameter_vars, pub_set, apply_mask, target_records)\n\n def get_stn_meta(cls):\n \"\"\" Returns a dict of station meta data using historic or realtime file. \"\"\"\n result = {}\n if cls.meta is None:\n return result\n cls.meta.set_request_info(vrs=cls.meta_vars)\n result = cls.meta.get_request()\n for attr_name in cls.meta_attributes:\n if hasattr(cls.meta.nc, attr_name):\n result[attr_name] = getattr(cls.meta.nc, attr_name)\n return result\n\n def get_xyz(cls, start=None, end=None, pub_set='public'):\n return cls.get_series(start, end, cls.xyz_vars, pub_set)\n\n def get_spectra(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):\n return cls.get_series(start, end, cls.spectrum_vars, pub_set, apply_mask, target_records)\n\n def get_series(cls, start=None, end=None, vrs=None, pub_set='public', apply_mask=True, target_records=0):\n \"\"\" \n Returns a dict of data between start and end dates with specified quality. \n\n Use this to get series that may span realtime and historic files. \n If end is None, then start is considered a target date.\n \"\"\"\n if vrs is None:\n vrs = cls.parameter_vars\n prefix = cls.get_var_prefix(vrs[0])\n\n if start is not None and end is None: # Target time\n ts_I = cls.get_target_timespan(cu.datetime_to_timestamp(start), target_records, prefix+'Time')\n if ts_I[0] is not None:\n start = cu.timestamp_to_datetime(ts_I[0])\n end = cu.timestamp_to_datetime(ts_I[1])\n else:\n return None\n elif start is None: # Use default 3 days back\n start = datetime.utcnow()-timedelta(days=3)\n end = datetime.utcnow()\n\n cls.set_request_info(start, end, vrs, pub_set, apply_mask)\n if vrs is not None and prefix == 'xyz':\n return cls.merge_xyz_request()\n else:\n return cls.merge_request()\n\n def aggregate_dicts(cls, dict1, dict2):\n \"\"\" Aggregate the data in two dictionaries. Dict1 has oldest data. \"\"\"\n #- Union the keys to make sure we check each one\n ukeys = set(dict1.keys()) | set(dict2.keys())\n result = { }\n #- Combine the variables\n for key in ukeys :\n if key in dict2 and key in dict1:\n result[key] = ma.concatenate([dict1[key], dict2[key]])\n elif key in dict2:\n result[key] = dict2[key]\n else:\n result[key] = dict1[key]\n return result\n\n def merge_xyz_request(cls):\n \"\"\" Merge xyz data from realtime and archive nc files. \"\"\"\n if cls.vrs and cls.vrs[0] == 'xyzData':\n cls.vrs = ['xyzXDisplacement','xyzYDisplacement','xyzZDisplacement']\n request_timespan = cu.Timespan(cls.start_stamp, cls.end_stamp)\n result = {}\n\n def helper(cdip_nc, request_timespan, result):\n # Try the next file if it is without xyz data\n z = cdip_nc.get_var('xyzZDisplacement')\n if z is None:\n return result, cls.start_stamp\n # Try the next file if start_stamp cannot be calculated\n start_stamp = cdip_nc.get_xyz_timestamp(0)\n end_stamp = cdip_nc.get_xyz_timestamp(len(z)-1)\n if start_stamp is None:\n return result, cls.start_stamp\n file_timespan = cu.Timespan(start_stamp, end_stamp)\n # Add data if request timespan overlaps data timespan\n if request_timespan.overlap(file_timespan):\n cdip_nc.start_stamp = cls.start_stamp\n cdip_nc.end_stamp = cls.end_stamp\n cdip_nc.pub_set = cls.pub_set\n cdip_nc.apply_mask = cls.apply_mask\n cdip_nc.vrs = cls.vrs\n tmp_result = cdip_nc.get_request()\n result = cls.aggregate_dicts(result, tmp_result)\n return result, start_stamp\n\n # First get realtime data if it exists\n rt = RealtimeXY(cls.stn)\n if rt.nc is not None:\n result, start_stamp = helper(rt, request_timespan, result)\n\n # If the request start time is more recent than the realtime\n # start time, no need to look in the archives\n if cls.start_stamp > start_stamp:\n return result\n\n # Second, look in archive files for data\n for dep in range(1, cls.max_deployments):\n deployment = 'd'+'{:02d}'.format(dep)\n ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)\n if ar.nc is None:\n break\n result, start_stamp = helper(ar, request_timespan, result)\n \n # Break if file start stamp is greater than request end stamp\n if start_stamp > cls.end_stamp :\n break\n return result\n\n def merge_request(cls):\n \"\"\" Returns data for given request across realtime and historic files \"\"\"\n rt = {};\n r = cls.realtime\n # Note that we are assuming that waveTime will work for every time dim.\n if r.nc is not None and r.get_var('waveTime')[0] <= cls.end_stamp:\n r.vrs = cls.vrs\n r.start_stamp = cls.start_stamp\n r.end_stamp = cls.end_stamp\n r.pub_set = cls.pub_set\n r.apply_mask = cls.apply_mask\n rt = r.get_request()\n ht = {};\n h = cls.historic\n if h.nc is not None and h.get_var('waveTime')[-1] >= cls.start_stamp:\n h.vrs = cls.vrs\n h.start_stamp = cls.start_stamp\n h.end_stamp = cls.end_stamp\n h.pub_set = cls.pub_set\n h.apply_mask = cls.apply_mask\n ht = h.get_request()\n return cls.aggregate_dicts(ht, rt)\n\n def get_nc_files(cls, types=['realtime','historic','archive']):\n \"\"\" Returns dict of netcdf4 objects of a station's netcdf files \"\"\"\n result = {}\n for type in types:\n if type == 'realtime':\n rt = Realtime(cls.stn, cls.data_dir, cls.org)\n if rt.nc:\n result[rt.filename] = rt.nc\n if type == 'historic':\n ht = Historic(cls.stn, cls.data_dir, cls.org)\n if ht.nc:\n result[ht.filename] = ht.nc\n if type == 'archive':\n for dep in range(1,cls.max_deployments):\n deployment = 'd'+'{:02d}'.format(dep)\n ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)\n if ar.nc is None:\n break\n result[ar.filename] = ar\n return result\n\n def get_target_timespan(cls, target_timestamp, n, time_var):\n \"\"\" \n Returns a 2-tuple of timestamps, an interval corresponding to n records to \n the right or left of target_timestamp.\n \n Given a time_var (e.g. 'waveTime') and target timestamp, returns a 2-tuple \n of timestamps corresponding to i and i+n (n<0 or n>=0) taken from\n the realtime and historic nc files. Those timestamps can then be used in\n set_request_info().\n \"\"\"\n r_ok = False\n if cls.realtime.nc is not None:\n r_ok = True\n h_ok = False\n if cls.historic.nc is not None:\n h_ok = True\n\n # Check realtime to find closest index\n\n r_closest_idx = None\n if r_ok: \n r_stamps = cls.realtime.get_var(time_var)[:] \n r_last_idx = len(r_stamps) - 1\n i_b = bisect_left(r_stamps, target_timestamp)\n # i_b will be possibly one more than the last index\n i_b = min(i_b, r_last_idx)\n # Target timestamp is exactly equal to a data time \n if i_b == r_last_idx or r_stamps[i_b] == target_timestamp:\n r_closest_idx = i_b\n elif i_b > 0:\n r_closest_idx = tsu.get_closest_index(i_b-1, i_b, r_stamps, target_timestamp)\n\n # If closest index not found, check historic\n\n h_closest_idx = None\n h_last_idx = None # Let's us know if h_stamps has been loaded\n if h_ok and not r_closest_idx:\n h_stamps = cls.historic.get_var(time_var)[:] \n h_last_idx = len(h_stamps) - 1\n i_b = bisect_left(h_stamps, target_timestamp)\n i_b = min(i_b, h_last_idx)\n # Target timestamp is exactly equal to a data time \n if (i_b <= h_last_idx and h_stamps[i_b] == target_timestamp) or i_b == 0:\n h_closest_idx = i_b\n elif i_b >= h_last_idx: # Target is between the two files\n if r_ok:\n if abs(h_stamps[h_last_idx]-target_timestamp) < abs(r_stamps[0]-target_timestamp):\n h_closest_idx = i_b\n else:\n r_closest_idx = 0\n else: # No realtime file \n h_closest_idx = i_b\n else: # Within middle of historic stamps\n h_closest_idx = tsu.get_closest_index(i_b-1, i_b, h_stamps, target_timestamp)\n\n # Now we have the closest index, find the intervals\n\n if r_closest_idx is not None:\n r_interval = tsu.get_interval(r_stamps, r_closest_idx, n)\n # If bound exceeded toward H and H exists, cacluate h_interval\n if r_interval[2] < 0 and h_ok:\n if not h_last_idx:\n h_stamps = cls.historic.get_var(time_var)[:] \n h_last_idx = len(h_stamps) - 1\n h_interval = tsu.get_interval(h_stamps, h_last_idx, n+r_closest_idx+1)\n #print(\"Rx H interval: \", h_interval)\n #print(\"Rx R interval: \", r_interval)\n return tsu.combine_intervals(h_interval, r_interval)\n else:\n return r_interval \n elif h_closest_idx is not None:\n h_interval = tsu.get_interval(h_stamps, h_closest_idx, n)\n # If bound exceeded toward R and R exists, cacluate r_interval\n if h_interval[2] > 0 and r_ok: \n r_interval = tsu.get_interval(r_stamps, 0, n+h_closest_idx-h_last_idx-1)\n #print(\"Hx H interval: \", h_interval)\n #print(\"Hx R interval: \", r_interval)\n return tsu.combine_intervals(h_interval, r_interval)\n else:\n return h_interval \n\n # If we get to here there's a problem\n return (None, None, None)\n\nif __name__ == \"__main__\":\n #- Tests\n def t0():\n s = StnData('100p1')\n d = s.get_stn_meta()\n print(d)\n def t1():\n s = StnData('100p1')\n d = s.get_spectra(datetime(2016,8,1), target_records=3)\n print(d.keys())\n print(d['waveEnergyDensity'].shape)\n def t2():\n s = StnData('100p1',org='ww3')\n d = s.get_series('2016-08-01 00:00:00','2016-08-02 23:59:59',['waveHs'],'public')\n print(d)\n def t3():\n s = StnData('100p1',data_dir='./gdata')\n d = s.get_nc_files(['historic','archive','realtime'])\n print(d.keys())\n def t4():\n s = StnData('100p1')\n # Across deployments 5 and 6\n d = s.get_series('2007-05-30 00:00:00','2007-06-01 23:59:59',['xyzData'],'public')\n print(len(d['xyzXDisplacement']))\n print(len(d['xyzTime']))\n print(d['xyzTime'][0],d['xyzTime'][-1])\n def t5():\n s = StnData('100p1')\n dt = datetime(2010,4,1,0,0)\n d = s.get_series(dt, target_records=-4)\n print(d)\n def t6():\n # Mark 1 filter delay set to -999.9\n s = StnData('071p1')\n end = datetime.utcnow()\n end = datetime(1996,1,22,15,57,00)\n start = end - timedelta(hours=2)\n d = s.get_xyz(start, end)\n print(\"D: \"+repr(d))\n print(\"Len: \"+repr(len(d['xyzTime'])))\n\n t6()\n" ]
[ [ "numpy.ma.concatenate" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
zoumt1633/pytorch-project-template
[ "871e00ebde6c2191de5f61b4cb7010c72b93c198" ]
[ "model/model.py" ]
[ "import torch\nimport torch.nn\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\nfrom collections import OrderedDict\nimport os.path as osp\nimport wandb\n\nfrom utils.utils import DotDict\n\n\nclass Model:\n def __init__(self, hp, net_arch, loss_f, rank=0, world_size=1):\n self.hp = hp\n self.device = self.hp.model.device\n self.net = net_arch.to(self.device)\n self.rank = rank\n self.world_size = world_size\n if self.device != \"cpu\" and self.world_size != 0:\n self.net = DDP(self.net, device_ids=[self.rank])\n self.input = None\n self.GT = None\n self.step = 0\n self.epoch = -1\n\n # init optimizer\n optimizer_mode = self.hp.train.optimizer.mode\n if optimizer_mode == \"adam\":\n self.optimizer = torch.optim.Adam(\n self.net.parameters(), **(self.hp.train.optimizer[optimizer_mode])\n )\n else:\n raise Exception(\"%s optimizer not supported\" % optimizer_mode)\n\n # init loss\n self.loss_f = loss_f\n self.log = DotDict()\n\n def feed_data(self, **data): # data's keys: input, GT\n for k, v in data.items():\n data[k] = v.to(self.device)\n self.input = data.get(\"input\")\n self.GT = data.get(\"GT\")\n\n def optimize_parameters(self):\n self.net.train()\n self.optimizer.zero_grad()\n output = self.run_network()\n loss_v = self.loss_f(output, self.GT)\n loss_v.backward()\n self.optimizer.step()\n\n # set log\n self.log.loss_v = loss_v.item()\n\n def inference(self):\n self.net.eval()\n output = self.run_network()\n return output\n\n def run_network(self):\n output = self.net(self.input)\n return output\n\n def save_network(self, logger, save_file=True):\n if self.rank == 0:\n net = self.net.module if isinstance(self.net, DDP) else self.net\n state_dict = net.state_dict()\n for key, param in state_dict.items():\n state_dict[key] = param.to(\"cpu\")\n if save_file:\n save_filename = \"%s_%d.pt\" % (self.hp.log.name, self.step)\n save_path = osp.join(self.hp.log.chkpt_dir, save_filename)\n torch.save(state_dict, save_path)\n if self.hp.log.use_wandb:\n wandb.save(save_path)\n if logger is not None:\n logger.info(\"Saved network checkpoint to: %s\" % save_path)\n return state_dict\n\n def load_network(self, loaded_net=None, logger=None):\n add_log = False\n if loaded_net is None:\n add_log = True\n if self.hp.load.wandb_load_path is not None:\n self.hp.load.network_chkpt_path = wandb.restore(\n self.hp.load.network_chkpt_path,\n run_path=self.hp.load.wandb_load_path,\n ).name\n loaded_net = torch.load(\n self.hp.load.network_chkpt_path, map_location=torch.device(self.device)\n )\n loaded_clean_net = OrderedDict() # remove unnecessary 'module.'\n for k, v in loaded_net.items():\n if k.startswith(\"module.\"):\n loaded_clean_net[k[7:]] = v\n else:\n loaded_clean_net[k] = v\n\n self.net.load_state_dict(loaded_clean_net, strict=self.hp.load.strict_load)\n if logger is not None and add_log:\n logger.info(\"Checkpoint %s is loaded\" % self.hp.load.network_chkpt_path)\n\n def save_training_state(self, logger):\n if self.rank == 0:\n save_filename = \"%s_%d.state\" % (self.hp.log.name, self.step)\n save_path = osp.join(self.hp.log.chkpt_dir, save_filename)\n net_state_dict = self.save_network(None, False)\n state = {\n \"model\": net_state_dict,\n \"optimizer\": self.optimizer.state_dict(),\n \"step\": self.step,\n \"epoch\": self.epoch,\n }\n torch.save(state, save_path)\n if self.hp.log.use_wandb:\n wandb.save(save_path)\n if logger is not None:\n logger.info(\"Saved training state to: %s\" % save_path)\n\n def load_training_state(self, logger):\n if self.hp.load.wandb_load_path is not None:\n self.hp.load.resume_state_path = wandb.restore(\n self.hp.load.resume_state_path, run_path=self.hp.load.wandb_load_path\n ).name\n resume_state = torch.load(\n self.hp.load.resume_state_path, map_location=torch.device(self.device)\n )\n\n self.load_network(loaded_net=resume_state[\"model\"], logger=logger)\n self.optimizer.load_state_dict(resume_state[\"optimizer\"])\n self.step = resume_state[\"step\"]\n self.epoch = resume_state[\"epoch\"]\n if logger is not None:\n logger.info(\n \"Resuming from training state: %s\" % self.hp.load.resume_state_path\n )\n" ]
[ [ "torch.device", "torch.nn.parallel.DistributedDataParallel", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ericagol/exoplanet
[ "ec270622f28cd53d3052ed44d20f30b5d2b4dcb6" ]
[ "src/exoplanet/distributions/physical_test.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pymc3 as pm\nfrom scipy.stats import kstest\n\nfrom .base_test import _Base\nfrom .physical import ImpactParameter, QuadLimbDark\n\n\nclass TestPhysical(_Base):\n random_seed = 19860925\n\n def test_quad_limb_dark(self):\n with self._model():\n dist = QuadLimbDark(\"u\", shape=2)\n\n # Test random sampling\n samples = dist.random(size=100)\n assert np.shape(samples) == (100, 2)\n\n logp = QuadLimbDark.dist(shape=2).logp(samples).eval().flatten()\n assert np.all(np.isfinite(logp))\n assert np.allclose(logp[0], logp)\n\n trace = self._sample()\n\n u1 = trace[\"u\"][:, 0]\n u2 = trace[\"u\"][:, 1]\n\n # Make sure that the physical constraints are satisfied\n assert np.all(u1 + u2 < 1)\n assert np.all(u1 > 0)\n assert np.all(u1 + 2 * u2 > 0)\n\n # Make sure that the qs are uniform\n q1 = (u1 + u2) ** 2\n q2 = 0.5 * u1 / (u1 + u2)\n\n cdf = lambda x: np.clip(x, 0, 1) # NOQA\n for q in (q1, q2):\n s, p = kstest(q, cdf)\n assert s < 0.05\n\n def test_impact(self):\n lower = 0.1\n upper = 1.0\n with self._model():\n ror = pm.Uniform(\"ror\", lower=lower, upper=upper, shape=(5, 2))\n dist = ImpactParameter(\"b\", ror=ror)\n\n # Test random sampling\n samples = dist.random(size=100)\n assert np.shape(samples) == (100, 5, 2)\n assert np.all((0 <= samples) & (samples <= 1 + upper))\n\n trace = self._sample()\n\n u = trace[\"ror\"]\n u = np.reshape(u, (len(u), -1))\n cdf = lambda x: np.clip((x - lower) / (upper - lower), 0, 1) # NOQA\n for i in range(u.shape[1]):\n s, p = kstest(u[:, i], cdf)\n assert s < 0.05\n\n assert np.all(trace[\"b\"] <= 1 + trace[\"ror\"])\n" ]
[ [ "scipy.stats.kstest", "numpy.allclose", "numpy.isfinite", "numpy.clip", "numpy.all", "numpy.shape" ] ]
[ { "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": [] } ]
Leopard-X/MXNET
[ "7ac046c58f0815223712f77288722a7b06755ec3" ]
[ "python/mxnet/image.py" ]
[ "# pylint: disable=no-member, too-many-lines, redefined-builtin, protected-access, unused-import, invalid-name\n# pylint: disable=too-many-arguments, too-many-locals, no-name-in-module, too-many-branches, too-many-statements\n\"\"\"Read invidual image files and perform augmentations.\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport random\nimport logging\nimport numpy as np\n\ntry:\n import cv2\nexcept ImportError:\n cv2 = None\n\nfrom .base import numeric_types\nfrom . import ndarray as nd\nfrom . import _ndarray_internal as _internal\nfrom ._ndarray_internal import _cvimresize as imresize\nfrom ._ndarray_internal import _cvcopyMakeBorder as copyMakeBorder\nfrom . import io\nfrom . import recordio\n\n\ndef imdecode(buf, **kwargs):\n \"\"\"Decode an image to an NDArray.\n\n Note: `imdecode` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with OpenCV for `imdecode` to work.\n\n Parameters\n ----------\n buf : str/bytes or numpy.ndarray\n Binary image data as string or numpy ndarray.\n flag : int, optional, default=1\n 1 for three channel color output. 0 for grayscale output.\n to_rgb : int, optional, default=1\n 1 for RGB formatted output (MXNet default). 0 for BGR formatted output (OpenCV default).\n out : NDArray, optional\n Output buffer. Use `None` for automatic allocation.\n\n Returns\n -------\n NDArray\n An `NDArray` containing the image.\n\n Example\n -------\n >>> with open(\"flower.jpg\", 'rb') as fp:\n ... str_image = fp.read()\n ...\n >>> image = mx.img.imdecode(str_image)\n >>> image\n <NDArray 224x224x3 @cpu(0)>\n\n Set `flag` parameter to 0 to get grayscale output\n\n >>> with open(\"flower.jpg\", 'rb') as fp:\n ... str_image = fp.read()\n ...\n >>> image = mx.img.imdecode(str_image, flag=0)\n >>> image\n <NDArray 224x224x1 @cpu(0)>\n\n Set `to_rgb` parameter to 0 to get output in OpenCV format (BGR)\n\n >>> with open(\"flower.jpg\", 'rb') as fp:\n ... str_image = fp.read()\n ...\n >>> image = mx.img.imdecode(str_image, to_rgb=0)\n >>> image\n <NDArray 224x224x3 @cpu(0)>\n \"\"\"\n if not isinstance(buf, nd.NDArray):\n buf = nd.array(np.frombuffer(buf, dtype=np.uint8), dtype=np.uint8)\n return _internal._cvimdecode(buf, **kwargs)\n\n\ndef scale_down(src_size, size):\n \"\"\"Scales down crop size if it's larger than image size.\n\n If width/height of the crop is larger than the width/height of the image,\n sets the width/height to the width/height of the image.\n\n Parameters\n ----------\n src_size : tuple of int\n Size of the image in (width, height) format.\n size : tuple of int\n Size of the crop in (width, height) format.\n\n Returns\n -------\n tuple of int\n A tuple containing the scaled crop size in (width, height) format.\n\n Example\n --------\n >>> src_size = (640,480)\n >>> size = (720,120)\n >>> new_size = mx.img.scale_down(src_size, size)\n >>> new_size\n (640,106)\n \"\"\"\n w, h = size\n sw, sh = src_size\n if sh < h:\n w, h = float(w * sh) / h, sh\n if sw < w:\n w, h = sw, float(h * sw) / w\n return int(w), int(h)\n\n\ndef resize_short(src, size, interp=2):\n \"\"\"Resizes shorter edge to size.\n\n Note: `resize_short` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with OpenCV for `resize_short` to work.\n\n Resizes the original image by setting the shorter edge to size\n and setting the longer edge accordingly.\n Resizing function is called from OpenCV.\n\n Parameters\n ----------\n src : NDArray\n The original image.\n size : int\n The length to be set for the shorter edge.\n interp : int, optional, default=2\n Interpolation method used for resizing the image.\n Default method is bicubic interpolation.\n More details can be found in the documentation of OpenCV, please refer to\n http://docs.opencv.org/master/da/d54/group__imgproc__transform.html.\n\n Returns\n -------\n NDArray\n An 'NDArray' containing the resized image.\n\n Example\n -------\n >>> with open(\"flower.jpeg\", 'rb') as fp:\n ... str_image = fp.read()\n ...\n >>> image = mx.img.imdecode(str_image)\n >>> image\n <NDArray 2321x3482x3 @cpu(0)>\n >>> size = 640\n >>> new_image = mx.img.resize_short(image, size)\n >>> new_image\n <NDArray 2321x3482x3 @cpu(0)>\n \"\"\"\n h, w, _ = src.shape\n if h > w:\n new_h, new_w = size * h / w, size\n else:\n new_h, new_w = size, size * w / h\n return imresize(src, new_w, new_h, interp=interp)\n\n\ndef fixed_crop(src, x0, y0, w, h, size=None, interp=2):\n \"\"\"Crop src at fixed location, and (optionally) resize it to size.\"\"\"\n out = nd.crop(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2])))\n if size is not None and (w, h) != size:\n out = imresize(out, *size, interp=interp)\n return out\n\n\ndef random_crop(src, size, interp=2):\n \"\"\"Randomly crop `src` with `size` (width, height).\n Upsample result if `src` is smaller than `size`.\n\n Parameters\n ----------\n src: Source image `NDArray`\n size: Size of the crop formatted as (width, height). If the `size` is larger\n than the image, then the source image is upsampled to `size` and returned.\n interp: Interpolation method to be used in case the size is larger (default: bicubic).\n Uses OpenCV convention for the parameters. Nearest - 0, Bilinear - 1, Bicubic - 2,\n Area - 3. See OpenCV imresize function for more details.\n Returns\n -------\n NDArray\n An `NDArray` containing the cropped image.\n Tuple\n A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the\n original image and (width, height) are the dimensions of the cropped image.\n\n Example\n -------\n >>> im = mx.nd.array(cv2.imread(\"flower.jpg\"))\n >>> cropped_im, rect = mx.image.random_crop(im, (100, 100))\n >>> print cropped_im\n <NDArray 100x100x1 @cpu(0)>\n >>> print rect\n (20, 21, 100, 100)\n \"\"\"\n\n h, w, _ = src.shape\n new_w, new_h = scale_down((w, h), size)\n\n x0 = random.randint(0, w - new_w)\n y0 = random.randint(0, h - new_h)\n\n out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)\n return out, (x0, y0, new_w, new_h)\n\n\ndef center_crop(src, size, interp=2):\n \"\"\"Crops the image `src` to the given `size` by trimming on all four\n sides and preserving the center of the image. Upsamples if `src` is smaller\n than `size`.\n\n .. note:: This requires MXNet to be compiled with USE_OPENCV.\n\n Parameters\n ----------\n src : NDArray\n Binary source image data.\n size : list or tuple of int\n The desired output image size.\n interp : interpolation, optional, default=Area-based\n The type of interpolation that is done to the image.\n\n Possible values:\n\n 0: Nearest Neighbors Interpolation.\n\n 1: Bilinear interpolation.\n\n 2: Area-based (resampling using pixel area relation). It may be a\n preferred method for image decimation, as it gives moire-free\n results. But when the image is zoomed, it is similar to the Nearest\n Neighbors method. (used by default).\n\n 3: Bicubic interpolation over 4x4 pixel neighborhood.\n\n 4: Lanczos interpolation over 8x8 pixel neighborhood.\n\n When shrinking an image, it will generally look best with AREA-based\n interpolation, whereas, when enlarging an image, it will generally look best\n with Bicubic (slow) or Bilinear (faster but still looks OK).\n\n Returns\n -------\n NDArray\n The cropped image.\n Tuple\n (x, y, width, height) where x, y are the positions of the crop in the\n original image and width, height the dimensions of the crop.\n\n Example\n -------\n >>> with open(\"flower.jpg\", 'rb') as fp:\n ... str_image = fp.read()\n ...\n >>> image = mx.image.imdecode(str_image)\n >>> image\n <NDArray 2321x3482x3 @cpu(0)>\n >>> cropped_image, (x, y, width, height) = mx.image.center_crop(image, (1000, 500))\n >>> cropped_image\n <NDArray 500x1000x3 @cpu(0)>\n >>> x, y, width, height\n (1241, 910, 1000, 500)\n \"\"\"\n\n h, w, _ = src.shape\n new_w, new_h = scale_down((w, h), size)\n\n x0 = int((w - new_w) / 2)\n y0 = int((h - new_h) / 2)\n\n out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)\n return out, (x0, y0, new_w, new_h)\n\n\ndef color_normalize(src, mean, std=None):\n \"\"\"Normalize src with mean and std.\"\"\"\n src -= mean\n if std is not None:\n src /= std\n return src\n\n\ndef random_size_crop(src, size, min_area, ratio, interp=2):\n \"\"\"Randomly crop src with size. Randomize area and aspect ratio.\"\"\"\n h, w, _ = src.shape\n new_ratio = random.uniform(*ratio)\n if new_ratio * h > w:\n max_area = w * int(w / new_ratio)\n else:\n max_area = h * int(h * new_ratio)\n\n min_area *= h * w\n if max_area < min_area:\n return random_crop(src, size, interp)\n new_area = random.uniform(min_area, max_area)\n new_w = int(np.sqrt(new_area * new_ratio))\n new_h = int(np.sqrt(new_area / new_ratio))\n\n assert new_w <= w and new_h <= h\n x0 = random.randint(0, w - new_w)\n y0 = random.randint(0, h - new_h)\n\n out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)\n return out, (x0, y0, new_w, new_h)\n\n\ndef ResizeAug(size, interp=2):\n \"\"\"Make resize shorter edge to size augmenter.\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n return [resize_short(src, size, interp)]\n\n return aug\n\n\ndef RandomCropAug(size, interp=2):\n \"\"\"Make random crop augmenter\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n return [random_crop(src, size, interp)[0]]\n\n return aug\n\n\ndef RandomSizedCropAug(size, min_area, ratio, interp=2):\n \"\"\"Make random crop with random resizing and random aspect ratio jitter augmenter.\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n return [random_size_crop(src, size, min_area, ratio, interp)[0]]\n\n return aug\n\n\ndef CenterCropAug(size, interp=2):\n \"\"\"Make center crop augmenter.\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n return [center_crop(src, size, interp)[0]]\n\n return aug\n\n\ndef RandomOrderAug(ts):\n \"\"\"Apply list of augmenters in random order\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n src = [src]\n random.shuffle(ts)\n for t in ts:\n src = [j for i in src for j in t(i)]\n return src\n\n return aug\n\n\ndef ColorJitterAug(brightness, contrast, saturation):\n \"\"\"Apply random brightness, contrast and saturation jitter in random order.\"\"\"\n ts = []\n coef = nd.array([[[0.299, 0.587, 0.114]]])\n if brightness > 0:\n def baug(src):\n \"\"\"Augmenter body\"\"\"\n alpha = 1.0 + random.uniform(-brightness, brightness)\n src *= alpha\n return [src]\n\n ts.append(baug)\n\n if contrast > 0:\n def caug(src):\n \"\"\"Augmenter body\"\"\"\n alpha = 1.0 + random.uniform(-contrast, contrast)\n gray = src * coef\n gray = (3.0 * (1.0 - alpha) / gray.size) * nd.sum(gray)\n src *= alpha\n src += gray\n return [src]\n\n ts.append(caug)\n\n if saturation > 0:\n def saug(src):\n \"\"\"Augmenter body\"\"\"\n alpha = 1.0 + random.uniform(-saturation, saturation)\n gray = src * coef\n gray = nd.sum(gray, axis=2, keepdims=True)\n gray *= (1.0 - alpha)\n src *= alpha\n src += gray\n return [src]\n\n ts.append(saug)\n return RandomOrderAug(ts)\n\n\ndef LightingAug(alphastd, eigval, eigvec):\n \"\"\"Add PCA based noise.\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n alpha = np.random.normal(0, alphastd, size=(3,))\n rgb = np.dot(eigvec * alpha, eigval)\n src += nd.array(rgb)\n return [src]\n\n return aug\n\n\ndef ColorNormalizeAug(mean, std):\n \"\"\"Mean and std normalization.\"\"\"\n mean = nd.array(mean)\n std = nd.array(std)\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n return [color_normalize(src, mean, std)]\n\n return aug\n\n\ndef HorizontalFlipAug(p):\n \"\"\"Random horizontal flipping.\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n if random.random() < p:\n src = nd.flip(src, axis=1)\n return [src]\n\n return aug\n\n\ndef CastAug():\n \"\"\"Cast to float32\"\"\"\n\n def aug(src):\n \"\"\"Augmenter body\"\"\"\n src = src.astype(np.float32)\n return [src]\n\n return aug\n\n\ndef CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,\n mean=None, std=None, brightness=0, contrast=0, saturation=0,\n pca_noise=0, inter_method=2):\n \"\"\"Creates an augmenter list.\"\"\"\n auglist = []\n\n if resize > 0:\n auglist.append(ResizeAug(resize, inter_method))\n\n crop_size = (data_shape[2], data_shape[1])\n if rand_resize:\n assert rand_crop\n auglist.append(RandomSizedCropAug(crop_size, 0.3, (3.0 / 4.0, 4.0 / 3.0), inter_method))\n elif rand_crop:\n auglist.append(RandomCropAug(crop_size, inter_method))\n else:\n auglist.append(CenterCropAug(crop_size, inter_method))\n\n if rand_mirror:\n auglist.append(HorizontalFlipAug(0.5))\n\n auglist.append(CastAug())\n\n if brightness or contrast or saturation:\n auglist.append(ColorJitterAug(brightness, contrast, saturation))\n\n if pca_noise > 0:\n eigval = np.array([55.46, 4.794, 1.148])\n eigvec = np.array([[-0.5675, 0.7192, 0.4009],\n [-0.5808, -0.0045, -0.8140],\n [-0.5836, -0.6948, 0.4203]])\n auglist.append(LightingAug(pca_noise, eigval, eigvec))\n\n if mean is True:\n mean = np.array([123.68, 116.28, 103.53])\n elif mean is not None:\n assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3]\n\n if std is True:\n std = np.array([58.395, 57.12, 57.375])\n elif std is not None:\n assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3]\n\n if mean is not None and std is not None:\n auglist.append(ColorNormalizeAug(mean, std))\n\n return auglist\n\n\nclass ImageIter(io.DataIter):\n \"\"\"Image data iterator with a large number of augmentation choices.\n This iterator supports reading from both .rec files and raw image files.\n\n To load input images from .rec files, use `path_imgrec` parameter and to load from raw image\n files, use `path_imglist` and `path_root` parameters.\n\n To use data partition (for distributed training) or shuffling, specify `path_imgidx` parameter.\n\n Parameters\n ----------\n batch_size : int\n Number of examples per batch.\n data_shape : tuple\n Data shape in (channels, height, width) format.\n For now, only RGB image with 3 channels is supported.\n label_width : int, optional\n Number of labels per example. The default label width is 1.\n path_imgrec : str\n Path to image record file (.rec).\n Created with tools/im2rec.py or bin/im2rec.\n path_imglist : str\n Path to image list (.lst).\n Created with tools/im2rec.py or with custom script.\n Format: Tab separated record of index, one or more labels and relative_path_from_root.\n imglist: list\n A list of images with the label(s).\n Each item is a list [imagelabel: float or list of float, imgpath].\n path_root : str\n Root folder of image files.\n path_imgidx : str\n Path to image index file. Needed for partition and shuffling when using .rec source.\n shuffle : bool\n Whether to shuffle all images at the start of each iteration or not.\n Can be slow for HDD.\n part_index : int\n Partition index.\n num_parts : int\n Total number of partitions.\n data_name : str\n Data name for provided symbols.\n label_name : str\n Label name for provided symbols.\n kwargs : ...\n More arguments for creating augmenter. See mx.image.CreateAugmenter.\n \"\"\"\n\n def __init__(self, batch_size, data_shape, label_width=1,\n path_imgrec=None, path_imglist=None, path_root=None, path_imgidx=None,\n shuffle=False, part_index=0, num_parts=1, aug_list=None, imglist=None,\n data_name='data', label_name='softmax_label', **kwargs):\n super(ImageIter, self).__init__()\n assert path_imgrec or path_imglist or (isinstance(imglist, list))\n if path_imgrec:\n print('loading recordio...')\n if path_imgidx:\n self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r') # pylint: disable=redefined-variable-type\n self.imgidx = list(self.imgrec.keys)\n else:\n self.imgrec = recordio.MXRecordIO(path_imgrec, 'r') # pylint: disable=redefined-variable-type\n self.imgidx = None\n else:\n self.imgrec = None\n\n if path_imglist:\n print('loading image list...')\n with open(path_imglist) as fin:\n imglist = {}\n imgkeys = []\n for line in iter(fin.readline, ''):\n line = line.strip().split('\\t')\n label = nd.array([float(i) for i in line[1:-1]])\n key = int(line[0])\n imglist[key] = (label, line[-1])\n imgkeys.append(key)\n self.imglist = imglist\n elif isinstance(imglist, list):\n print('loading image list...')\n result = {}\n imgkeys = []\n index = 1\n for img in imglist:\n key = str(index) # pylint: disable=redefined-variable-type\n index += 1\n if isinstance(img[0], numeric_types):\n label = nd.array([img[0]])\n else:\n label = nd.array(img[0])\n result[key] = (label, img[1])\n imgkeys.append(str(key))\n self.imglist = result\n else:\n self.imglist = None\n self.path_root = path_root\n\n self.check_data_shape(data_shape)\n self.provide_data = [(data_name, (batch_size,) + data_shape)]\n if label_width > 1:\n self.provide_label = [(label_name, (batch_size, label_width))]\n else:\n self.provide_label = [(label_name, (batch_size,))]\n self.batch_size = batch_size\n self.data_shape = data_shape\n self.label_width = label_width\n\n self.shuffle = shuffle\n if self.imgrec is None:\n self.seq = imgkeys\n elif shuffle or num_parts > 1:\n assert self.imgidx is not None\n self.seq = self.imgidx\n else:\n self.seq = None\n\n if num_parts > 1:\n assert part_index < num_parts\n N = len(self.seq)\n C = N / num_parts\n self.seq = self.seq[part_index * C:(part_index + 1) * C]\n if aug_list is None:\n self.auglist = CreateAugmenter(data_shape, **kwargs)\n else:\n self.auglist = aug_list\n self.cur = 0\n self.reset()\n\n def reset(self):\n \"\"\"Resets the iterator to the beginning of the data.\"\"\"\n if self.shuffle:\n random.shuffle(self.seq)\n if self.imgrec is not None:\n self.imgrec.reset()\n self.cur = 0\n\n def next_sample(self):\n \"\"\"Helper function for reading in next sample.\"\"\"\n if self.seq is not None:\n if self.cur >= len(self.seq):\n raise StopIteration\n idx = self.seq[self.cur]\n self.cur += 1\n if self.imgrec is not None:\n s = self.imgrec.read_idx(idx)\n header, img = recordio.unpack(s)\n if self.imglist is None:\n return header.label, img\n else:\n return self.imglist[idx][0], img\n else:\n label, fname = self.imglist[idx]\n return label, self.read_image(fname)\n else:\n s = self.imgrec.read()\n if s is None:\n raise StopIteration\n header, img = recordio.unpack(s)\n return header.label, img\n\n def next(self):\n \"\"\"Returns the next batch of data.\"\"\"\n batch_size = self.batch_size\n c, h, w = self.data_shape\n batch_data = nd.empty((batch_size, c, h, w))\n batch_label = nd.empty(self.provide_label[0][1])\n i = 0\n try:\n while i < batch_size:\n label, s = self.next_sample()\n data = [self.imdecode(s)]\n try:\n self.check_valid_image(data)\n except RuntimeError as e:\n logging.debug('Invalid image, skipping: %s', str(e))\n continue\n data = self.augmentation_transform(data)\n for datum in data:\n assert i < batch_size, 'Batch size must be multiples of augmenter output length'\n batch_data[i][:] = self.postprocess_data(datum)\n batch_label[i][:] = label\n i += 1\n except StopIteration:\n if not i:\n raise StopIteration\n\n return io.DataBatch([batch_data], [batch_label], batch_size - i)\n\n def check_data_shape(self, data_shape):\n \"\"\"Checks if the input data shape is valid\"\"\"\n if not len(data_shape) == 3:\n raise ValueError('data_shape should have length 3, with dimensions CxHxW')\n if not data_shape[0] == 3:\n raise ValueError('This iterator expects inputs to have 3 channels.')\n\n def check_valid_image(self, data):\n \"\"\"Checks if the input data is valid\"\"\"\n if len(data[0].shape) == 0:\n raise RuntimeError('Data shape is wrong')\n\n def imdecode(self, s):\n \"\"\"Decodes a string or byte string to an NDArray.\n See mx.img.imdecode for more details.\"\"\"\n return imdecode(s)\n\n def read_image(self, fname):\n \"\"\"Reads an input image `fname` and returns the decoded raw bytes.\n\n Example usage:\n ----------\n >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.\n '\\xff\\xd8\\xff\\xe0\\x00...'\n \"\"\"\n with open(os.path.join(self.path_root, fname), 'rb') as fin:\n img = fin.read()\n return img\n\n def augmentation_transform(self, data):\n \"\"\"Transforms input data with specified augmentation.\"\"\"\n for aug in self.auglist:\n data = [ret for src in data for ret in aug(src)]\n return data\n\n def postprocess_data(self, datum):\n \"\"\"Final postprocessing step before image is loaded into the batch.\"\"\"\n return nd.transpose(datum, axes=(2, 0, 1))\n" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.frombuffer", "numpy.random.normal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qma16443/AIcamp_MTCNN
[ "431c3ce1cabf24266690322d525bdf7133666dc0" ]
[ "Detection/MtcnnDetector.py" ]
[ "import cv2\nimport time\nimport numpy as np\nimport sys\nsys.path.append(\"../\")\nfrom train_models.MTCNN_config import config\nfrom Detection.nms import py_nms\n\n\nclass MtcnnDetector(object):\n\n\n def __init__(self,\n detectors,\n min_face_size=25,\n stride=2,\n threshold=[0.6, 0.7, 0.7],\n scale_factor=0.79,\n #scale_factor=0.709,#change\n slide_window=False):\n\n self.pnet_detector = detectors[0]\n self.rnet_detector = detectors[1]\n self.onet_detector = detectors[2]\n self.min_face_size = min_face_size\n self.stride = stride\n self.thresh = threshold\n self.scale_factor = scale_factor\n self.slide_window = slide_window\n\n def convert_to_square(self, bbox):\n \"\"\"\n convert bbox to square\n Parameters:\n ----------\n bbox: numpy array , shape n x 5\n input bbox\n Returns:\n -------\n square bbox\n \"\"\"\n square_bbox = bbox.copy()\n\n h = bbox[:, 3] - bbox[:, 1] + 1\n w = bbox[:, 2] - bbox[:, 0] + 1\n max_side = np.maximum(h, w)\n square_bbox[:, 0] = bbox[:, 0] + w * 0.5 - max_side * 0.5\n square_bbox[:, 1] = bbox[:, 1] + h * 0.5 - max_side * 0.5\n square_bbox[:, 2] = square_bbox[:, 0] + max_side - 1\n square_bbox[:, 3] = square_bbox[:, 1] + max_side - 1\n return square_bbox\n\n def calibrate_box(self, bbox, reg):\n \"\"\"\n calibrate bboxes\n Parameters:\n ----------\n bbox: numpy array, shape n x 5\n input bboxes\n reg: numpy array, shape n x 4\n bboxes adjustment\n Returns:\n -------\n bboxes after refinement\n \"\"\"\n\n bbox_c = bbox.copy()\n w = bbox[:, 2] - bbox[:, 0] + 1\n w = np.expand_dims(w, 1)\n h = bbox[:, 3] - bbox[:, 1] + 1\n h = np.expand_dims(h, 1)\n reg_m = np.hstack([w, h, w, h])\n aug = reg_m * reg\n bbox_c[:, 0:4] = bbox_c[:, 0:4] + aug\n return bbox_c\n\n def generate_bbox(self, cls_map, reg, scale, threshold):\n \"\"\"\n generate bbox from feature cls_map\n Parameters:\n ----------\n cls_map: numpy array , n x m \n detect score for each position\n reg: numpy array , n x m x 4\n bbox\n scale: float number\n scale of this detection\n threshold: float number\n detect threshold\n Returns:\n -------\n bbox array\n \"\"\"\n stride = 2\n #stride = 4\n cellsize = 12\n #cellsize = 25\n\n t_index = np.where(cls_map > threshold)\n\n # find nothing\n if t_index[0].size == 0:\n return np.array([])\n #offset\n dx1, dy1, dx2, dy2 = [reg[t_index[0], t_index[1], i] for i in range(4)]\n\n reg = np.array([dx1, dy1, dx2, dy2])\n score = cls_map[t_index[0], t_index[1]]\n boundingbox = np.vstack([np.round((stride * t_index[1]) / scale),\n np.round((stride * t_index[0]) / scale),\n np.round((stride * t_index[1] + cellsize) / scale),\n np.round((stride * t_index[0] + cellsize) / scale),\n score,\n reg])\n\n return boundingbox.T\n #pre-process images\n def processed_image(self, img, scale):\n height, width, channels = img.shape\n new_height = int(height * scale) # resized new height\n new_width = int(width * scale) # resized new width\n new_dim = (new_width, new_height)\n img_resized = cv2.resize(img, new_dim, interpolation=cv2.INTER_LINEAR) # resized image\n img_resized = (img_resized - 127.5) / 128\n return img_resized\n\n def pad(self, bboxes, w, h):\n \"\"\"\n pad the the bboxes, alse restrict the size of it\n Parameters:\n ----------\n bboxes: numpy array, n x 5\n input bboxes\n w: float number\n width of the input image\n h: float number\n height of the input image\n Returns :\n ------\n dy, dx : numpy array, n x 1\n start point of the bbox in target image\n edy, edx : numpy array, n x 1\n end point of the bbox in target image\n y, x : numpy array, n x 1\n start point of the bbox in original image\n ex, ex : numpy array, n x 1\n end point of the bbox in original image\n tmph, tmpw: numpy array, n x 1\n height and width of the bbox\n \"\"\"\n tmpw, tmph = bboxes[:, 2] - bboxes[:, 0] + 1, bboxes[:, 3] - bboxes[:, 1] + 1\n num_box = bboxes.shape[0]\n\n dx, dy = np.zeros((num_box,)), np.zeros((num_box,))\n edx, edy = tmpw.copy() - 1, tmph.copy() - 1\n\n x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]\n\n tmp_index = np.where(ex > w - 1)\n edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]\n ex[tmp_index] = w - 1\n\n tmp_index = np.where(ey > h - 1)\n edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]\n ey[tmp_index] = h - 1\n\n tmp_index = np.where(x < 0)\n dx[tmp_index] = 0 - x[tmp_index]\n x[tmp_index] = 0\n\n tmp_index = np.where(y < 0)\n dy[tmp_index] = 0 - y[tmp_index]\n y[tmp_index] = 0\n\n return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]\n return_list = [item.astype(np.int32) for item in return_list]\n\n return return_list\n \n def detect_pnet(self, im):\n \"\"\"Get face candidates through pnet\n\n Parameters:\n ----------\n im: numpy array\n input image array\n\n Returns:\n -------\n boxes: numpy array\n detected boxes before calibration\n boxes_c: numpy array\n boxes after calibration\n \"\"\"\n h, w, c = im.shape\n net_size = 12\n \n current_scale = float(net_size) / self.min_face_size # find initial scale\n # print(\"current_scale\", net_size, self.min_face_size, current_scale)\n im_resized = self.processed_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n # fcn\n all_boxes = list()\n while min(current_height, current_width) > net_size:\n #return the result predicted by pnet\n #cls_cls_map : H*w*2\n #reg: H*w*4\n cls_cls_map, reg = self.pnet_detector.predict(im_resized)\n #boxes: num*9(x1,y1,x2,y2,score,x1_offset,y1_offset,x2_offset,y2_offset)\n boxes = self.generate_bbox(cls_cls_map[:, :,1], reg, current_scale, self.thresh[0])\n\n current_scale *= self.scale_factor\n im_resized = self.processed_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n\n if boxes.size == 0:\n continue\n keep = py_nms(boxes[:, :5], 0.5, 'Union')\n boxes = boxes[keep]\n all_boxes.append(boxes)\n\n if len(all_boxes) == 0:\n return None, None, None\n\n all_boxes = np.vstack(all_boxes)\n\n # merge the detection from first stage\n keep = py_nms(all_boxes[:, 0:5], 0.7, 'Union')\n all_boxes = all_boxes[keep]\n boxes = all_boxes[:, :5]\n\n bbw = all_boxes[:, 2] - all_boxes[:, 0] + 1\n bbh = all_boxes[:, 3] - all_boxes[:, 1] + 1\n\n # refine the boxes\n boxes_c = np.vstack([all_boxes[:, 0] + all_boxes[:, 5] * bbw,\n all_boxes[:, 1] + all_boxes[:, 6] * bbh,\n all_boxes[:, 2] + all_boxes[:, 7] * bbw,\n all_boxes[:, 3] + all_boxes[:, 8] * bbh,\n all_boxes[:, 4]])\n boxes_c = boxes_c.T\n\n return boxes, boxes_c, None\n def detect_rnet(self, im, dets):\n \"\"\"Get face candidates using rnet\n\n Parameters:\n ----------\n im: numpy array\n input image array\n dets: numpy array\n detection results of pnet\n\n Returns:\n -------\n boxes: numpy array\n detected boxes before calibration\n boxes_c: numpy array\n boxes after calibration\n \"\"\"\n h, w, c = im.shape\n dets = self.convert_to_square(dets)\n dets[:, 0:4] = np.round(dets[:, 0:4])\n\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)\n num_boxes = dets.shape[0]\n cropped_ims = np.zeros((num_boxes, 24, 24, 3), dtype=np.float32)\n for i in range(num_boxes):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]\n cropped_ims[i, :, :, :] = (cv2.resize(tmp, (24, 24))-127.5) / 128\n #cls_scores : num_data*2\n #reg: num_data*4\n #landmark: num_data*10\n cls_scores, reg, _ = self.rnet_detector.predict(cropped_ims)\n cls_scores = cls_scores[:,1]\n keep_inds = np.where(cls_scores > self.thresh[1])[0]\n if len(keep_inds) > 0:\n boxes = dets[keep_inds]\n boxes[:, 4] = cls_scores[keep_inds]\n reg = reg[keep_inds]\n #landmark = landmark[keep_inds]\n else:\n return None, None, None\n \n \n keep = py_nms(boxes, 0.6)\n boxes = boxes[keep]\n boxes_c = self.calibrate_box(boxes, reg[keep])\n return boxes, boxes_c,None\n def detect_onet(self, im, dets):\n \"\"\"Get face candidates using onet\n\n Parameters:\n ----------\n im: numpy array\n input image array\n dets: numpy array\n detection results of rnet\n\n Returns:\n -------\n boxes: numpy array\n detected boxes before calibration\n boxes_c: numpy array\n boxes after calibration\n \"\"\"\n h, w, c = im.shape\n dets = self.convert_to_square(dets)\n dets[:, 0:4] = np.round(dets[:, 0:4])\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)\n num_boxes = dets.shape[0]\n cropped_ims = np.zeros((num_boxes, 48, 48, 3), dtype=np.float32)\n for i in range(num_boxes):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]\n cropped_ims[i, :, :, :] = (cv2.resize(tmp, (48, 48))-127.5) / 128\n \n cls_scores, reg,landmark = self.onet_detector.predict(cropped_ims)\n #prob belongs to face\n cls_scores = cls_scores[:,1] \n keep_inds = np.where(cls_scores > self.thresh[2])[0] \n if len(keep_inds) > 0:\n #pickout filtered box\n boxes = dets[keep_inds]\n boxes[:, 4] = cls_scores[keep_inds]\n reg = reg[keep_inds]\n landmark = landmark[keep_inds]\n else:\n return None, None, None\n \n #width\n w = boxes[:,2] - boxes[:,0] + 1\n #height\n h = boxes[:,3] - boxes[:,1] + 1\n landmark[:,0::2] = (np.tile(w,(5,1)) * landmark[:,0::2].T + np.tile(boxes[:,0],(5,1)) - 1).T\n landmark[:,1::2] = (np.tile(h,(5,1)) * landmark[:,1::2].T + np.tile(boxes[:,1],(5,1)) - 1).T \n boxes_c = self.calibrate_box(boxes, reg)\n \n \n boxes = boxes[py_nms(boxes, 0.6, \"Minimum\")]\n keep = py_nms(boxes_c, 0.6, \"Minimum\")\n boxes_c = boxes_c[keep]\n landmark = landmark[keep]\n return boxes, boxes_c,landmark\n #use for video\n def detect(self, img):\n \"\"\"Detect face over image\n \"\"\"\n boxes = None\n t = time.time()\n \n # pnet\n t1 = 0\n if self.pnet_detector:\n boxes, boxes_c,_ = self.detect_pnet(img)\n if boxes_c is None:\n return np.array([]),np.array([])\n \n t1 = time.time() - t\n t = time.time()\n \n # rnet\n t2 = 0\n if self.rnet_detector:\n boxes, boxes_c,_ = self.detect_rnet(img, boxes_c)\n if boxes_c is None:\n return np.array([]),np.array([])\n \n t2 = time.time() - t\n t = time.time()\n \n # onet\n t3 = 0\n if self.onet_detector:\n boxes, boxes_c,landmark = self.detect_onet(img, boxes_c)\n if boxes_c is None:\n return np.array([]),np.array([])\n \n t3 = time.time() - t\n t = time.time()\n print(\n \"time cost \" + '{:.3f}'.format(t1 + t2 + t3) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,\n t3))\n \n return boxes_c,landmark\n def detect_face(self, test_data):\n all_boxes = []#save each image's bboxes\n landmarks = []\n batch_idx = 0\n sum_time = 0\n #test_data is iter_\n for databatch in test_data:\n #databatch(image returned)\n if batch_idx % 100 == 0:\n print(\"%d images done\" % batch_idx)\n im = databatch\n # pnet\n t1 = 0\n if self.pnet_detector:\n t = time.time()\n #ignore landmark \n boxes, boxes_c, landmark = self.detect_pnet(im)\n t1 = time.time() - t\n sum_time += t1\n if boxes_c is None:\n print(\"boxes_c is None...\")\n all_boxes.append(np.array([]))\n #pay attention\n landmarks.append(np.array([]))\n batch_idx += 1\n continue\n # rnet\n t2 = 0\n if self.rnet_detector:\n t = time.time()\n #ignore landmark \n boxes, boxes_c, landmark = self.detect_rnet(im, boxes_c)\n t2 = time.time() - t\n sum_time += t2\n if boxes_c is None:\n all_boxes.append(np.array([]))\n landmarks.append(np.array([]))\n batch_idx += 1\n continue\n # onet\n t3 = 0\n if self.onet_detector:\n t = time.time()\n boxes, boxes_c, landmark = self.detect_onet(im, boxes_c)\n t3 = time.time() - t\n sum_time += t3\n if boxes_c is None:\n all_boxes.append(np.array([]))\n landmarks.append(np.array([])) \n batch_idx += 1\n continue\n print(\n \"time cost \" + '{:.3f}'.format(sum_time) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,t3))\n \n \n all_boxes.append(boxes_c)\n landmarks.append(landmark)\n batch_idx += 1\n #num_of_data*9,num_of_data*10\n return all_boxes,landmarks\n\n" ]
[ [ "numpy.hstack", "numpy.expand_dims", "numpy.maximum", "numpy.tile", "numpy.round", "numpy.zeros", "numpy.array", "numpy.where", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stjordanis/graph4nlp
[ "c6ebde32bc77d3a7b78f86a93f19b1c057963ffa", "c6ebde32bc77d3a7b78f86a93f19b1c057963ffa", "c6ebde32bc77d3a7b78f86a93f19b1c057963ffa", "c6ebde32bc77d3a7b78f86a93f19b1c057963ffa", "c6ebde32bc77d3a7b78f86a93f19b1c057963ffa" ]
[ "graph4nlp/pytorch/test/seq_decoder/graph2seq/src/g2s_v2/core/utils/vocab_utils.py", "graph4nlp/pytorch/modules/prediction/classification/link_prediction/ConcatFeedForwardNN.py", "graph4nlp/pytorch/modules/prediction/classification/node_classification/FeedForwardNNLayer.py", "graph4nlp/pytorch/test/graph_embedding/run_gat.py", "graph4nlp/pytorch/test/kg_completion/src/spodernet/spodernet/hooks.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport os\nimport re\nimport pickle\nimport numpy as np\nfrom collections import Counter\nfrom functools import lru_cache\n\nfrom . import constants\nfrom .data_utils import tokenize\n\nword_detector = re.compile('\\w')\n\nclass VocabModel(object):\n def __init__(self, data_set, config):\n print('Building vocabs...')\n (allWords, allEdgeTypes) = collect_vocabs(data_set)\n print('Number of words: {}'.format(len(allWords)))\n print('Number of edge types: {}'.format(len(allEdgeTypes)))\n\n self.word_vocab = Vocab()\n self.word_vocab.build_vocab(allWords, vocab_size=config['top_word_vocab'], min_freq=config['min_word_freq'])\n if config.get('pretrained_word_embed_file', None):\n self.word_vocab.load_embeddings(config['pretrained_word_embed_file'])\n print('Using pretrained word embeddings')\n else:\n self.word_vocab.randomize_embeddings(config['word_embed_dim'])\n print('Using randomized word embeddings')\n print('word_vocab: {}'.format(self.word_vocab.embeddings.shape))\n\n self.edge_vocab = Vocab()\n self.edge_vocab.build_vocab(allEdgeTypes)\n print('edge_vocab: {}'.format((self.edge_vocab.get_vocab_size())))\n\n\n @classmethod\n def build(cls, saved_vocab_file=None, data_set=None, config=None):\n \"\"\"\n Loads a Vocabulary from disk.\n\n Args:\n saved_vocab_file (str): path to the saved vocab file\n data_set:\n config:\n\n Returns:\n Vocabulary: loaded Vocabulary\n \"\"\"\n if os.path.exists(saved_vocab_file):\n print('Loading pre-built vocab model stored in {}'.format(saved_vocab_file))\n vocab_model = pickle.load(open(saved_vocab_file, 'rb'))\n\n else:\n vocab_model = VocabModel(data_set, config)\n print('Saving vocab model to {}'.format(saved_vocab_file))\n pickle.dump(vocab_model, open(saved_vocab_file, 'wb'))\n return vocab_model\n\nclass Vocab(object):\n def __init__(self):\n self.PAD = 0\n self.SOS = 1\n self.EOS = 2\n self.UNK = 3\n self.pad_token = constants._PAD_TOKEN\n self.sos_token = constants._SOS_TOKEN\n self.eos_token = constants._EOS_TOKEN\n self.unk_token = constants._UNK_TOKEN\n\n self.reserved = [self.pad_token, self.sos_token, self.eos_token, self.unk_token]\n self.index2word = self.reserved[:]\n self.word2index = dict(zip(self.reserved, range(len(self.reserved))))\n self.word2count = Counter()\n self.embeddings = None\n\n def build_vocab(self, vocab_counter, vocab_size=None, min_freq=1):\n self.word2count = vocab_counter\n self._add_words(vocab_counter.keys())\n self._trim(vocab_size=vocab_size, min_freq=min_freq)\n\n def _add_words(self, words):\n for word in words:\n if word not in self.word2index:\n self.word2index[word] = len(self.index2word)\n self.index2word.append(word)\n assert len(self.word2index) == len(self.index2word)\n\n def _trim(self, vocab_size: int=None, min_freq: int=1):\n if min_freq <= 1 and (vocab_size is None or vocab_size >= len(self.word2index)):\n return\n ordered_words = sorted(((c, w) for (w, c) in self.word2count.items()), reverse=True)\n if vocab_size:\n ordered_words = ordered_words[:vocab_size]\n self.index2word = self.reserved[:]\n self.word2index = dict(zip(self.reserved, range(len(self.reserved))))\n self.word2count = Counter()\n for count, word in ordered_words:\n if count < min_freq: break\n if word not in self.word2index:\n self.word2index[word] = len(self.index2word)\n self.word2count[word] = count\n self.index2word.append(word)\n assert len(self.word2index) == len(self.index2word)\n\n def load_embeddings(self, file_path, scale=0.08, dtype=np.float32):\n hit_words = set()\n vocab_size = len(self)\n with open(file_path, 'rb') as f:\n for line in f:\n line = line.split()\n word = line[0].decode('utf-8')\n idx = self.word2index.get(word.lower(), None)\n if idx is None or idx in hit_words:\n continue\n\n vec = np.array(line[1:], dtype=dtype)\n if self.embeddings is None:\n n_dims = len(vec)\n self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=(vocab_size, n_dims)), dtype=dtype)\n self.embeddings[self.PAD] = np.zeros(n_dims)\n self.embeddings[idx] = vec\n hit_words.add(idx)\n print('Pretrained word embeddings hit ratio: {}'.format(len(hit_words) / len(self.index2word)))\n\n def randomize_embeddings(self, n_dims, scale=0.08):\n vocab_size = self.get_vocab_size()\n shape = (vocab_size, n_dims)\n self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=shape), dtype=np.float32)\n self.embeddings[self.PAD] = np.zeros(n_dims)\n\n def __getitem__(self, item):\n if type(item) is int:\n return self.index2word[item]\n return self.word2index.get(item, self.UNK)\n\n def __len__(self):\n return len(self.index2word)\n\n @lru_cache(maxsize=None)\n def is_word(self, token_id: int) -> bool:\n \"\"\"Return whether the token at `token_id` is a word; False for punctuations.\"\"\"\n if token_id < 4: return False\n if token_id >= len(self): return True # OOV is assumed to be words\n token_str = self.index2word[token_id]\n if not word_detector.search(token_str) or token_str == '<P>':\n return False\n return True\n\n def get_vocab_size(self):\n return len(self.index2word)\n\n def getIndex(self, word):\n return self.word2index.get(word, self.UNK)\n\n def getWord(self, idx):\n return self.index2word[idx] if idx < len(self.index2word) else self.unk_token\n\n def to_word_sequence(self, seq):\n sentence = []\n for idx in seq:\n word = self.getWord(idx)\n sentence.append(word)\n return sentence\n\n def to_index_sequence(self, sentence):\n sentence = sentence.strip()\n seq = []\n for word in tokenize(sentence):\n idx = self.getIndex(word)\n seq.append(idx)\n return seq\n\n def to_index_sequence_for_list(self, words):\n seq = []\n for word in words:\n idx = self.getIndex(word)\n seq.append(idx)\n return seq\n\ndef collect_vocabs(all_instances):\n all_words = Counter()\n all_edge_types = Counter()\n for (sent1, sent2) in all_instances:\n # for each in sent1.words:\n # all_words.update(each)\n for each in sent1.graph['g_features']:\n all_words.update(each)\n all_words.update(sent2.words)\n\n # for node, value in sent1.graph['g_adj'].items():\n # all_edge_types.update([each['edge'] for each in value])\n return all_words, all_edge_types\n", "from torch import nn\nimport torch\nfrom ..base import LinkPredictionBase\nfrom .ConcatFeedForwardNNLayer import ConcatFeedForwardNNLayer\n\nclass ConcatFeedForwardNN(LinkPredictionBase):\n r\"\"\"Specific class for link prediction task.\n\n Parameters\n ----------\n\n input_size : int \n The length of input node embeddings\n num_class : int \n The number of node catrgoriey for classification\n hidden_size : list of int type values\n Example for two layers's FeedforwardNN: [50, 20]\n activation: the activation function class for each fully connected layer\n Default: nn.ReLU()\n Example: nn.ReLU(),nn.Sigmoid(). \n\n \"\"\" \n def __init__(self, input_size, hidden_size,num_class,activation=nn.ReLU()): \n super(ConcatFeedForwardNN, self).__init__()\n \n \n self.classifier=ConcatFeedForwardNNLayer(input_size, num_class, hidden_size,activation)\n\n def forward(self, input_graph):\n r\"\"\"\n Forward functions to compute the logits tensor for link prediction.\n \n \n Parameters\n ----------\n \n input graph : GraphData\n The tensors stored in the node feature field named \"node_emb\" in the \n input_graph are used for link prediction.\n\n \n Returns \n ---------\n \n output_graph : GraphData\n The computed logit tensor for each pair of nodes in the graph are stored\n in the node feature field named \"edge_logits\".\n logit tensor shape is: [num_class] \n \"\"\" \n #get the nod embedding from the graph \n node_emb=input_graph.node_features['node_emb']\n \n #add the edges and edge prediction logits into the graph\n num_node=node_emb.shape[0]\n node_idx_list=[idx for idx in range(num_node)]\n src_idx=torch.tensor(node_idx_list).view(-1,1).repeat(1,num_node).view(-1)\n dst_idx=torch.tensor(node_idx_list).view(1,-1).repeat(num_node,1).view(-1)\n \n input_graph.add_edges(src_idx,dst_idx)\n input_graph.edge_features['logits']=self.classifier(node_emb)\n \n return input_graph\n\n\n\n\n\n\n\n", "import collections\nfrom torch import nn\nimport torch as th\nfrom ..base import NodeClassifierLayerBase\n\nclass FeedForwardNNLayer(NodeClassifierLayerBase):\n r\"\"\"Specific class for node classification task.\n\n\n Parameters\n ----------\n\n input_size : int \n The length of input node embeddings\n num_class : int \n The number of node catrgoriey for classification\n hidden_size : list of int type values\n Example for two layers's FeedforwardNN: [50, 20]\n activation: the activation function class for each fully connected layer\n Default: nn.ReLU()\n Example: nn.ReLU(),nn.Sigmoid(). \n\n \"\"\" \n def __init__(self, input_size, num_class, hidden_size,activation=nn.ReLU()): \n super(FeedForwardNNLayer, self).__init__()\n \n \n #build the linear module list\n module_seq=[] \n \n for layer_idx in range(len(hidden_size)):\n if layer_idx==0:\n module_seq.append(('linear'+str(layer_idx),nn.Linear(input_size,hidden_size[layer_idx])))\n else:\n module_seq.append(('linear'+str(layer_idx),nn.Linear(hidden_size[layer_idx-1],self.hidden_size[layer_idx])))\n module_seq.append(('activate'+str(layer_idx),activation))\n \n module_seq.append(('linear_end',nn.Linear(hidden_size[-1],num_class)))\n \n self.classifier = nn.Sequential(collections.OrderedDict(module_seq))\n\n def forward(self, node_emb, node_idx=None):\n r\"\"\"\n Forward functions to compute the logits tensor for node classification.\n \n \n \n Parameters\n ----------\n \n node_emb : tensor [N,H] \n N: number of nodes \n H: length of the node embeddings\n node_idx : a list of index of nodes that needs classification.\n Default: 'None'\n \n Returns \n -------\n logit tensor: [N, num_class] The score logits for all nodes preidcted.\n \"\"\" \n if node_idx == None:\n return self.classifier(node_emb)\n else:\n new_emb_new = node_emb[th.tensor(node_idx), :] # get the required node embeddings.\n return self.classifier(new_emb_new)\n", "\"\"\"\nGraph Attention Networks in Grap4NLP using SPMV optimization.\nMultiple heads are also batched together for faster training.\nReferences\n----------\nDGL GAT example: https://github.com/dmlc/dgl/tree/master/examples/pytorch/gat\n\"\"\"\nimport os\nimport time\nimport argparse\nimport numpy as np\nimport networkx as nx\nfrom collections import namedtuple\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport dgl\nfrom dgl import DGLGraph\nfrom dgl.data import register_data_args, load_data\n\nfrom .utils import EarlyStopping\nfrom ...modules.utils.generic_utils import *\nfrom ...modules.graph_embedding.gat import GAT\nfrom ...data.data import GraphData\nfrom graph4nlp.pytorch.modules.utils.logger import Logger\n\n\ndef accuracy(logits, labels):\n _, indices = torch.max(logits, dim=1)\n correct = torch.sum(indices == labels)\n return correct.item() * 1.0 / len(labels)\n\ndef evaluate(model, g, labels, mask):\n model.eval()\n with torch.no_grad():\n logits = model(g)\n logits = logits[mask]\n labels = labels[mask]\n return accuracy(logits, labels)\n\nclass GNNClassifier(nn.Module):\n def __init__(self,\n num_layers,\n input_size,\n hidden_size,\n output_size,\n num_heads,\n num_out_heads,\n direction_option,\n feat_drop=0.6,\n attn_drop=0.6,\n negative_slope=0.2,\n residual=False,\n activation=F.elu):\n super(GNNClassifier, self).__init__()\n self.direction_option = direction_option\n heads = [num_heads] * (num_layers - 1) + [num_out_heads]\n self.model = GAT(num_layers,\n input_size,\n hidden_size,\n output_size,\n heads,\n direction_option=direction_option,\n feat_drop=feat_drop,\n attn_drop=attn_drop,\n negative_slope=negative_slope,\n residual=residual,\n activation=activation)\n\n if self.direction_option == 'bi_sep':\n self.fc = nn.Linear(2 * output_size, output_size)\n\n def forward(self, graph):\n graph = self.model(graph)\n logits = graph.node_features['node_emb']\n if self.direction_option == 'bi_sep':\n logits = self.fc(F.elu(logits))\n\n return logits\n\ndef prepare_dgl_graph_data(args):\n data = load_data(args)\n features = torch.FloatTensor(data.features)\n labels = torch.LongTensor(data.labels)\n if hasattr(torch, 'BoolTensor'):\n train_mask = torch.BoolTensor(data.train_mask)\n val_mask = torch.BoolTensor(data.val_mask)\n test_mask = torch.BoolTensor(data.test_mask)\n else:\n train_mask = torch.ByteTensor(data.train_mask)\n val_mask = torch.ByteTensor(data.val_mask)\n test_mask = torch.ByteTensor(data.test_mask)\n\n num_feats = features.shape[1]\n n_classes = data.num_labels\n n_edges = data.graph.number_of_edges()\n print(\"\"\"----Data statistics------'\n #Edges %d\n #Classes %d\n #Train samples %d\n #Val samples %d\n #Test samples %d\"\"\" %\n (n_edges, n_classes,\n train_mask.int().sum().item(),\n val_mask.int().sum().item(),\n test_mask.int().sum().item()))\n\n g = data.graph\n # add self loop\n g.remove_edges_from(nx.selfloop_edges(g))\n g = DGLGraph(g)\n g.add_edges(g.nodes(), g.nodes())\n n_edges = g.number_of_edges()\n\n data = {'features': features,\n 'graph': g,\n 'train_mask': train_mask,\n 'val_mask': val_mask,\n 'test_mask': test_mask,\n 'labels': labels,\n 'num_feats': num_feats,\n 'n_classes': n_classes,\n 'n_edges': n_edges}\n\n return data\n\ndef prepare_ogbn_graph_data(args):\n from ogb.nodeproppred import DglNodePropPredDataset\n\n dataset = DglNodePropPredDataset(name=args.dataset)\n\n split_idx = dataset.get_idx_split()\n train_idx, val_idx, test_idx = torch.LongTensor(split_idx['train']), torch.LongTensor(split_idx['valid']), torch.LongTensor(split_idx['test'])\n g, labels = dataset[0] # graph: dgl graph object, label: torch tensor of shape (num_nodes, num_tasks)\n features = torch.Tensor(g.ndata['feat'])\n labels = torch.LongTensor(labels).squeeze(-1)\n\n if args.to_undirected:\n inv_edge_index = (g.edges()[1], g.edges()[0])\n g = dgl.add_edges(g, inv_edge_index[0], inv_edge_index[1])\n print('convert the input graph to undirected graph')\n\n\n # add self loop\n # no duplicate self loop will be added for nodes already having self loops\n new_g = dgl.transform.add_self_loop(g)\n\n\n num_feats = features.shape[1]\n n_classes = labels.max().item() + 1\n n_edges = new_g.number_of_edges()\n print(\"\"\"----Data statistics------'\n #Edges %d\n #Classes %d\n #Train samples %d\n #Val samples %d\n #Test samples %d\"\"\" %\n (n_edges, n_classes,\n train_idx.shape[0],\n val_idx.shape[0],\n test_idx.shape[0]))\n\n data = {'features': features,\n 'graph': new_g,\n 'train_mask': train_idx,\n 'val_mask': val_idx,\n 'test_mask': test_idx,\n 'labels': labels,\n 'num_feats': num_feats,\n 'n_classes': n_classes,\n 'n_edges': n_edges}\n\n return data\n\ndef main(args, seed):\n # load and preprocess dataset\n if args.dataset.startswith('ogbn'):\n # Open Graph Benchmark datasets\n data = prepare_ogbn_graph_data(args)\n else:\n # DGL datasets\n data = prepare_dgl_graph_data(args)\n\n features, dgl_graph, train_mask, val_mask, test_mask, labels, num_feats, n_classes, n_edges\\\n = data['features'], data['graph'], data['train_mask'], \\\n data['val_mask'], data['test_mask'], data['labels'], \\\n data['num_feats'], data['n_classes'], data['n_edges']\n\n\n # Configure\n np.random.seed(seed)\n torch.manual_seed(seed)\n\n if not args.no_cuda and torch.cuda.is_available():\n print('[ Using CUDA ]')\n device = torch.device('cuda' if args.gpu < 0 else 'cuda:%d' % args.gpu)\n cudnn.benchmark = True\n torch.cuda.manual_seed(seed)\n else:\n device = torch.device('cpu')\n\n features = features.to(device)\n labels = labels.to(device)\n train_mask = train_mask.to(device)\n val_mask = val_mask.to(device)\n test_mask = test_mask.to(device)\n\n dgl_graph.ndata['node_feat'] = features\n\n # convert DGLGraph to GraphData\n g = GraphData()\n g.from_dgl(dgl_graph)\n\n # create model\n model = GNNClassifier(args.num_layers,\n num_feats,\n args.num_hidden,\n n_classes,\n args.num_heads,\n args.num_out_heads,\n direction_option=args.direction_option,\n feat_drop=args.in_drop,\n attn_drop=args.attn_drop,\n negative_slope=args.negative_slope,\n residual=args.residual,\n activation=F.elu)\n\n\n print(model)\n model.to(device)\n\n if args.early_stop:\n stopper = EarlyStopping('{}.{}'.format(args.save_model_path, seed), patience=args.patience)\n\n if args.use_log_softmax_nll:\n loss_fcn = torch.nn.NLLLoss()\n else:\n loss_fcn = torch.nn.CrossEntropyLoss()\n\n # use optimizer\n optimizer = torch.optim.Adam(\n model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n\n # initialize graph\n dur = []\n for epoch in range(args.epochs):\n model.train()\n if epoch >= 3:\n t0 = time.time()\n # forward\n logits = model(g)\n if args.use_log_softmax_nll:\n logits = logits.log_softmax(dim=-1)\n\n loss = loss_fcn(logits[train_mask], labels[train_mask])\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if epoch >= 3:\n dur.append(time.time() - t0)\n\n train_acc = accuracy(logits[train_mask], labels[train_mask])\n\n if args.fastmode:\n val_acc = accuracy(logits[val_mask], labels[val_mask])\n else:\n val_acc = evaluate(model, g, labels, val_mask)\n\n val_loss = loss_fcn(logits[val_mask], labels[val_mask])\n\n if args.early_stop:\n if stopper.step(-val_loss, model):\n break\n\n print(\"Epoch {:05d} | Time(s) {:.4f} | Loss {:.4f} | TrainAcc {:.4f} |\"\n \" ValLoss {:.4f} | ValAcc {:.4f} | ETputs(KTEPS) {:.2f}\".\n format(epoch, np.mean(dur), loss.item(), train_acc,\n val_loss, val_acc, n_edges / np.mean(dur) / 1000))\n\n print()\n if args.early_stop:\n model = stopper.load_checkpoint(model)\n print('Restored best saved model')\n os.remove(stopper.save_model_path)\n print('Removed best saved model file to save disk space')\n\n acc = evaluate(model, g, labels, test_mask)\n print(\"Test Accuracy {:.4f}\".format(acc))\n\n return acc\n\ndef multi_run(config):\n config['save_model_path'] = '{}_{}_{}_{}'.format(config['save_model_path'], config['dataset'], 'gcn', config['direction_option'])\n print_config(config)\n\n logger = Logger(config['save_model_path'], config=config, overwrite=True)\n\n config = dict_to_namedtuple(config)\n np.random.seed(config.random_seed)\n scores = []\n for _ in range(config.num_runs):\n seed = np.random.randint(10000)\n scores.append(main(config, seed))\n\n print(\"\\nTest Accuracy ({} runs): mean {:.4f}, std {:.4f}\".format(config.num_runs, np.mean(scores), np.std(scores)))\n logger.write(\"\\nTest Accuracy ({} runs): mean {:.4f}, std {:.4f}\".format(config.num_runs, np.mean(scores), np.std(scores)))\n logger.close()\n\ndef grid_search_main(config):\n print_config(config)\n grid_search_hyperparams = []\n for k, v in config.items():\n if isinstance(v, list):\n grid_search_hyperparams.append(k)\n\n\n logger = Logger(config['save_model_path'], config=config, overwrite=True)\n\n best_config = None\n best_score = -1\n configs = grid(config)\n for cnf in configs:\n print('\\n')\n for k in grid_search_hyperparams:\n cnf['save_model_path'] += '_{}_{}'.format(k, cnf[k])\n print(cnf['save_model_path'])\n logger.write(cnf['save_model_path'])\n\n\n score = main(dict_to_namedtuple(cnf), cnf['random_seed'])\n if best_score < score:\n best_score = score\n best_config = cnf\n print('Found a better configuration: {}'.format(best_score))\n logger.write('Found a better configuration: {}'.format(best_score))\n\n print('\\nBest configuration:')\n logger.write('\\nBest configuration:')\n\n for k in grid_search_hyperparams:\n print('{}: {}'.format(k, best_config[k]))\n logger.write('{}: {}'.format(k, best_config[k]))\n\n\n print('Best test score: {}'.format(best_score))\n logger.write('Best test score: {}'.format(best_score))\n logger.close()\n\ndef dict_to_namedtuple(data, typename='config'):\n return namedtuple(typename, data.keys())(\n *(dict_to_namedtuple(typename + '_' + k, v) if isinstance(v, dict) else v for k, v in data.items())\n )\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-config', type=str, help='path to the config file')\n parser.add_argument('--grid_search', action='store_true', help='flag: grid search')\n cfg = vars(parser.parse_args())\n\n config = get_config(cfg['config'])\n if cfg['grid_search']:\n grid_search_main(config)\n else:\n multi_run(config)\n\n\n\n# if __name__ == '__main__':\n\n# parser = argparse.ArgumentParser(description='GAT')\n# register_data_args(parser)\n# parser.add_argument(\"--num-runs\", type=int, default=5,\n# help=\"number of runs\")\n# parser.add_argument(\"--no-cuda\", action=\"store_true\", default=False,\n# help=\"use CPU\")\n# parser.add_argument(\"--gpu\", type=int, default=-1,\n# help=\"which GPU to use.\")\n# parser.add_argument(\"--epochs\", type=int, default=200,\n# help=\"number of training epochs\")\n# parser.add_argument(\"--to_undirected\", action=\"store_true\", default=False,\n# help=\"convert to undirected graph\")\n# parser.add_argument(\"--direction-option\", type=str, default='bi_sep',\n# help=\"direction type (`'undirected'`, `'bi_fuse'`, `'bi_sep'`)\")\n# parser.add_argument(\"--num-heads\", type=int, default=8,\n# help=\"number of hidden attention heads\")\n# parser.add_argument(\"--num-out-heads\", type=int, default=1,\n# help=\"number of output attention heads\")\n# parser.add_argument(\"--num-layers\", type=int, default=2,\n# help=\"number of hidden layers\")\n# parser.add_argument(\"--num-hidden\", type=int, default=8,\n# help=\"number of hidden units\")\n# parser.add_argument(\"--residual\", action=\"store_true\", default=False,\n# help=\"use residual connection\")\n# parser.add_argument(\"--in-drop\", type=float, default=.6,\n# help=\"input feature dropout\")\n# parser.add_argument(\"--attn-drop\", type=float, default=.6,\n# help=\"attention dropout\")\n# parser.add_argument(\"--lr\", type=float, default=0.005,\n# help=\"learning rate\")\n# parser.add_argument('--weight-decay', type=float, default=5e-4,\n# help=\"weight decay\")\n# parser.add_argument('--negative-slope', type=float, default=0.2,\n# help=\"the negative slope of leaky relu\")\n# parser.add_argument('--early-stop', action='store_true', default=False,\n# help=\"indicates whether to use early stop or not\")\n# parser.add_argument(\"--patience\", type=int, default=100,\n# help=\"early stopping patience\")\n# parser.add_argument('--fastmode', action=\"store_true\", default=False,\n# help=\"skip re-evaluate the validation set\")\n# parser.add_argument('--save-model-path', type=str, default=\"checkpoint\",\n# help=\"path to the best saved model\")\n# args = parser.parse_args()\n# args.save_model_path = '{}_{}_{}_{}'.format(args.save_model_path, args.dataset, 'gat', args.direction_option)\n# print(args)\n\n# np.random.seed(123)\n# scores = []\n# for _ in range(args.num_runs):\n# seed = np.random.randint(10000)\n# scores.append(main(args, seed))\n\n# print(\"\\nTest Accuracy ({} runs): mean {:.4f}, std {:.4f}\".format(args.num_runs, np.mean(scores), np.std(scores)))\n", "import numpy as np\nimport scipy.stats\nimport datetime\n\nfrom src.spodernet.spodernet.interfaces import IAtIterEndObservable, IAtEpochEndObservable, IAtEpochStartObservable\nfrom src.spodernet.spodernet.utils.util import Timer\nfrom src.spodernet.spodernet.utils.global_config import Config, Backends\n\nfrom src.spodernet.spodernet.utils.logger import Logger\nlog = Logger('hooks.py.txt')\n\nclass AbstractHook(IAtIterEndObservable, IAtEpochEndObservable):\n def __init__(self, name, metric_name, print_every_x_batches):\n self.epoch_errors = []\n self.current_scores = []\n self.name = name\n self.iter_count = 0\n self.print_every = print_every_x_batches\n self.metric_name = metric_name\n self.epoch = 1\n\n # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\n self.n = 0\n self.epoch_n = 0\n self.mean = 0\n self.M2 = 0\n self.load_backend_specific_functions()\n\n def load_backend_specific_functions(self):\n if Config.backend == Backends.TORCH:\n from torch.autograd import Variable\n def convert_state(state):\n if isinstance(state.targets, Variable):\n state.targets = state.targets.data\n if isinstance(state.argmax, Variable):\n state.argmax = state.argmax.data\n if isinstance(state.pred, Variable):\n state.pred = state.pred.data\n if isinstance(state.loss, Variable):\n state.loss = state.loss.data\n if isinstance(state.multi_labels, Variable):\n state.multi_labels = state.multi_labels.data\n\n return state\n\n self.convert_state = convert_state\n else:\n self.convert_state = lambda x: x\n\n def calculate_metric(self, state):\n raise NotImplementedError('Classes that inherit from abstract hook need to implement the calcualte metric method.')\n\n def at_end_of_iter_event(self, state):\n state = self.convert_state(state)\n metric = self.calculate_metric(state)\n #print(metric)\n\n self.n += 1\n delta = metric - self.mean\n self.mean += delta/self.n\n delta2 = metric - self.mean\n self.M2 += delta*delta2\n\n self.current_scores.append(metric)\n self.iter_count += 1\n if self.iter_count % self.print_every == 0:\n lower, upper, m, n = self.print_statistic()\n self.n = 0\n self.mean = 0\n self.M2 = 0\n return lower, upper, m, n\n return 0, 0, self.mean, self.n\n\n def at_end_of_epoch_event(self, state):\n if self.n == 0: return 0, 0, 0, 0\n self.epoch_errors.append(self.get_confidence_intervals())\n lower, upper, m, n = self.print_statistic(True)\n del self.current_scores[:]\n self.n = 0\n self.mean = 0\n self.M2 = 0\n self.epoch += 1\n self.iter_count = 0\n return lower, upper, m, n\n\n def get_confidence_intervals(self, percentile=0.99, limit=1000):\n z = scipy.stats.norm.ppf(percentile)\n var = self.M2/ (self.n)\n SE = np.sqrt(var/self.n)\n lower = self.mean-(z*SE)\n upper = self.mean+(z*SE)\n return [self.n, lower, self.mean, upper]\n\n def print_statistic(self, at_epoch_end=False):\n n, lower, m, upper = self.get_confidence_intervals()\n str_message = '{3} {4}: {2:.5}\\t99% CI: ({0:.5}, {1:.5}), n={5}'.format(lower, upper, m, self.name, self.metric_name, self.n)\n if at_epoch_end: log.info('\\n')\n if at_epoch_end: log.info('#'*40)\n if at_epoch_end: log.info(' '*10 + 'COMPLETED EPOCH: {0}'.format(self.epoch) + ' '*30)\n log.info(str_message)\n if at_epoch_end: log.info('#'*40)\n if at_epoch_end: log.info('\\n')\n return lower, upper, m, n\n\n\nclass AccuracyHook(AbstractHook):\n def __init__(self, name='', print_every_x_batches=1000):\n super(AccuracyHook, self).__init__(name, 'Accuracy', print_every_x_batches)\n self.func = None\n self.topk = 1\n if Config.backend == Backends.TORCH:\n import torch\n self.func = lambda x: torch.sum(x)\n\n def calculate_metric(self, state):\n if Config.backend == Backends.TORCH:\n correct = 0.0\n if len(state.argmax.size()) == 1:\n correct += self.func(state.targets==state.argmax)\n else:\n topk = state.argmax.size(1)\n for i in range(topk):\n correct += self.func(state.targets==state.argmax[:, i])\n n = state.argmax.size()[0]\n return correct.item()/np.float32(n)\n elif Config.backend == Backends.TENSORFLOW:\n n = state.argmax.shape[0]\n return np.sum(state.targets==state.argmax)/np.float32(n)\n elif Config.backend == Backends.TEST:\n n = state.argmax.shape[0]\n return np.sum(state.targets==state.argmax)/np.float32(n)\n else:\n raise Exception('Backend has unsupported value {0}'.format(Config.backend))\n\n\nclass TopKRankingLoss(AbstractHook):\n def __init__(self, k, filtered=False, name='', print_every_x_batches=1000):\n super(TopKRankingLoss, self).__init__(name, '{1}Hits@{0} loss'.format(k, ('' if not filtered else 'Filtered ')), print_every_x_batches)\n self.func = None\n self.argsort = None\n self.sum_func = None\n self.k = k\n self.filtered = filtered\n if Config.backend == Backends.TORCH:\n import torch\n self.argsort = lambda x, k: torch.topk(x, k)\n self.sum_func = lambda x: torch.sum(x)\n\n\n def calculate_metric(self, state):\n if Config.backend == Backends.TORCH:\n if self.filtered:\n import torch\n saved = torch.index_select(state.pred,1,state.targets)\n state.pred[state.multi_labels.byte()] = -100000.0\n state.pred.index_copy_(1, state.targets, saved)\n\n max_values, argmax = self.argsort(state.pred, self.k)\n in_topk = 0\n for i in range(self.k):\n in_topk += self.sum_func(argmax[:,i] == state.targets)\n n = state.pred.size()[0]\n return in_topk/np.float32(n)\n else:\n raise Exception('Backend has unsupported value {0}'.format(Config.backend))\n\n\n\nclass LossHook(AbstractHook):\n def __init__(self, name='', print_every_x_batches=1000):\n super(LossHook, self).__init__(name, 'Loss', print_every_x_batches)\n\n def calculate_metric(self, state):\n if Config.backend == Backends.TORCH:\n state = self.convert_state(state)\n return state.loss.item()\n else:\n return state.loss\n\n\nclass IntersectionHook(AbstractHook):\n def __init__(self, name='', print_every_x_batches=1000):\n super(IntersectionHook, self).__init__(name, 'Intersection', print_every_x_batches)\n\n def calculate_metric(self, state):\n state = self.convert_state(state)\n preds = state.pred\n targets = state.targets\n if Config.cuda:\n preds = preds.cpu()\n targets = targets.cpu()\n\n preds = preds.numpy()\n targets = targets.numpy()\n n = targets.size\n k = 0\n for row in range(Config.batch_size):\n k += np.intersect1d(preds[row], targets[row]).size\n\n return k/float(n)\n\n\n\nclass ETAHook(AbstractHook, IAtEpochStartObservable):\n def __init__(self, name='', print_every_x_batches=1000):\n super(ETAHook, self).__init__(name, 'ETA', print_every_x_batches)\n self.t = Timer(silent=True)\n self.cumulative_t = 0.0\n self.skipped_first = False\n\n def get_time_string(self, seconds):\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n if h < 0: h = 0\n if m < 0: m = 0\n if s < 0: s = 0\n return \"%d:%02d:%02d\" % (h, m, s)\n\n def calculate_metric(self, state):\n n = state.num_batches\n i = state.current_idx\n cumulative_t = self.t.tick('ETA')\n total_time_estimate = (cumulative_t/i)*n\n self.t.tick('ETA')\n self.cumulative_t = cumulative_t\n\n return total_time_estimate\n\n def print_statistic(self):\n if not self.skipped_first:\n # the first estimation is very unreliable for time measures\n self.skipped_first = True\n return 0, 0, 0, 0\n n, lower, m, upper = self.get_confidence_intervals()\n lower -= self.cumulative_t\n m -= self.cumulative_t\n upper -= self.cumulative_t\n lower, m, upper = self.get_time_string(lower), self.get_time_string(m), self.get_time_string(upper)\n log.info('{3} {4}: {2}\\t99% CI: ({0}, {1}), n={5}'.format(lower, upper, m, self.name, self.metric_name, n))\n return lower, upper, m, n\n\n def at_start_of_epoch_event(self, batcher_state):\n self.t.tick('ETA')\n t = self.t.tick('Epoch')\n\n def at_end_of_epoch_event(self, state):\n self.t.tock('ETA')\n epoch_time = self.t.tock('Epoch')\n self.epoch_errors.append([epoch_time])\n log.info('Total epoch time: {0}'.format(self.get_time_string(epoch_time)))\n del self.current_scores[:]\n self.n = 0\n self.mean = 0\n self.M2 = 0\n self.skipped_first = False\n self.epoch += 1\n return epoch_time\n" ]
[ [ "numpy.random.uniform", "numpy.array", "numpy.zeros" ], [ "torch.nn.ReLU", "torch.tensor" ], [ "torch.nn.Linear", "torch.nn.ReLU", "torch.tensor" ], [ "torch.BoolTensor", "torch.max", "torch.sum", "torch.FloatTensor", "torch.no_grad", "torch.cuda.is_available", "numpy.mean", "torch.device", "numpy.random.randint", "torch.nn.CrossEntropyLoss", "numpy.std", "torch.nn.functional.elu", "torch.LongTensor", "torch.nn.NLLLoss", "torch.nn.Linear", "torch.ByteTensor", "torch.Tensor", "numpy.random.seed", "torch.cuda.manual_seed", "torch.manual_seed" ], [ "numpy.sqrt", "torch.sum", "numpy.intersect1d", "numpy.float32", "torch.topk", "torch.index_select", "numpy.sum" ] ]
[ { "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": [] } ]
YinchaoGao/detectron2
[ "04958b93e1232935e126c2fd9e6ccd3f57c3a8f3" ]
[ "detectron2/export/api.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport copy\nimport logging\nimport os\nimport torch\nfrom caffe2.proto import caffe2_pb2\nfrom torch import nn\n\nfrom detectron2.config import CfgNode as CN\n\nfrom .caffe2_export import export_caffe2_detection_model\nfrom .caffe2_export import export_onnx_model as export_onnx_model_impl\nfrom .caffe2_export import run_and_save_graph\nfrom .caffe2_inference import ProtobufDetectionModel\nfrom .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format\nfrom .shared import get_pb_arg_vali, get_pb_arg_vals, save_graph\n\n__all__ = [\"add_export_config\", \"export_caffe2_model\", \"Caffe2Model\", \"export_onnx_model\"]\n\n\ndef add_export_config(cfg):\n \"\"\"\n Args:\n cfg (CfgNode): a detectron2 config\n\n Returns:\n CfgNode: an updated config with new options that will be used\n by :class:`Caffe2Tracer`.\n \"\"\"\n is_frozen = cfg.is_frozen()\n cfg.defrost()\n cfg.EXPORT_CAFFE2 = CN()\n cfg.EXPORT_CAFFE2.USE_HEATMAP_MAX_KEYPOINT = False\n if is_frozen:\n cfg.freeze()\n return cfg\n\n\nclass Caffe2Tracer:\n \"\"\"\n Make a detectron2 model traceable with caffe2 style.\n\n An original detectron2 model may not be traceable, or\n cannot be deployed directly after being traced, due to some reasons:\n 1. control flow in some ops\n 2. custom ops\n 3. complicated pre/post processing\n\n This class provides a traceable version of a detectron2 model by:\n 1. Rewrite parts of the model using ops in caffe2\n 2. Define the inputs \"after pre-processing\" as inputs to the model\n 3. Remove post-processing and produce raw layer outputs\n\n More specifically about inputs: all builtin models take two input tensors.\n (1) NCHW float \"data\" which is an image (usually in [0, 255])\n (2) Nx3 float \"im_info\", each row of which is (height, width, 1.0)\n\n After making a traceable model, the class provide methods to export such a\n model to different deployment formats.\n\n The class currently only supports models using builtin meta architectures.\n\n Experimental. Don't use.\n \"\"\"\n\n def __init__(self, cfg, model, inputs):\n \"\"\"\n Args:\n cfg (CfgNode): a detectron2 config, with extra export-related options\n added by :func:`add_export_config`.\n model (nn.Module): a model built by\n :func:`detectron2.modeling.build_model`.\n inputs: sample inputs that the given model takes for inference.\n Will be used to trace the model.\n \"\"\"\n assert isinstance(cfg, CN), cfg\n assert isinstance(model, torch.nn.Module), type(model)\n if \"EXPORT_CAFFE2\" not in cfg:\n cfg = add_export_config(cfg) # will just the defaults\n\n self.cfg = cfg\n self.model = model\n self.inputs = inputs\n\n def _get_traceable(self):\n # TODO how to make it extensible to support custom models\n C2MetaArch = META_ARCH_CAFFE2_EXPORT_TYPE_MAP[self.cfg.MODEL.META_ARCHITECTURE]\n traceable_model = C2MetaArch(self.cfg, copy.deepcopy(self.model))\n traceable_inputs = traceable_model.get_caffe2_inputs(self.inputs)\n return traceable_model, traceable_inputs\n\n def export_caffe2(self):\n \"\"\"\n Export the model to Caffe2's protobuf format.\n The returned object can be saved with `.save_protobuf()` method.\n The result can be loaded and executed using Caffe2 runtime.\n\n Returns:\n Caffe2Model\n \"\"\"\n model, inputs = self._get_traceable()\n predict_net, init_net = export_caffe2_detection_model(model, inputs)\n return Caffe2Model(predict_net, init_net)\n\n def export_onnx(self):\n \"\"\"\n Export the model to ONNX format.\n Note that the exported model contains custom ops only available in caffe2, therefore it\n cannot be directly executed by other runtime. Post-processing or transformation passes\n may be applied on the model to accommodate different runtimes.\n\n Returns:\n onnx.ModelProto: an onnx model.\n \"\"\"\n model, inputs = self._get_traceable()\n return export_onnx_model_impl(model, (inputs,))\n\n def export_torchscript(self):\n \"\"\"\n Export the model to a `torch.jit.TracedModule` by tracing.\n The returned object can be saved to a file by \".save()\".\n\n Returns:\n torch.jit.TracedModule: a torch TracedModule\n \"\"\"\n model, inputs = self._get_traceable()\n logger = logging.getLogger(__name__)\n logger.info(\"Tracing the model with torch.jit.trace ...\")\n with torch.no_grad():\n return torch.jit.trace(model, (inputs,))\n\n\ndef export_caffe2_model(cfg, model, inputs):\n \"\"\"\n Export a detectron2 model to caffe2 format.\n\n Args:\n cfg (CfgNode): a detectron2 config, with extra export-related options\n added by :func:`add_export_config`.\n model (nn.Module): a model built by\n :func:`detectron2.modeling.build_model`.\n It will be modified by this function.\n inputs: sample inputs that the given model takes for inference.\n Will be used to trace the model.\n\n Returns:\n Caffe2Model\n \"\"\"\n return Caffe2Tracer(cfg, model, inputs).export_caffe2()\n\n\ndef export_onnx_model(cfg, model, inputs):\n \"\"\"\n Export a detectron2 model to ONNX format.\n Note that the exported model contains custom ops only available in caffe2, therefore it\n cannot be directly executed by other runtime. Post-processing or transformation passes\n may be applied on the model to accommodate different runtimes.\n Args:\n cfg (CfgNode): a detectron2 config, with extra export-related options\n added by :func:`add_export_config`.\n model (nn.Module): a model built by\n :func:`detectron2.modeling.build_model`.\n It will be modified by this function.\n inputs: sample inputs that the given model takes for inference.\n Will be used to trace the model.\n Returns:\n onnx.ModelProto: an onnx model.\n \"\"\"\n return Caffe2Tracer(cfg, model, inputs).export_onnx()\n\n\nclass Caffe2Model(nn.Module):\n \"\"\"\n A wrapper around the traced model in caffe2's pb format.\n \"\"\"\n\n def __init__(self, predict_net, init_net):\n super().__init__()\n self.eval() # always in eval mode\n self._predict_net = predict_net\n self._init_net = init_net\n self._predictor = None\n\n @property\n def predict_net(self):\n \"\"\"\n Returns:\n core.Net: the underlying caffe2 predict net\n \"\"\"\n return self._predict_net\n\n @property\n def init_net(self):\n \"\"\"\n Returns:\n core.Net: the underlying caffe2 init net\n \"\"\"\n return self._init_net\n\n __init__.__HIDE_SPHINX_DOC__ = True\n\n def save_protobuf(self, output_dir):\n \"\"\"\n Save the model as caffe2's protobuf format.\n\n Args:\n output_dir (str): the output directory to save protobuf files.\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info(\"Saving model to {} ...\".format(output_dir))\n os.makedirs(output_dir, exist_ok=True)\n\n with open(os.path.join(output_dir, \"model.pb\"), \"wb\") as f:\n f.write(self._predict_net.SerializeToString())\n with open(os.path.join(output_dir, \"model.pbtxt\"), \"w\") as f:\n f.write(str(self._predict_net))\n with open(os.path.join(output_dir, \"model_init.pb\"), \"wb\") as f:\n f.write(self._init_net.SerializeToString())\n\n def save_graph(self, output_file, inputs=None):\n \"\"\"\n Save the graph as SVG format.\n\n Args:\n output_file (str): a SVG file\n inputs: optional inputs given to the model.\n If given, the inputs will be used to run the graph to record\n shape of every tensor. The shape information will be\n saved together with the graph.\n \"\"\"\n if inputs is None:\n save_graph(self._predict_net, output_file, op_only=False)\n else:\n size_divisibility = get_pb_arg_vali(self._predict_net, \"size_divisibility\", 0)\n device = get_pb_arg_vals(self._predict_net, \"device\", b\"cpu\").decode(\"ascii\")\n inputs = convert_batched_inputs_to_c2_format(inputs, size_divisibility, device)\n inputs = [x.cpu().numpy() for x in inputs]\n run_and_save_graph(self._predict_net, self._init_net, inputs, output_file)\n\n @staticmethod\n def load_protobuf(dir):\n \"\"\"\n Args:\n dir (str): a directory used to save Caffe2Model with\n :meth:`save_protobuf`.\n The files \"model.pb\" and \"model_init.pb\" are needed.\n\n Returns:\n Caffe2Model: the caffe2 model loaded from this directory.\n \"\"\"\n predict_net = caffe2_pb2.NetDef()\n with open(os.path.join(dir, \"model.pb\"), \"rb\") as f:\n predict_net.ParseFromString(f.read())\n\n init_net = caffe2_pb2.NetDef()\n with open(os.path.join(dir, \"model_init.pb\"), \"rb\") as f:\n init_net.ParseFromString(f.read())\n\n return Caffe2Model(predict_net, init_net)\n\n def __call__(self, inputs):\n \"\"\"\n An interface that wraps around a caffe2 model and mimics detectron2's models'\n input & output format. This is used to compare the outputs of caffe2 model\n with its original torch model.\n\n Due to the extra conversion between torch/caffe2,\n this method is not meant for benchmark.\n \"\"\"\n if self._predictor is None:\n self._predictor = ProtobufDetectionModel(self._predict_net, self._init_net)\n return self._predictor(inputs)\n" ]
[ [ "torch.no_grad", "torch.jit.trace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
UrielMaD/pandas
[ "b5233c447f3ed0ecfe256501e357326b82ce9120" ]
[ "pandas/core/frame.py" ]
[ "\"\"\"\nDataFrame\n---------\nAn efficient 2D container for potentially mixed-type time series or other\nlabeled data series.\n\nSimilar to its R counterpart, data.frame, except providing automatic data\nalignment and a host of useful data manipulation methods having to do with the\nlabeling information\n\"\"\"\nfrom __future__ import annotations\n\nimport collections\nfrom collections import abc\nimport datetime\nfrom io import StringIO\nimport itertools\nimport mmap\nfrom textwrap import dedent\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n AnyStr,\n Dict,\n FrozenSet,\n Hashable,\n Iterable,\n Iterator,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n Type,\n Union,\n cast,\n overload,\n)\nimport warnings\n\nimport numpy as np\nimport numpy.ma as ma\n\nfrom pandas._config import get_option\n\nfrom pandas._libs import algos as libalgos, lib, properties\nfrom pandas._libs.lib import no_default\nfrom pandas._typing import (\n AggFuncType,\n ArrayLike,\n Axes,\n Axis,\n CompressionOptions,\n Dtype,\n FilePathOrBuffer,\n FrameOrSeriesUnion,\n IndexKeyFunc,\n Label,\n Level,\n Renamer,\n StorageOptions,\n ValueKeyFunc,\n)\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import (\n Appender,\n Substitution,\n deprecate_kwarg,\n doc,\n rewrite_axis_style_signature,\n)\nfrom pandas.util._validators import (\n validate_axis_style_args,\n validate_bool_kwarg,\n validate_percentile,\n)\n\nfrom pandas.core.dtypes.cast import (\n cast_scalar_to_array,\n coerce_to_dtypes,\n construct_1d_arraylike_from_scalar,\n find_common_type,\n infer_dtype_from_scalar,\n invalidate_string_dtypes,\n maybe_box_datetimelike,\n maybe_cast_to_datetime,\n maybe_casted_values,\n maybe_convert_platform,\n maybe_downcast_to_dtype,\n maybe_infer_to_datetimelike,\n maybe_upcast,\n validate_numeric_casting,\n)\nfrom pandas.core.dtypes.common import (\n ensure_int64,\n ensure_platform_int,\n infer_dtype_from_object,\n is_bool_dtype,\n is_dataclass,\n is_datetime64_any_dtype,\n is_dict_like,\n is_dtype_equal,\n is_extension_array_dtype,\n is_float,\n is_float_dtype,\n is_hashable,\n is_integer,\n is_integer_dtype,\n is_iterator,\n is_list_like,\n is_named_tuple,\n is_object_dtype,\n is_scalar,\n is_sequence,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.missing import isna, notna\n\nfrom pandas.core import algorithms, common as com, generic, nanops, ops\nfrom pandas.core.accessor import CachedAccessor\nfrom pandas.core.aggregation import (\n aggregate,\n reconstruct_func,\n relabel_result,\n transform,\n)\nfrom pandas.core.arraylike import OpsMixin\nfrom pandas.core.arrays import Categorical, ExtensionArray\nfrom pandas.core.arrays.sparse import SparseFrameAccessor\nfrom pandas.core.construction import extract_array\nfrom pandas.core.generic import NDFrame, _shared_docs\nfrom pandas.core.indexes import base as ibase\nfrom pandas.core.indexes.api import (\n DatetimeIndex,\n Index,\n PeriodIndex,\n ensure_index,\n ensure_index_from_sequences,\n)\nfrom pandas.core.indexes.multi import MultiIndex, maybe_droplevels\nfrom pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable\nfrom pandas.core.internals import BlockManager\nfrom pandas.core.internals.construction import (\n arrays_to_mgr,\n dataclasses_to_dicts,\n get_names_from_index,\n init_dict,\n init_ndarray,\n masked_rec_array_to_mgr,\n reorder_arrays,\n sanitize_index,\n to_arrays,\n)\nfrom pandas.core.reshape.melt import melt\nfrom pandas.core.series import Series\nfrom pandas.core.sorting import get_group_index, lexsort_indexer, nargsort\n\nfrom pandas.io.common import get_handle\nfrom pandas.io.formats import console, format as fmt\nfrom pandas.io.formats.info import BaseInfo, DataFrameInfo\nimport pandas.plotting\n\nif TYPE_CHECKING:\n from typing import Literal\n\n from pandas.core.groupby.generic import DataFrameGroupBy\n\n from pandas.io.formats.style import Styler\n\n# ---------------------------------------------------------------------\n# Docstring templates\n\n_shared_doc_kwargs = {\n \"axes\": \"index, columns\",\n \"klass\": \"DataFrame\",\n \"axes_single_arg\": \"{0 or 'index', 1 or 'columns'}\",\n \"axis\": \"\"\"axis : {0 or 'index', 1 or 'columns'}, default 0\n If 0 or 'index': apply function to each column.\n If 1 or 'columns': apply function to each row.\"\"\",\n \"optional_by\": \"\"\"\n by : str or list of str\n Name or list of names to sort by.\n\n - if `axis` is 0 or `'index'` then `by` may contain index\n levels and/or column labels.\n - if `axis` is 1 or `'columns'` then `by` may contain column\n levels and/or index labels.\"\"\",\n \"optional_labels\": \"\"\"labels : array-like, optional\n New labels / index to conform the axis specified by 'axis' to.\"\"\",\n \"optional_axis\": \"\"\"axis : int or str, optional\n Axis to target. Can be either the axis name ('index', 'columns')\n or number (0, 1).\"\"\",\n}\n\n_numeric_only_doc = \"\"\"numeric_only : boolean, default None\n Include only float, int, boolean data. If None, will attempt to use\n everything, then use only numeric data\n\"\"\"\n\n_merge_doc = \"\"\"\nMerge DataFrame or named Series objects with a database-style join.\n\nThe join is done on columns or indexes. If joining columns on\ncolumns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes\non indexes or indexes on a column or columns, the index will be passed on.\nWhen performing a cross merge, no column specifications to merge on are\nallowed.\n\nParameters\n----------%s\nright : DataFrame or named Series\n Object to merge with.\nhow : {'left', 'right', 'outer', 'inner', 'cross'}, default 'inner'\n Type of merge to be performed.\n\n * left: use only keys from left frame, similar to a SQL left outer join;\n preserve key order.\n * right: use only keys from right frame, similar to a SQL right outer join;\n preserve key order.\n * outer: use union of keys from both frames, similar to a SQL full outer\n join; sort keys lexicographically.\n * inner: use intersection of keys from both frames, similar to a SQL inner\n join; preserve the order of the left keys.\n * cross: creates the cartesian product from both frames, preserves the order\n of the left keys.\n\n .. versionadded:: 1.2.0\n\non : label or list\n Column or index level names to join on. These must be found in both\n DataFrames. If `on` is None and not merging on indexes then this defaults\n to the intersection of the columns in both DataFrames.\nleft_on : label or list, or array-like\n Column or index level names to join on in the left DataFrame. Can also\n be an array or list of arrays of the length of the left DataFrame.\n These arrays are treated as if they are columns.\nright_on : label or list, or array-like\n Column or index level names to join on in the right DataFrame. Can also\n be an array or list of arrays of the length of the right DataFrame.\n These arrays are treated as if they are columns.\nleft_index : bool, default False\n Use the index from the left DataFrame as the join key(s). If it is a\n MultiIndex, the number of keys in the other DataFrame (either the index\n or a number of columns) must match the number of levels.\nright_index : bool, default False\n Use the index from the right DataFrame as the join key. Same caveats as\n left_index.\nsort : bool, default False\n Sort the join keys lexicographically in the result DataFrame. If False,\n the order of the join keys depends on the join type (how keyword).\nsuffixes : list-like, default is (\"_x\", \"_y\")\n A length-2 sequence where each element is optionally a string\n indicating the suffix to add to overlapping column names in\n `left` and `right` respectively. Pass a value of `None` instead\n of a string to indicate that the column name from `left` or\n `right` should be left as-is, with no suffix. At least one of the\n values must not be None.\ncopy : bool, default True\n If False, avoid copy if possible.\nindicator : bool or str, default False\n If True, adds a column to the output DataFrame called \"_merge\" with\n information on the source of each row. The column can be given a different\n name by providing a string argument. The column will have a Categorical\n type with the value of \"left_only\" for observations whose merge key only\n appears in the left DataFrame, \"right_only\" for observations\n whose merge key only appears in the right DataFrame, and \"both\"\n if the observation's merge key is found in both DataFrames.\n\nvalidate : str, optional\n If specified, checks if merge is of specified type.\n\n * \"one_to_one\" or \"1:1\": check if merge keys are unique in both\n left and right datasets.\n * \"one_to_many\" or \"1:m\": check if merge keys are unique in left\n dataset.\n * \"many_to_one\" or \"m:1\": check if merge keys are unique in right\n dataset.\n * \"many_to_many\" or \"m:m\": allowed, but does not result in checks.\n\nReturns\n-------\nDataFrame\n A DataFrame of the two merged objects.\n\nSee Also\n--------\nmerge_ordered : Merge with optional filling/interpolation.\nmerge_asof : Merge on nearest keys.\nDataFrame.join : Similar method using indices.\n\nNotes\n-----\nSupport for specifying index levels as the `on`, `left_on`, and\n`right_on` parameters was added in version 0.23.0\nSupport for merging named Series objects was added in version 0.24.0\n\nExamples\n--------\n>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],\n... 'value': [1, 2, 3, 5]})\n>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],\n... 'value': [5, 6, 7, 8]})\n>>> df1\n lkey value\n0 foo 1\n1 bar 2\n2 baz 3\n3 foo 5\n>>> df2\n rkey value\n0 foo 5\n1 bar 6\n2 baz 7\n3 foo 8\n\nMerge df1 and df2 on the lkey and rkey columns. The value columns have\nthe default suffixes, _x and _y, appended.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey')\n lkey value_x rkey value_y\n0 foo 1 foo 5\n1 foo 1 foo 8\n2 foo 5 foo 5\n3 foo 5 foo 8\n4 bar 2 bar 6\n5 baz 3 baz 7\n\nMerge DataFrames df1 and df2 with specified left and right suffixes\nappended to any overlapping columns.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey',\n... suffixes=('_left', '_right'))\n lkey value_left rkey value_right\n0 foo 1 foo 5\n1 foo 1 foo 8\n2 foo 5 foo 5\n3 foo 5 foo 8\n4 bar 2 bar 6\n5 baz 3 baz 7\n\nMerge DataFrames df1 and df2, but raise an exception if the DataFrames have\nany overlapping columns.\n\n>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))\nTraceback (most recent call last):\n...\nValueError: columns overlap but no suffix specified:\n Index(['value'], dtype='object')\n\n>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})\n>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})\n>>> df1\n a b\n0 foo 1\n1 bar 2\n>>> df2\n a c\n0 foo 3\n1 baz 4\n\n>>> df1.merge(df2, how='inner', on='a')\n a b c\n0 foo 1 3\n\n>>> df1.merge(df2, how='left', on='a')\n a b c\n0 foo 1 3.0\n1 bar 2 NaN\n\n>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})\n>>> df2 = pd.DataFrame({'right': [7, 8]})\n>>> df1\n left\n0 foo\n1 bar\n>>> df2\n right\n0 7\n1 8\n\n>>> df1.merge(df2, how='cross')\n left right\n0 foo 7\n1 foo 8\n2 bar 7\n3 bar 8\n\"\"\"\n\n\n# -----------------------------------------------------------------------\n# DataFrame class\n\n\nclass DataFrame(NDFrame, OpsMixin):\n \"\"\"\n Two-dimensional, size-mutable, potentially heterogeneous tabular data.\n\n Data structure also contains labeled axes (rows and columns).\n Arithmetic operations align on both row and column labels. Can be\n thought of as a dict-like container for Series objects. The primary\n pandas data structure.\n\n Parameters\n ----------\n data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame\n Dict can contain Series, arrays, constants, dataclass or list-like objects. If\n data is a dict, column order follows insertion-order.\n\n .. versionchanged:: 0.25.0\n If data is a list of dicts, column order follows insertion-order.\n\n index : Index or array-like\n Index to use for resulting frame. Will default to RangeIndex if\n no indexing information part of input data and no index provided.\n columns : Index or array-like\n Column labels to use for resulting frame. Will default to\n RangeIndex (0, 1, 2, ..., n) if no column labels are provided.\n dtype : dtype, default None\n Data type to force. Only a single dtype is allowed. If None, infer.\n copy : bool, default False\n Copy data from inputs. Only affects DataFrame / 2d ndarray input.\n\n See Also\n --------\n DataFrame.from_records : Constructor from tuples, also record arrays.\n DataFrame.from_dict : From dicts of Series, arrays, or dicts.\n read_csv : Read a comma-separated values (csv) file into DataFrame.\n read_table : Read general delimited file into DataFrame.\n read_clipboard : Read text from clipboard into DataFrame.\n\n Examples\n --------\n Constructing DataFrame from a dictionary.\n\n >>> d = {'col1': [1, 2], 'col2': [3, 4]}\n >>> df = pd.DataFrame(data=d)\n >>> df\n col1 col2\n 0 1 3\n 1 2 4\n\n Notice that the inferred dtype is int64.\n\n >>> df.dtypes\n col1 int64\n col2 int64\n dtype: object\n\n To enforce a single dtype:\n\n >>> df = pd.DataFrame(data=d, dtype=np.int8)\n >>> df.dtypes\n col1 int8\n col2 int8\n dtype: object\n\n Constructing DataFrame from numpy ndarray:\n\n >>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n ... columns=['a', 'b', 'c'])\n >>> df2\n a b c\n 0 1 2 3\n 1 4 5 6\n 2 7 8 9\n\n Constructing DataFrame from dataclass:\n\n >>> from dataclasses import make_dataclass\n >>> Point = make_dataclass(\"Point\", [(\"x\", int), (\"y\", int)])\n >>> pd.DataFrame([Point(0, 0), Point(0, 3), Point(2, 3)])\n x y\n 0 0 0\n 1 0 3\n 2 2 3\n \"\"\"\n\n _internal_names_set = {\"columns\", \"index\"} | NDFrame._internal_names_set\n _typ = \"dataframe\"\n _HANDLED_TYPES = (Series, Index, ExtensionArray, np.ndarray)\n\n @property\n def _constructor(self) -> Type[DataFrame]:\n return DataFrame\n\n _constructor_sliced: Type[Series] = Series\n _hidden_attrs: FrozenSet[str] = NDFrame._hidden_attrs | frozenset([])\n _accessors: Set[str] = {\"sparse\"}\n\n @property\n def _constructor_expanddim(self):\n # GH#31549 raising NotImplementedError on a property causes trouble\n # for `inspect`\n def constructor(*args, **kwargs):\n raise NotImplementedError(\"Not supported for DataFrames!\")\n\n return constructor\n\n # ----------------------------------------------------------------------\n # Constructors\n\n def __init__(\n self,\n data=None,\n index: Optional[Axes] = None,\n columns: Optional[Axes] = None,\n dtype: Optional[Dtype] = None,\n copy: bool = False,\n ):\n if data is None:\n data = {}\n if dtype is not None:\n dtype = self._validate_dtype(dtype)\n\n if isinstance(data, DataFrame):\n data = data._mgr\n\n if isinstance(data, BlockManager):\n if index is None and columns is None and dtype is None and copy is False:\n # GH#33357 fastpath\n NDFrame.__init__(self, data)\n return\n\n mgr = self._init_mgr(\n data, axes={\"index\": index, \"columns\": columns}, dtype=dtype, copy=copy\n )\n\n elif isinstance(data, dict):\n mgr = init_dict(data, index, columns, dtype=dtype)\n elif isinstance(data, ma.MaskedArray):\n import numpy.ma.mrecords as mrecords\n\n # masked recarray\n if isinstance(data, mrecords.MaskedRecords):\n mgr = masked_rec_array_to_mgr(data, index, columns, dtype, copy)\n\n # a masked array\n else:\n mask = ma.getmaskarray(data)\n if mask.any():\n data, fill_value = maybe_upcast(data, copy=True)\n data.soften_mask() # set hardmask False if it was True\n data[mask] = fill_value\n else:\n data = data.copy()\n mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)\n\n elif isinstance(data, (np.ndarray, Series, Index)):\n if data.dtype.names:\n data_columns = list(data.dtype.names)\n data = {k: data[k] for k in data_columns}\n if columns is None:\n columns = data_columns\n mgr = init_dict(data, index, columns, dtype=dtype)\n elif getattr(data, \"name\", None) is not None:\n mgr = init_dict({data.name: data}, index, columns, dtype=dtype)\n else:\n mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)\n\n # For data is list-like, or Iterable (will consume into list)\n elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):\n if not isinstance(data, (abc.Sequence, ExtensionArray)):\n data = list(data)\n if len(data) > 0:\n if is_dataclass(data[0]):\n data = dataclasses_to_dicts(data)\n if is_list_like(data[0]) and getattr(data[0], \"ndim\", 1) == 1:\n if is_named_tuple(data[0]) and columns is None:\n columns = data[0]._fields\n arrays, columns = to_arrays(data, columns, dtype=dtype)\n columns = ensure_index(columns)\n\n # set the index\n if index is None:\n if isinstance(data[0], Series):\n index = get_names_from_index(data)\n elif isinstance(data[0], Categorical):\n index = ibase.default_index(len(data[0]))\n else:\n index = ibase.default_index(len(data))\n\n mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)\n else:\n mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)\n else:\n mgr = init_dict({}, index, columns, dtype=dtype)\n # For data is scalar\n else:\n if index is None or columns is None:\n raise ValueError(\"DataFrame constructor not properly called!\")\n\n if not dtype:\n dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)\n\n # For data is a scalar extension dtype\n if is_extension_array_dtype(dtype):\n\n values = [\n construct_1d_arraylike_from_scalar(data, len(index), dtype)\n for _ in range(len(columns))\n ]\n mgr = arrays_to_mgr(values, columns, index, columns, dtype=None)\n else:\n # Attempt to coerce to a numpy array\n try:\n arr = np.array(data, dtype=dtype, copy=copy)\n except (ValueError, TypeError) as err:\n exc = TypeError(\n \"DataFrame constructor called with \"\n f\"incompatible data and dtype: {err}\"\n )\n raise exc from err\n\n if arr.ndim != 0:\n raise ValueError(\"DataFrame constructor not properly called!\")\n\n values = cast_scalar_to_array(\n (len(index), len(columns)), data, dtype=dtype\n )\n\n mgr = init_ndarray(\n values, index, columns, dtype=values.dtype, copy=False\n )\n\n NDFrame.__init__(self, mgr)\n\n # ----------------------------------------------------------------------\n\n @property\n def axes(self) -> List[Index]:\n \"\"\"\n Return a list representing the axes of the DataFrame.\n\n It has the row axis labels and column axis labels as the only members.\n They are returned in that order.\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.axes\n [RangeIndex(start=0, stop=2, step=1), Index(['col1', 'col2'],\n dtype='object')]\n \"\"\"\n return [self.index, self.columns]\n\n @property\n def shape(self) -> Tuple[int, int]:\n \"\"\"\n Return a tuple representing the dimensionality of the DataFrame.\n\n See Also\n --------\n ndarray.shape : Tuple of array dimensions.\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.shape\n (2, 2)\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4],\n ... 'col3': [5, 6]})\n >>> df.shape\n (2, 3)\n \"\"\"\n return len(self.index), len(self.columns)\n\n @property\n def _is_homogeneous_type(self) -> bool:\n \"\"\"\n Whether all the columns in a DataFrame have the same type.\n\n Returns\n -------\n bool\n\n See Also\n --------\n Index._is_homogeneous_type : Whether the object has a single\n dtype.\n MultiIndex._is_homogeneous_type : Whether all the levels of a\n MultiIndex have the same dtype.\n\n Examples\n --------\n >>> DataFrame({\"A\": [1, 2], \"B\": [3, 4]})._is_homogeneous_type\n True\n >>> DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.0]})._is_homogeneous_type\n False\n\n Items with the same type but different sizes are considered\n different types.\n\n >>> DataFrame({\n ... \"A\": np.array([1, 2], dtype=np.int32),\n ... \"B\": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type\n False\n \"\"\"\n if self._mgr.any_extension_types:\n return len({block.dtype for block in self._mgr.blocks}) == 1\n else:\n return not self._is_mixed_type\n\n @property\n def _can_fast_transpose(self) -> bool:\n \"\"\"\n Can we transpose this DataFrame without creating any new array objects.\n \"\"\"\n if self._mgr.any_extension_types:\n # TODO(EA2D) special case would be unnecessary with 2D EAs\n return False\n return len(self._mgr.blocks) == 1\n\n # ----------------------------------------------------------------------\n # Rendering Methods\n\n def _repr_fits_vertical_(self) -> bool:\n \"\"\"\n Check length against max_rows.\n \"\"\"\n max_rows = get_option(\"display.max_rows\")\n return len(self) <= max_rows\n\n def _repr_fits_horizontal_(self, ignore_width: bool = False) -> bool:\n \"\"\"\n Check if full repr fits in horizontal boundaries imposed by the display\n options width and max_columns.\n\n In case of non-interactive session, no boundaries apply.\n\n `ignore_width` is here so ipynb+HTML output can behave the way\n users expect. display.max_columns remains in effect.\n GH3541, GH3573\n \"\"\"\n width, height = console.get_console_size()\n max_columns = get_option(\"display.max_columns\")\n nb_columns = len(self.columns)\n\n # exceed max columns\n if (max_columns and nb_columns > max_columns) or (\n (not ignore_width) and width and nb_columns > (width // 2)\n ):\n return False\n\n # used by repr_html under IPython notebook or scripts ignore terminal\n # dims\n if ignore_width or not console.in_interactive_session():\n return True\n\n if get_option(\"display.width\") is not None or console.in_ipython_frontend():\n # check at least the column row for excessive width\n max_rows = 1\n else:\n max_rows = get_option(\"display.max_rows\")\n\n # when auto-detecting, so width=None and not in ipython front end\n # check whether repr fits horizontal by actually checking\n # the width of the rendered repr\n buf = StringIO()\n\n # only care about the stuff we'll actually print out\n # and to_string on entire frame may be expensive\n d = self\n\n if not (max_rows is None): # unlimited rows\n # min of two, where one may be None\n d = d.iloc[: min(max_rows, len(d))]\n else:\n return True\n\n d.to_string(buf=buf)\n value = buf.getvalue()\n repr_width = max(len(line) for line in value.split(\"\\n\"))\n\n return repr_width < width\n\n def _info_repr(self) -> bool:\n \"\"\"\n True if the repr should show the info view.\n \"\"\"\n info_repr_option = get_option(\"display.large_repr\") == \"info\"\n return info_repr_option and not (\n self._repr_fits_horizontal_() and self._repr_fits_vertical_()\n )\n\n def __repr__(self) -> str:\n \"\"\"\n Return a string representation for a particular DataFrame.\n \"\"\"\n buf = StringIO(\"\")\n if self._info_repr():\n self.info(buf=buf)\n return buf.getvalue()\n\n max_rows = get_option(\"display.max_rows\")\n min_rows = get_option(\"display.min_rows\")\n max_cols = get_option(\"display.max_columns\")\n max_colwidth = get_option(\"display.max_colwidth\")\n show_dimensions = get_option(\"display.show_dimensions\")\n if get_option(\"display.expand_frame_repr\"):\n width, _ = console.get_console_size()\n else:\n width = None\n self.to_string(\n buf=buf,\n max_rows=max_rows,\n min_rows=min_rows,\n max_cols=max_cols,\n line_width=width,\n max_colwidth=max_colwidth,\n show_dimensions=show_dimensions,\n )\n\n return buf.getvalue()\n\n def _repr_html_(self) -> Optional[str]:\n \"\"\"\n Return a html representation for a particular DataFrame.\n\n Mainly for IPython notebook.\n \"\"\"\n if self._info_repr():\n buf = StringIO(\"\")\n self.info(buf=buf)\n # need to escape the <class>, should be the first line.\n val = buf.getvalue().replace(\"<\", r\"&lt;\", 1)\n val = val.replace(\">\", r\"&gt;\", 1)\n return \"<pre>\" + val + \"</pre>\"\n\n if get_option(\"display.notebook_repr_html\"):\n max_rows = get_option(\"display.max_rows\")\n min_rows = get_option(\"display.min_rows\")\n max_cols = get_option(\"display.max_columns\")\n show_dimensions = get_option(\"display.show_dimensions\")\n\n formatter = fmt.DataFrameFormatter(\n self,\n columns=None,\n col_space=None,\n na_rep=\"NaN\",\n formatters=None,\n float_format=None,\n sparsify=None,\n justify=None,\n index_names=True,\n header=True,\n index=True,\n bold_rows=True,\n escape=True,\n max_rows=max_rows,\n min_rows=min_rows,\n max_cols=max_cols,\n show_dimensions=show_dimensions,\n decimal=\".\",\n )\n return fmt.DataFrameRenderer(formatter).to_html(notebook=True)\n else:\n return None\n\n @Substitution(\n header_type=\"bool or sequence\",\n header=\"Write out the column names. If a list of strings \"\n \"is given, it is assumed to be aliases for the \"\n \"column names\",\n col_space_type=\"int, list or dict of int\",\n col_space=\"The minimum width of each column\",\n )\n @Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)\n def to_string(\n self,\n buf: Optional[FilePathOrBuffer[str]] = None,\n columns: Optional[Sequence[str]] = None,\n col_space: Optional[int] = None,\n header: Union[bool, Sequence[str]] = True,\n index: bool = True,\n na_rep: str = \"NaN\",\n formatters: Optional[fmt.FormattersType] = None,\n float_format: Optional[fmt.FloatFormatType] = None,\n sparsify: Optional[bool] = None,\n index_names: bool = True,\n justify: Optional[str] = None,\n max_rows: Optional[int] = None,\n min_rows: Optional[int] = None,\n max_cols: Optional[int] = None,\n show_dimensions: bool = False,\n decimal: str = \".\",\n line_width: Optional[int] = None,\n max_colwidth: Optional[int] = None,\n encoding: Optional[str] = None,\n ) -> Optional[str]:\n \"\"\"\n Render a DataFrame to a console-friendly tabular output.\n %(shared_params)s\n line_width : int, optional\n Width to wrap a line in characters.\n max_colwidth : int, optional\n Max width to truncate each column in characters. By default, no limit.\n\n .. versionadded:: 1.0.0\n encoding : str, default \"utf-8\"\n Set character encoding.\n\n .. versionadded:: 1.0\n %(returns)s\n See Also\n --------\n to_html : Convert DataFrame to HTML.\n\n Examples\n --------\n >>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}\n >>> df = pd.DataFrame(d)\n >>> print(df.to_string())\n col1 col2\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n from pandas import option_context\n\n with option_context(\"display.max_colwidth\", max_colwidth):\n formatter = fmt.DataFrameFormatter(\n self,\n columns=columns,\n col_space=col_space,\n na_rep=na_rep,\n formatters=formatters,\n float_format=float_format,\n sparsify=sparsify,\n justify=justify,\n index_names=index_names,\n header=header,\n index=index,\n min_rows=min_rows,\n max_rows=max_rows,\n max_cols=max_cols,\n show_dimensions=show_dimensions,\n decimal=decimal,\n )\n return fmt.DataFrameRenderer(formatter).to_string(\n buf=buf,\n encoding=encoding,\n line_width=line_width,\n )\n\n # ----------------------------------------------------------------------\n\n @property\n def style(self) -> Styler:\n \"\"\"\n Returns a Styler object.\n\n Contains methods for building a styled HTML representation of the DataFrame.\n\n See Also\n --------\n io.formats.style.Styler : Helps style a DataFrame or Series according to the\n data with HTML and CSS.\n \"\"\"\n from pandas.io.formats.style import Styler\n\n return Styler(self)\n\n _shared_docs[\n \"items\"\n ] = r\"\"\"\n Iterate over (column name, Series) pairs.\n\n Iterates over the DataFrame columns, returning a tuple with\n the column name and the content as a Series.\n\n Yields\n ------\n label : object\n The column names for the DataFrame being iterated over.\n content : Series\n The column entries belonging to each label, as a Series.\n\n See Also\n --------\n DataFrame.iterrows : Iterate over DataFrame rows as\n (index, Series) pairs.\n DataFrame.itertuples : Iterate over DataFrame rows as namedtuples\n of the values.\n\n Examples\n --------\n >>> df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],\n ... 'population': [1864, 22000, 80000]},\n ... index=['panda', 'polar', 'koala'])\n >>> df\n species population\n panda bear 1864\n polar bear 22000\n koala marsupial 80000\n >>> for label, content in df.items():\n ... print(f'label: {label}')\n ... print(f'content: {content}', sep='\\n')\n ...\n label: species\n content:\n panda bear\n polar bear\n koala marsupial\n Name: species, dtype: object\n label: population\n content:\n panda 1864\n polar 22000\n koala 80000\n Name: population, dtype: int64\n \"\"\"\n\n @Appender(_shared_docs[\"items\"])\n def items(self) -> Iterable[Tuple[Label, Series]]:\n if self.columns.is_unique and hasattr(self, \"_item_cache\"):\n for k in self.columns:\n yield k, self._get_item_cache(k)\n else:\n for i, k in enumerate(self.columns):\n yield k, self._ixs(i, axis=1)\n\n @Appender(_shared_docs[\"items\"])\n def iteritems(self) -> Iterable[Tuple[Label, Series]]:\n yield from self.items()\n\n def iterrows(self) -> Iterable[Tuple[Label, Series]]:\n \"\"\"\n Iterate over DataFrame rows as (index, Series) pairs.\n\n Yields\n ------\n index : label or tuple of label\n The index of the row. A tuple for a `MultiIndex`.\n data : Series\n The data of the row as a Series.\n\n See Also\n --------\n DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values.\n DataFrame.items : Iterate over (column name, Series) pairs.\n\n Notes\n -----\n 1. Because ``iterrows`` returns a Series for each row,\n it does **not** preserve dtypes across the rows (dtypes are\n preserved across columns for DataFrames). For example,\n\n >>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])\n >>> row = next(df.iterrows())[1]\n >>> row\n int 1.0\n float 1.5\n Name: 0, dtype: float64\n >>> print(row['int'].dtype)\n float64\n >>> print(df['int'].dtype)\n int64\n\n To preserve dtypes while iterating over the rows, it is better\n to use :meth:`itertuples` which returns namedtuples of the values\n and which is generally faster than ``iterrows``.\n\n 2. You should **never modify** something you are iterating over.\n This is not guaranteed to work in all cases. Depending on the\n data types, the iterator returns a copy and not a view, and writing\n to it will have no effect.\n \"\"\"\n columns = self.columns\n klass = self._constructor_sliced\n for k, v in zip(self.index, self.values):\n s = klass(v, index=columns, name=k)\n yield k, s\n\n def itertuples(self, index: bool = True, name: Optional[str] = \"Pandas\"):\n \"\"\"\n Iterate over DataFrame rows as namedtuples.\n\n Parameters\n ----------\n index : bool, default True\n If True, return the index as the first element of the tuple.\n name : str or None, default \"Pandas\"\n The name of the returned namedtuples or None to return regular\n tuples.\n\n Returns\n -------\n iterator\n An object to iterate over namedtuples for each row in the\n DataFrame with the first field possibly being the index and\n following fields being the column values.\n\n See Also\n --------\n DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)\n pairs.\n DataFrame.items : Iterate over (column name, Series) pairs.\n\n Notes\n -----\n The column names will be renamed to positional names if they are\n invalid Python identifiers, repeated, or start with an underscore.\n On python versions < 3.7 regular tuples are returned for DataFrames\n with a large number of columns (>254).\n\n Examples\n --------\n >>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},\n ... index=['dog', 'hawk'])\n >>> df\n num_legs num_wings\n dog 4 0\n hawk 2 2\n >>> for row in df.itertuples():\n ... print(row)\n ...\n Pandas(Index='dog', num_legs=4, num_wings=0)\n Pandas(Index='hawk', num_legs=2, num_wings=2)\n\n By setting the `index` parameter to False we can remove the index\n as the first element of the tuple:\n\n >>> for row in df.itertuples(index=False):\n ... print(row)\n ...\n Pandas(num_legs=4, num_wings=0)\n Pandas(num_legs=2, num_wings=2)\n\n With the `name` parameter set we set a custom name for the yielded\n namedtuples:\n\n >>> for row in df.itertuples(name='Animal'):\n ... print(row)\n ...\n Animal(Index='dog', num_legs=4, num_wings=0)\n Animal(Index='hawk', num_legs=2, num_wings=2)\n \"\"\"\n arrays = []\n fields = list(self.columns)\n if index:\n arrays.append(self.index)\n fields.insert(0, \"Index\")\n\n # use integer indexing because of possible duplicate column names\n arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))\n\n if name is not None:\n # https://github.com/python/mypy/issues/9046\n # error: namedtuple() expects a string literal as the first argument\n itertuple = collections.namedtuple( # type: ignore[misc]\n name, fields, rename=True\n )\n return map(itertuple._make, zip(*arrays))\n\n # fallback to regular tuples\n return zip(*arrays)\n\n def __len__(self) -> int:\n \"\"\"\n Returns length of info axis, but here we use the index.\n \"\"\"\n return len(self.index)\n\n def dot(self, other):\n \"\"\"\n Compute the matrix multiplication between the DataFrame and other.\n\n This method computes the matrix product between the DataFrame and the\n values of an other Series, DataFrame or a numpy array.\n\n It can also be called using ``self @ other`` in Python >= 3.5.\n\n Parameters\n ----------\n other : Series, DataFrame or array-like\n The other object to compute the matrix product with.\n\n Returns\n -------\n Series or DataFrame\n If other is a Series, return the matrix product between self and\n other as a Series. If other is a DataFrame or a numpy.array, return\n the matrix product of self and other in a DataFrame of a np.array.\n\n See Also\n --------\n Series.dot: Similar method for Series.\n\n Notes\n -----\n The dimensions of DataFrame and other must be compatible in order to\n compute the matrix multiplication. In addition, the column names of\n DataFrame and the index of other must contain the same values, as they\n will be aligned prior to the multiplication.\n\n The dot method for Series computes the inner product, instead of the\n matrix product here.\n\n Examples\n --------\n Here we multiply a DataFrame with a Series.\n\n >>> df = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])\n >>> s = pd.Series([1, 1, 2, 1])\n >>> df.dot(s)\n 0 -4\n 1 5\n dtype: int64\n\n Here we multiply a DataFrame with another DataFrame.\n\n >>> other = pd.DataFrame([[0, 1], [1, 2], [-1, -1], [2, 0]])\n >>> df.dot(other)\n 0 1\n 0 1 4\n 1 2 2\n\n Note that the dot method give the same result as @\n\n >>> df @ other\n 0 1\n 0 1 4\n 1 2 2\n\n The dot method works also if other is an np.array.\n\n >>> arr = np.array([[0, 1], [1, 2], [-1, -1], [2, 0]])\n >>> df.dot(arr)\n 0 1\n 0 1 4\n 1 2 2\n\n Note how shuffling of the objects does not change the result.\n\n >>> s2 = s.reindex([1, 0, 2, 3])\n >>> df.dot(s2)\n 0 -4\n 1 5\n dtype: int64\n \"\"\"\n if isinstance(other, (Series, DataFrame)):\n common = self.columns.union(other.index)\n if len(common) > len(self.columns) or len(common) > len(other.index):\n raise ValueError(\"matrices are not aligned\")\n\n left = self.reindex(columns=common, copy=False)\n right = other.reindex(index=common, copy=False)\n lvals = left.values\n rvals = right._values\n else:\n left = self\n lvals = self.values\n rvals = np.asarray(other)\n if lvals.shape[1] != rvals.shape[0]:\n raise ValueError(\n f\"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}\"\n )\n\n if isinstance(other, DataFrame):\n return self._constructor(\n np.dot(lvals, rvals), index=left.index, columns=other.columns\n )\n elif isinstance(other, Series):\n return self._constructor_sliced(np.dot(lvals, rvals), index=left.index)\n elif isinstance(rvals, (np.ndarray, Index)):\n result = np.dot(lvals, rvals)\n if result.ndim == 2:\n return self._constructor(result, index=left.index)\n else:\n return self._constructor_sliced(result, index=left.index)\n else: # pragma: no cover\n raise TypeError(f\"unsupported type: {type(other)}\")\n\n def __matmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.dot(other)\n\n def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n try:\n return self.T.dot(np.transpose(other)).T\n except ValueError as err:\n if \"shape mismatch\" not in str(err):\n raise\n # GH#21581 give exception message for original shapes\n msg = f\"shapes {np.shape(other)} and {self.shape} not aligned\"\n raise ValueError(msg) from err\n\n # ----------------------------------------------------------------------\n # IO methods (to / from other formats)\n\n @classmethod\n def from_dict(cls, data, orient=\"columns\", dtype=None, columns=None) -> DataFrame:\n \"\"\"\n Construct DataFrame from dict of array-like or dicts.\n\n Creates DataFrame object from dictionary by columns or by index\n allowing dtype specification.\n\n Parameters\n ----------\n data : dict\n Of the form {field : array-like} or {field : dict}.\n orient : {'columns', 'index'}, default 'columns'\n The \"orientation\" of the data. If the keys of the passed dict\n should be the columns of the resulting DataFrame, pass 'columns'\n (default). Otherwise if the keys should be rows, pass 'index'.\n dtype : dtype, default None\n Data type to force, otherwise infer.\n columns : list, default None\n Column labels to use when ``orient='index'``. Raises a ValueError\n if used with ``orient='columns'``.\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n DataFrame.from_records : DataFrame from structured ndarray, sequence\n of tuples or dicts, or DataFrame.\n DataFrame : DataFrame object creation using constructor.\n\n Examples\n --------\n By default the keys of the dict become the DataFrame columns:\n\n >>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}\n >>> pd.DataFrame.from_dict(data)\n col_1 col_2\n 0 3 a\n 1 2 b\n 2 1 c\n 3 0 d\n\n Specify ``orient='index'`` to create the DataFrame using dictionary\n keys as rows:\n\n >>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}\n >>> pd.DataFrame.from_dict(data, orient='index')\n 0 1 2 3\n row_1 3 2 1 0\n row_2 a b c d\n\n When using the 'index' orientation, the column names can be\n specified manually:\n\n >>> pd.DataFrame.from_dict(data, orient='index',\n ... columns=['A', 'B', 'C', 'D'])\n A B C D\n row_1 3 2 1 0\n row_2 a b c d\n \"\"\"\n index = None\n orient = orient.lower()\n if orient == \"index\":\n if len(data) > 0:\n # TODO speed up Series case\n if isinstance(list(data.values())[0], (Series, dict)):\n data = _from_nested_dict(data)\n else:\n data, index = list(data.values()), list(data.keys())\n elif orient == \"columns\":\n if columns is not None:\n raise ValueError(\"cannot use columns parameter with orient='columns'\")\n else: # pragma: no cover\n raise ValueError(\"only recognize index or columns for orient\")\n\n return cls(data, index=index, columns=columns, dtype=dtype)\n\n def to_numpy(\n self, dtype=None, copy: bool = False, na_value=lib.no_default\n ) -> np.ndarray:\n \"\"\"\n Convert the DataFrame to a NumPy array.\n\n .. versionadded:: 0.24.0\n\n By default, the dtype of the returned array will be the common NumPy\n dtype of all types in the DataFrame. For example, if the dtypes are\n ``float16`` and ``float32``, the results dtype will be ``float32``.\n This may require copying data and coercing values, which may be\n expensive.\n\n Parameters\n ----------\n dtype : str or numpy.dtype, optional\n The dtype to pass to :meth:`numpy.asarray`.\n copy : bool, default False\n Whether to ensure that the returned value is not a view on\n another array. Note that ``copy=False`` does not *ensure* that\n ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that\n a copy is made, even if not strictly necessary.\n na_value : Any, optional\n The value to use for missing values. The default value depends\n on `dtype` and the dtypes of the DataFrame columns.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n numpy.ndarray\n\n See Also\n --------\n Series.to_numpy : Similar method for Series.\n\n Examples\n --------\n >>> pd.DataFrame({\"A\": [1, 2], \"B\": [3, 4]}).to_numpy()\n array([[1, 3],\n [2, 4]])\n\n With heterogeneous data, the lowest common type will have to\n be used.\n\n >>> df = pd.DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.5]})\n >>> df.to_numpy()\n array([[1. , 3. ],\n [2. , 4.5]])\n\n For a mix of numeric and non-numeric types, the output array will\n have object dtype.\n\n >>> df['C'] = pd.date_range('2000', periods=2)\n >>> df.to_numpy()\n array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],\n [2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)\n \"\"\"\n self._consolidate_inplace()\n result = self._mgr.as_array(\n transpose=self._AXIS_REVERSED, dtype=dtype, copy=copy, na_value=na_value\n )\n if result.dtype is not dtype:\n result = np.array(result, dtype=dtype, copy=False)\n\n return result\n\n def to_dict(self, orient=\"dict\", into=dict):\n \"\"\"\n Convert the DataFrame to a dictionary.\n\n The type of the key-value pairs can be customized with the parameters\n (see below).\n\n Parameters\n ----------\n orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}\n Determines the type of the values of the dictionary.\n\n - 'dict' (default) : dict like {column -> {index -> value}}\n - 'list' : dict like {column -> [values]}\n - 'series' : dict like {column -> Series(values)}\n - 'split' : dict like\n {'index' -> [index], 'columns' -> [columns], 'data' -> [values]}\n - 'records' : list like\n [{column -> value}, ... , {column -> value}]\n - 'index' : dict like {index -> {column -> value}}\n\n Abbreviations are allowed. `s` indicates `series` and `sp`\n indicates `split`.\n\n into : class, default dict\n The collections.abc.Mapping subclass used for all Mappings\n in the return value. Can be the actual class or an empty\n instance of the mapping type you want. If you want a\n collections.defaultdict, you must pass it initialized.\n\n Returns\n -------\n dict, list or collections.abc.Mapping\n Return a collections.abc.Mapping object representing the DataFrame.\n The resulting transformation depends on the `orient` parameter.\n\n See Also\n --------\n DataFrame.from_dict: Create a DataFrame from a dictionary.\n DataFrame.to_json: Convert a DataFrame to JSON format.\n\n Examples\n --------\n >>> df = pd.DataFrame({'col1': [1, 2],\n ... 'col2': [0.5, 0.75]},\n ... index=['row1', 'row2'])\n >>> df\n col1 col2\n row1 1 0.50\n row2 2 0.75\n >>> df.to_dict()\n {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}\n\n You can specify the return orientation.\n\n >>> df.to_dict('series')\n {'col1': row1 1\n row2 2\n Name: col1, dtype: int64,\n 'col2': row1 0.50\n row2 0.75\n Name: col2, dtype: float64}\n\n >>> df.to_dict('split')\n {'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],\n 'data': [[1, 0.5], [2, 0.75]]}\n\n >>> df.to_dict('records')\n [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]\n\n >>> df.to_dict('index')\n {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}\n\n You can also specify the mapping type.\n\n >>> from collections import OrderedDict, defaultdict\n >>> df.to_dict(into=OrderedDict)\n OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),\n ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])\n\n If you want a `defaultdict`, you need to initialize it:\n\n >>> dd = defaultdict(list)\n >>> df.to_dict('records', into=dd)\n [defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),\n defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]\n \"\"\"\n if not self.columns.is_unique:\n warnings.warn(\n \"DataFrame columns are not unique, some columns will be omitted.\",\n UserWarning,\n stacklevel=2,\n )\n # GH16122\n into_c = com.standardize_mapping(into)\n\n orient = orient.lower()\n # GH32515\n if orient.startswith((\"d\", \"l\", \"s\", \"r\", \"i\")) and orient not in {\n \"dict\",\n \"list\",\n \"series\",\n \"split\",\n \"records\",\n \"index\",\n }:\n warnings.warn(\n \"Using short name for 'orient' is deprecated. Only the \"\n \"options: ('dict', list, 'series', 'split', 'records', 'index') \"\n \"will be used in a future version. Use one of the above \"\n \"to silence this warning.\",\n FutureWarning,\n )\n\n if orient.startswith(\"d\"):\n orient = \"dict\"\n elif orient.startswith(\"l\"):\n orient = \"list\"\n elif orient.startswith(\"sp\"):\n orient = \"split\"\n elif orient.startswith(\"s\"):\n orient = \"series\"\n elif orient.startswith(\"r\"):\n orient = \"records\"\n elif orient.startswith(\"i\"):\n orient = \"index\"\n\n if orient == \"dict\":\n return into_c((k, v.to_dict(into)) for k, v in self.items())\n\n elif orient == \"list\":\n return into_c((k, v.tolist()) for k, v in self.items())\n\n elif orient == \"split\":\n return into_c(\n (\n (\"index\", self.index.tolist()),\n (\"columns\", self.columns.tolist()),\n (\n \"data\",\n [\n list(map(maybe_box_datetimelike, t))\n for t in self.itertuples(index=False, name=None)\n ],\n ),\n )\n )\n\n elif orient == \"series\":\n return into_c((k, maybe_box_datetimelike(v)) for k, v in self.items())\n\n elif orient == \"records\":\n columns = self.columns.tolist()\n rows = (\n dict(zip(columns, row))\n for row in self.itertuples(index=False, name=None)\n )\n return [\n into_c((k, maybe_box_datetimelike(v)) for k, v in row.items())\n for row in rows\n ]\n\n elif orient == \"index\":\n if not self.index.is_unique:\n raise ValueError(\"DataFrame index must be unique for orient='index'.\")\n return into_c(\n (t[0], dict(zip(self.columns, t[1:])))\n for t in self.itertuples(name=None)\n )\n\n else:\n raise ValueError(f\"orient '{orient}' not understood\")\n\n def to_gbq(\n self,\n destination_table,\n project_id=None,\n chunksize=None,\n reauth=False,\n if_exists=\"fail\",\n auth_local_webserver=False,\n table_schema=None,\n location=None,\n progress_bar=True,\n credentials=None,\n ) -> None:\n \"\"\"\n Write a DataFrame to a Google BigQuery table.\n\n This function requires the `pandas-gbq package\n <https://pandas-gbq.readthedocs.io>`__.\n\n See the `How to authenticate with Google BigQuery\n <https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__\n guide for authentication instructions.\n\n Parameters\n ----------\n destination_table : str\n Name of table to be written, in the form ``dataset.tablename``.\n project_id : str, optional\n Google BigQuery Account project ID. Optional when available from\n the environment.\n chunksize : int, optional\n Number of rows to be inserted in each chunk from the dataframe.\n Set to ``None`` to load the whole dataframe at once.\n reauth : bool, default False\n Force Google BigQuery to re-authenticate the user. This is useful\n if multiple accounts are used.\n if_exists : str, default 'fail'\n Behavior when the destination table exists. Value can be one of:\n\n ``'fail'``\n If table exists raise pandas_gbq.gbq.TableCreationError.\n ``'replace'``\n If table exists, drop it, recreate it, and insert data.\n ``'append'``\n If table exists, insert data. Create if does not exist.\n auth_local_webserver : bool, default False\n Use the `local webserver flow`_ instead of the `console flow`_\n when getting user credentials.\n\n .. _local webserver flow:\n https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server\n .. _console flow:\n https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console\n\n *New in version 0.2.0 of pandas-gbq*.\n table_schema : list of dicts, optional\n List of BigQuery table fields to which according DataFrame\n columns conform to, e.g. ``[{'name': 'col1', 'type':\n 'STRING'},...]``. If schema is not provided, it will be\n generated according to dtypes of DataFrame columns. See\n BigQuery API documentation on available names of a field.\n\n *New in version 0.3.1 of pandas-gbq*.\n location : str, optional\n Location where the load job should run. See the `BigQuery locations\n documentation\n <https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a\n list of available locations. The location must match that of the\n target dataset.\n\n *New in version 0.5.0 of pandas-gbq*.\n progress_bar : bool, default True\n Use the library `tqdm` to show the progress bar for the upload,\n chunk by chunk.\n\n *New in version 0.5.0 of pandas-gbq*.\n credentials : google.auth.credentials.Credentials, optional\n Credentials for accessing Google APIs. Use this parameter to\n override default credentials, such as to use Compute Engine\n :class:`google.auth.compute_engine.Credentials` or Service\n Account :class:`google.oauth2.service_account.Credentials`\n directly.\n\n *New in version 0.8.0 of pandas-gbq*.\n\n .. versionadded:: 0.24.0\n\n See Also\n --------\n pandas_gbq.to_gbq : This function in the pandas-gbq library.\n read_gbq : Read a DataFrame from Google BigQuery.\n \"\"\"\n from pandas.io import gbq\n\n gbq.to_gbq(\n self,\n destination_table,\n project_id=project_id,\n chunksize=chunksize,\n reauth=reauth,\n if_exists=if_exists,\n auth_local_webserver=auth_local_webserver,\n table_schema=table_schema,\n location=location,\n progress_bar=progress_bar,\n credentials=credentials,\n )\n\n @classmethod\n def from_records(\n cls,\n data,\n index=None,\n exclude=None,\n columns=None,\n coerce_float=False,\n nrows=None,\n ) -> DataFrame:\n \"\"\"\n Convert structured or record ndarray to DataFrame.\n\n Creates a DataFrame object from a structured ndarray, sequence of\n tuples or dicts, or DataFrame.\n\n Parameters\n ----------\n data : structured ndarray, sequence of tuples or dicts, or DataFrame\n Structured input data.\n index : str, list of fields, array-like\n Field of array to use as the index, alternately a specific set of\n input labels to use.\n exclude : sequence, default None\n Columns or fields to exclude.\n columns : sequence, default None\n Column names to use. If the passed data do not have names\n associated with them, this argument provides names for the\n columns. Otherwise this argument indicates the order of the columns\n in the result (any names not found in the data will become all-NA\n columns).\n coerce_float : bool, default False\n Attempt to convert values of non-string, non-numeric objects (like\n decimal.Decimal) to floating point, useful for SQL result sets.\n nrows : int, default None\n Number of rows to read if data is an iterator.\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n DataFrame.from_dict : DataFrame from dict of array-like or dicts.\n DataFrame : DataFrame object creation using constructor.\n\n Examples\n --------\n Data can be provided as a structured ndarray:\n\n >>> data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')],\n ... dtype=[('col_1', 'i4'), ('col_2', 'U1')])\n >>> pd.DataFrame.from_records(data)\n col_1 col_2\n 0 3 a\n 1 2 b\n 2 1 c\n 3 0 d\n\n Data can be provided as a list of dicts:\n\n >>> data = [{'col_1': 3, 'col_2': 'a'},\n ... {'col_1': 2, 'col_2': 'b'},\n ... {'col_1': 1, 'col_2': 'c'},\n ... {'col_1': 0, 'col_2': 'd'}]\n >>> pd.DataFrame.from_records(data)\n col_1 col_2\n 0 3 a\n 1 2 b\n 2 1 c\n 3 0 d\n\n Data can be provided as a list of tuples with corresponding columns:\n\n >>> data = [(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')]\n >>> pd.DataFrame.from_records(data, columns=['col_1', 'col_2'])\n col_1 col_2\n 0 3 a\n 1 2 b\n 2 1 c\n 3 0 d\n \"\"\"\n # Make a copy of the input columns so we can modify it\n if columns is not None:\n columns = ensure_index(columns)\n\n if is_iterator(data):\n if nrows == 0:\n return cls()\n\n try:\n first_row = next(data)\n except StopIteration:\n return cls(index=index, columns=columns)\n\n dtype = None\n if hasattr(first_row, \"dtype\") and first_row.dtype.names:\n dtype = first_row.dtype\n\n values = [first_row]\n\n if nrows is None:\n values += data\n else:\n values.extend(itertools.islice(data, nrows - 1))\n\n if dtype is not None:\n data = np.array(values, dtype=dtype)\n else:\n data = values\n\n if isinstance(data, dict):\n if columns is None:\n columns = arr_columns = ensure_index(sorted(data))\n arrays = [data[k] for k in columns]\n else:\n arrays = []\n arr_columns_list = []\n for k, v in data.items():\n if k in columns:\n arr_columns_list.append(k)\n arrays.append(v)\n\n arrays, arr_columns = reorder_arrays(arrays, arr_columns_list, columns)\n\n elif isinstance(data, (np.ndarray, DataFrame)):\n arrays, columns = to_arrays(data, columns)\n if columns is not None:\n columns = ensure_index(columns)\n arr_columns = columns\n else:\n arrays, arr_columns = to_arrays(data, columns, coerce_float=coerce_float)\n\n arr_columns = ensure_index(arr_columns)\n if columns is not None:\n columns = ensure_index(columns)\n else:\n columns = arr_columns\n\n if exclude is None:\n exclude = set()\n else:\n exclude = set(exclude)\n\n result_index = None\n if index is not None:\n if isinstance(index, str) or not hasattr(index, \"__iter__\"):\n i = columns.get_loc(index)\n exclude.add(index)\n if len(arrays) > 0:\n result_index = Index(arrays[i], name=index)\n else:\n result_index = Index([], name=index)\n else:\n try:\n index_data = [arrays[arr_columns.get_loc(field)] for field in index]\n except (KeyError, TypeError):\n # raised by get_loc, see GH#29258\n result_index = index\n else:\n result_index = ensure_index_from_sequences(index_data, names=index)\n exclude.update(index)\n\n if any(exclude):\n arr_exclude = [x for x in exclude if x in arr_columns]\n to_remove = [arr_columns.get_loc(col) for col in arr_exclude]\n arrays = [v for i, v in enumerate(arrays) if i not in to_remove]\n\n arr_columns = arr_columns.drop(arr_exclude)\n columns = columns.drop(exclude)\n\n mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns)\n\n return cls(mgr)\n\n def to_records(\n self, index=True, column_dtypes=None, index_dtypes=None\n ) -> np.recarray:\n \"\"\"\n Convert DataFrame to a NumPy record array.\n\n Index will be included as the first field of the record array if\n requested.\n\n Parameters\n ----------\n index : bool, default True\n Include index in resulting record array, stored in 'index'\n field or using the index label, if set.\n column_dtypes : str, type, dict, default None\n .. versionadded:: 0.24.0\n\n If a string or type, the data type to store all columns. If\n a dictionary, a mapping of column names and indices (zero-indexed)\n to specific data types.\n index_dtypes : str, type, dict, default None\n .. versionadded:: 0.24.0\n\n If a string or type, the data type to store all index levels. If\n a dictionary, a mapping of index level names and indices\n (zero-indexed) to specific data types.\n\n This mapping is applied only if `index=True`.\n\n Returns\n -------\n numpy.recarray\n NumPy ndarray with the DataFrame labels as fields and each row\n of the DataFrame as entries.\n\n See Also\n --------\n DataFrame.from_records: Convert structured or record ndarray\n to DataFrame.\n numpy.recarray: An ndarray that allows field access using\n attributes, analogous to typed columns in a\n spreadsheet.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2], 'B': [0.5, 0.75]},\n ... index=['a', 'b'])\n >>> df\n A B\n a 1 0.50\n b 2 0.75\n >>> df.to_records()\n rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],\n dtype=[('index', 'O'), ('A', '<i8'), ('B', '<f8')])\n\n If the DataFrame index has no label then the recarray field name\n is set to 'index'. If the index has a label then this is used as the\n field name:\n\n >>> df.index = df.index.rename(\"I\")\n >>> df.to_records()\n rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],\n dtype=[('I', 'O'), ('A', '<i8'), ('B', '<f8')])\n\n The index can be excluded from the record array:\n\n >>> df.to_records(index=False)\n rec.array([(1, 0.5 ), (2, 0.75)],\n dtype=[('A', '<i8'), ('B', '<f8')])\n\n Data types can be specified for the columns:\n\n >>> df.to_records(column_dtypes={\"A\": \"int32\"})\n rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],\n dtype=[('I', 'O'), ('A', '<i4'), ('B', '<f8')])\n\n As well as for the index:\n\n >>> df.to_records(index_dtypes=\"<S2\")\n rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],\n dtype=[('I', 'S2'), ('A', '<i8'), ('B', '<f8')])\n\n >>> index_dtypes = f\"<S{df.index.str.len().max()}\"\n >>> df.to_records(index_dtypes=index_dtypes)\n rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],\n dtype=[('I', 'S1'), ('A', '<i8'), ('B', '<f8')])\n \"\"\"\n if index:\n if isinstance(self.index, MultiIndex):\n # array of tuples to numpy cols. copy copy copy\n ix_vals = list(map(np.array, zip(*self.index._values)))\n else:\n ix_vals = [self.index.values]\n\n arrays = ix_vals + [\n np.asarray(self.iloc[:, i]) for i in range(len(self.columns))\n ]\n\n count = 0\n index_names = list(self.index.names)\n\n if isinstance(self.index, MultiIndex):\n for i, n in enumerate(index_names):\n if n is None:\n index_names[i] = f\"level_{count}\"\n count += 1\n elif index_names[0] is None:\n index_names = [\"index\"]\n\n names = [str(name) for name in itertools.chain(index_names, self.columns)]\n else:\n arrays = [np.asarray(self.iloc[:, i]) for i in range(len(self.columns))]\n names = [str(c) for c in self.columns]\n index_names = []\n\n index_len = len(index_names)\n formats = []\n\n for i, v in enumerate(arrays):\n index = i\n\n # When the names and arrays are collected, we\n # first collect those in the DataFrame's index,\n # followed by those in its columns.\n #\n # Thus, the total length of the array is:\n # len(index_names) + len(DataFrame.columns).\n #\n # This check allows us to see whether we are\n # handling a name / array in the index or column.\n if index < index_len:\n dtype_mapping = index_dtypes\n name = index_names[index]\n else:\n index -= index_len\n dtype_mapping = column_dtypes\n name = self.columns[index]\n\n # We have a dictionary, so we get the data type\n # associated with the index or column (which can\n # be denoted by its name in the DataFrame or its\n # position in DataFrame's array of indices or\n # columns, whichever is applicable.\n if is_dict_like(dtype_mapping):\n if name in dtype_mapping:\n dtype_mapping = dtype_mapping[name]\n elif index in dtype_mapping:\n dtype_mapping = dtype_mapping[index]\n else:\n dtype_mapping = None\n\n # If no mapping can be found, use the array's\n # dtype attribute for formatting.\n #\n # A valid dtype must either be a type or\n # string naming a type.\n if dtype_mapping is None:\n formats.append(v.dtype)\n elif isinstance(dtype_mapping, (type, np.dtype, str)):\n formats.append(dtype_mapping)\n else:\n element = \"row\" if i < index_len else \"column\"\n msg = f\"Invalid dtype {dtype_mapping} specified for {element} {name}\"\n raise ValueError(msg)\n\n return np.rec.fromarrays(arrays, dtype={\"names\": names, \"formats\": formats})\n\n @classmethod\n def _from_arrays(\n cls,\n arrays,\n columns,\n index,\n dtype: Optional[Dtype] = None,\n verify_integrity: bool = True,\n ) -> DataFrame:\n \"\"\"\n Create DataFrame from a list of arrays corresponding to the columns.\n\n Parameters\n ----------\n arrays : list-like of arrays\n Each array in the list corresponds to one column, in order.\n columns : list-like, Index\n The column names for the resulting DataFrame.\n index : list-like, Index\n The rows labels for the resulting DataFrame.\n dtype : dtype, optional\n Optional dtype to enforce for all arrays.\n verify_integrity : bool, default True\n Validate and homogenize all input. If set to False, it is assumed\n that all elements of `arrays` are actual arrays how they will be\n stored in a block (numpy ndarray or ExtensionArray), have the same\n length as and are aligned with the index, and that `columns` and\n `index` are ensured to be an Index object.\n\n Returns\n -------\n DataFrame\n \"\"\"\n if dtype is not None:\n dtype = pandas_dtype(dtype)\n\n mgr = arrays_to_mgr(\n arrays,\n columns,\n index,\n columns,\n dtype=dtype,\n verify_integrity=verify_integrity,\n )\n return cls(mgr)\n\n @doc(storage_options=generic._shared_docs[\"storage_options\"])\n @deprecate_kwarg(old_arg_name=\"fname\", new_arg_name=\"path\")\n def to_stata(\n self,\n path: FilePathOrBuffer,\n convert_dates: Optional[Dict[Label, str]] = None,\n write_index: bool = True,\n byteorder: Optional[str] = None,\n time_stamp: Optional[datetime.datetime] = None,\n data_label: Optional[str] = None,\n variable_labels: Optional[Dict[Label, str]] = None,\n version: Optional[int] = 114,\n convert_strl: Optional[Sequence[Label]] = None,\n compression: CompressionOptions = \"infer\",\n storage_options: StorageOptions = None,\n ) -> None:\n \"\"\"\n Export DataFrame object to Stata dta format.\n\n Writes the DataFrame to a Stata dataset file.\n \"dta\" files contain a Stata dataset.\n\n Parameters\n ----------\n path : str, buffer or path object\n String, path object (pathlib.Path or py._path.local.LocalPath) or\n object implementing a binary write() function. If using a buffer\n then the buffer will not be automatically closed after the file\n data has been written.\n\n .. versionchanged:: 1.0.0\n\n Previously this was \"fname\"\n\n convert_dates : dict\n Dictionary mapping columns containing datetime types to stata\n internal format to use when writing the dates. Options are 'tc',\n 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer\n or a name. Datetime columns that do not have a conversion type\n specified will be converted to 'tc'. Raises NotImplementedError if\n a datetime column has timezone information.\n write_index : bool\n Write the index to Stata dataset.\n byteorder : str\n Can be \">\", \"<\", \"little\", or \"big\". default is `sys.byteorder`.\n time_stamp : datetime\n A datetime to use as file creation date. Default is the current\n time.\n data_label : str, optional\n A label for the data set. Must be 80 characters or smaller.\n variable_labels : dict\n Dictionary containing columns as keys and variable labels as\n values. Each label must be 80 characters or smaller.\n version : {{114, 117, 118, 119, None}}, default 114\n Version to use in the output dta file. Set to None to let pandas\n decide between 118 or 119 formats depending on the number of\n columns in the frame. Version 114 can be read by Stata 10 and\n later. Version 117 can be read by Stata 13 or later. Version 118\n is supported in Stata 14 and later. Version 119 is supported in\n Stata 15 and later. Version 114 limits string variables to 244\n characters or fewer while versions 117 and later allow strings\n with lengths up to 2,000,000 characters. Versions 118 and 119\n support Unicode characters, and version 119 supports more than\n 32,767 variables.\n\n Version 119 should usually only be used when the number of\n variables exceeds the capacity of dta format 118. Exporting\n smaller datasets in format 119 may have unintended consequences,\n and, as of November 2020, Stata SE cannot read version 119 files.\n\n .. versionchanged:: 1.0.0\n\n Added support for formats 118 and 119.\n\n convert_strl : list, optional\n List of column names to convert to string columns to Stata StrL\n format. Only available if version is 117. Storing strings in the\n StrL format can produce smaller dta files if strings have more than\n 8 characters and values are repeated.\n compression : str or dict, default 'infer'\n For on-the-fly compression of the output dta. If string, specifies\n compression mode. If dict, value at key 'method' specifies\n compression mode. Compression mode must be one of {{'infer', 'gzip',\n 'bz2', 'zip', 'xz', None}}. If compression mode is 'infer' and\n `fname` is path-like, then detect compression from the following\n extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no\n compression). If dict and compression mode is one of {{'zip',\n 'gzip', 'bz2'}}, or inferred as one of the above, other entries\n passed as additional compression options.\n\n .. versionadded:: 1.1.0\n\n {storage_options}\n\n .. versionadded:: 1.2.0\n\n Raises\n ------\n NotImplementedError\n * If datetimes contain timezone information\n * Column dtype is not representable in Stata\n ValueError\n * Columns listed in convert_dates are neither datetime64[ns]\n or datetime.datetime\n * Column listed in convert_dates is not in DataFrame\n * Categorical label contains more than 32,000 characters\n\n See Also\n --------\n read_stata : Import Stata data files.\n io.stata.StataWriter : Low-level writer for Stata data files.\n io.stata.StataWriter117 : Low-level writer for version 117 files.\n\n Examples\n --------\n >>> df = pd.DataFrame({{'animal': ['falcon', 'parrot', 'falcon',\n ... 'parrot'],\n ... 'speed': [350, 18, 361, 15]}})\n >>> df.to_stata('animals.dta') # doctest: +SKIP\n \"\"\"\n if version not in (114, 117, 118, 119, None):\n raise ValueError(\"Only formats 114, 117, 118 and 119 are supported.\")\n if version == 114:\n if convert_strl is not None:\n raise ValueError(\"strl is not supported in format 114\")\n from pandas.io.stata import StataWriter as statawriter\n elif version == 117:\n # mypy: Name 'statawriter' already defined (possibly by an import)\n from pandas.io.stata import ( # type: ignore[no-redef]\n StataWriter117 as statawriter,\n )\n else: # versions 118 and 119\n # mypy: Name 'statawriter' already defined (possibly by an import)\n from pandas.io.stata import ( # type: ignore[no-redef]\n StataWriterUTF8 as statawriter,\n )\n\n kwargs: Dict[str, Any] = {}\n if version is None or version >= 117:\n # strl conversion is only supported >= 117\n kwargs[\"convert_strl\"] = convert_strl\n if version is None or version >= 118:\n # Specifying the version is only supported for UTF8 (118 or 119)\n kwargs[\"version\"] = version\n\n # mypy: Too many arguments for \"StataWriter\"\n writer = statawriter( # type: ignore[call-arg]\n path,\n self,\n convert_dates=convert_dates,\n byteorder=byteorder,\n time_stamp=time_stamp,\n data_label=data_label,\n write_index=write_index,\n variable_labels=variable_labels,\n compression=compression,\n storage_options=storage_options,\n **kwargs,\n )\n writer.write_file()\n\n @deprecate_kwarg(old_arg_name=\"fname\", new_arg_name=\"path\")\n def to_feather(self, path: FilePathOrBuffer[AnyStr], **kwargs) -> None:\n \"\"\"\n Write a DataFrame to the binary Feather format.\n\n Parameters\n ----------\n path : str or file-like object\n If a string, it will be used as Root Directory path.\n **kwargs :\n Additional keywords passed to :func:`pyarrow.feather.write_feather`.\n Starting with pyarrow 0.17, this includes the `compression`,\n `compression_level`, `chunksize` and `version` keywords.\n\n .. versionadded:: 1.1.0\n \"\"\"\n from pandas.io.feather_format import to_feather\n\n to_feather(self, path, **kwargs)\n\n @doc(\n Series.to_markdown,\n klass=_shared_doc_kwargs[\"klass\"],\n storage_options=_shared_docs[\"storage_options\"],\n examples=\"\"\"Examples\n --------\n >>> df = pd.DataFrame(\n ... data={\"animal_1\": [\"elk\", \"pig\"], \"animal_2\": [\"dog\", \"quetzal\"]}\n ... )\n >>> print(df.to_markdown())\n | | animal_1 | animal_2 |\n |---:|:-----------|:-----------|\n | 0 | elk | dog |\n | 1 | pig | quetzal |\n\n Output markdown with a tabulate option.\n\n >>> print(df.to_markdown(tablefmt=\"grid\"))\n +----+------------+------------+\n | | animal_1 | animal_2 |\n +====+============+============+\n | 0 | elk | dog |\n +----+------------+------------+\n | 1 | pig | quetzal |\n +----+------------+------------+\n \"\"\",\n )\n def to_markdown(\n self,\n buf: Optional[Union[IO[str], str]] = None,\n mode: str = \"wt\",\n index: bool = True,\n storage_options: StorageOptions = None,\n **kwargs,\n ) -> Optional[str]:\n if \"showindex\" in kwargs:\n warnings.warn(\n \"'showindex' is deprecated. Only 'index' will be used \"\n \"in a future version. Use 'index' to silence this warning.\",\n FutureWarning,\n stacklevel=2,\n )\n\n kwargs.setdefault(\"headers\", \"keys\")\n kwargs.setdefault(\"tablefmt\", \"pipe\")\n kwargs.setdefault(\"showindex\", index)\n tabulate = import_optional_dependency(\"tabulate\")\n result = tabulate.tabulate(self, **kwargs)\n if buf is None:\n return result\n\n with get_handle(buf, mode, storage_options=storage_options) as handles:\n assert not isinstance(handles.handle, (str, mmap.mmap))\n handles.handle.writelines(result)\n return None\n\n @doc(storage_options=generic._shared_docs[\"storage_options\"])\n @deprecate_kwarg(old_arg_name=\"fname\", new_arg_name=\"path\")\n def to_parquet(\n self,\n path: Optional[FilePathOrBuffer] = None,\n engine: str = \"auto\",\n compression: Optional[str] = \"snappy\",\n index: Optional[bool] = None,\n partition_cols: Optional[List[str]] = None,\n storage_options: StorageOptions = None,\n **kwargs,\n ) -> Optional[bytes]:\n \"\"\"\n Write a DataFrame to the binary parquet format.\n\n This function writes the dataframe as a `parquet file\n <https://parquet.apache.org/>`_. You can choose different parquet\n backends, and have the option of compression. See\n :ref:`the user guide <io.parquet>` for more details.\n\n Parameters\n ----------\n path : str or file-like object, default None\n If a string, it will be used as Root Directory path\n when writing a partitioned dataset. By file-like object,\n we refer to objects with a write() method, such as a file handle\n (e.g. via builtin open function) or io.BytesIO. The engine\n fastparquet does not accept file-like objects. If path is None,\n a bytes object is returned.\n\n .. versionchanged:: 1.2.0\n\n Previously this was \"fname\"\n\n engine : {{'auto', 'pyarrow', 'fastparquet'}}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n compression : {{'snappy', 'gzip', 'brotli', None}}, default 'snappy'\n Name of the compression to use. Use ``None`` for no compression.\n index : bool, default None\n If ``True``, include the dataframe's index(es) in the file output.\n If ``False``, they will not be written to the file.\n If ``None``, similar to ``True`` the dataframe's index(es)\n will be saved. However, instead of being saved as values,\n the RangeIndex will be stored as a range in the metadata so it\n doesn't require much space and is faster. Other indexes will\n be included as columns in the file output.\n\n .. versionadded:: 0.24.0\n\n partition_cols : list, optional, default None\n Column names by which to partition the dataset.\n Columns are partitioned in the order they are given.\n Must be None if path is not a string.\n\n .. versionadded:: 0.24.0\n\n {storage_options}\n\n .. versionadded:: 1.2.0\n\n **kwargs\n Additional arguments passed to the parquet library. See\n :ref:`pandas io <io.parquet>` for more details.\n\n Returns\n -------\n bytes if no path argument is provided else None\n\n See Also\n --------\n read_parquet : Read a parquet file.\n DataFrame.to_csv : Write a csv file.\n DataFrame.to_sql : Write to a sql table.\n DataFrame.to_hdf : Write to hdf.\n\n Notes\n -----\n This function requires either the `fastparquet\n <https://pypi.org/project/fastparquet>`_ or `pyarrow\n <https://arrow.apache.org/docs/python/>`_ library.\n\n Examples\n --------\n >>> df = pd.DataFrame(data={{'col1': [1, 2], 'col2': [3, 4]}})\n >>> df.to_parquet('df.parquet.gzip',\n ... compression='gzip') # doctest: +SKIP\n >>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP\n col1 col2\n 0 1 3\n 1 2 4\n\n If you want to get a buffer to the parquet content you can use a io.BytesIO\n object, as long as you don't use partition_cols, which creates multiple files.\n\n >>> import io\n >>> f = io.BytesIO()\n >>> df.to_parquet(f)\n >>> f.seek(0)\n 0\n >>> content = f.read()\n \"\"\"\n from pandas.io.parquet import to_parquet\n\n return to_parquet(\n self,\n path,\n engine,\n compression=compression,\n index=index,\n partition_cols=partition_cols,\n storage_options=storage_options,\n **kwargs,\n )\n\n @Substitution(\n header_type=\"bool\",\n header=\"Whether to print column labels, default True\",\n col_space_type=\"str or int, list or dict of int or str\",\n col_space=\"The minimum width of each column in CSS length \"\n \"units. An int is assumed to be px units.\\n\\n\"\n \" .. versionadded:: 0.25.0\\n\"\n \" Ability to use str\",\n )\n @Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)\n def to_html(\n self,\n buf=None,\n columns=None,\n col_space=None,\n header=True,\n index=True,\n na_rep=\"NaN\",\n formatters=None,\n float_format=None,\n sparsify=None,\n index_names=True,\n justify=None,\n max_rows=None,\n max_cols=None,\n show_dimensions=False,\n decimal=\".\",\n bold_rows=True,\n classes=None,\n escape=True,\n notebook=False,\n border=None,\n table_id=None,\n render_links=False,\n encoding=None,\n ):\n \"\"\"\n Render a DataFrame as an HTML table.\n %(shared_params)s\n bold_rows : bool, default True\n Make the row labels bold in the output.\n classes : str or list or tuple, default None\n CSS class(es) to apply to the resulting html table.\n escape : bool, default True\n Convert the characters <, >, and & to HTML-safe sequences.\n notebook : {True, False}, default False\n Whether the generated HTML is for IPython Notebook.\n border : int\n A ``border=border`` attribute is included in the opening\n `<table>` tag. Default ``pd.options.display.html.border``.\n encoding : str, default \"utf-8\"\n Set character encoding.\n\n .. versionadded:: 1.0\n\n table_id : str, optional\n A css id is included in the opening `<table>` tag if specified.\n render_links : bool, default False\n Convert URLs to HTML links.\n\n .. versionadded:: 0.24.0\n %(returns)s\n See Also\n --------\n to_string : Convert DataFrame to a string.\n \"\"\"\n if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:\n raise ValueError(\"Invalid value for justify parameter\")\n\n formatter = fmt.DataFrameFormatter(\n self,\n columns=columns,\n col_space=col_space,\n na_rep=na_rep,\n header=header,\n index=index,\n formatters=formatters,\n float_format=float_format,\n bold_rows=bold_rows,\n sparsify=sparsify,\n justify=justify,\n index_names=index_names,\n escape=escape,\n decimal=decimal,\n max_rows=max_rows,\n max_cols=max_cols,\n show_dimensions=show_dimensions,\n )\n # TODO: a generic formatter wld b in DataFrameFormatter\n return fmt.DataFrameRenderer(formatter).to_html(\n buf=buf,\n classes=classes,\n notebook=notebook,\n border=border,\n encoding=encoding,\n table_id=table_id,\n render_links=render_links,\n )\n\n # ----------------------------------------------------------------------\n @Substitution(\n klass=\"DataFrame\",\n type_sub=\" and columns\",\n max_cols_sub=dedent(\n \"\"\"\\\n max_cols : int, optional\n When to switch from the verbose to the truncated output. If the\n DataFrame has more than `max_cols` columns, the truncated output\n is used. By default, the setting in\n ``pandas.options.display.max_info_columns`` is used.\"\"\"\n ),\n show_counts_sub=dedent(\n \"\"\"\\\n show_counts : bool, optional\n Whether to show the non-null counts. By default, this is shown\n only if the DataFrame is smaller than\n ``pandas.options.display.max_info_rows`` and\n ``pandas.options.display.max_info_columns``. A value of True always\n shows the counts, and False never shows the counts.\n null_counts : bool, optional\n .. deprecated:: 1.2.0\n Use show_counts instead.\"\"\"\n ),\n examples_sub=dedent(\n \"\"\"\\\n >>> int_values = [1, 2, 3, 4, 5]\n >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']\n >>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0]\n >>> df = pd.DataFrame({\"int_col\": int_values, \"text_col\": text_values,\n ... \"float_col\": float_values})\n >>> df\n int_col text_col float_col\n 0 1 alpha 0.00\n 1 2 beta 0.25\n 2 3 gamma 0.50\n 3 4 delta 0.75\n 4 5 epsilon 1.00\n\n Prints information of all columns:\n\n >>> df.info(verbose=True)\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 5 entries, 0 to 4\n Data columns (total 3 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 int_col 5 non-null int64\n 1 text_col 5 non-null object\n 2 float_col 5 non-null float64\n dtypes: float64(1), int64(1), object(1)\n memory usage: 248.0+ bytes\n\n Prints a summary of columns count and its dtypes but not per column\n information:\n\n >>> df.info(verbose=False)\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 5 entries, 0 to 4\n Columns: 3 entries, int_col to float_col\n dtypes: float64(1), int64(1), object(1)\n memory usage: 248.0+ bytes\n\n Pipe output of DataFrame.info to buffer instead of sys.stdout, get\n buffer content and writes to a text file:\n\n >>> import io\n >>> buffer = io.StringIO()\n >>> df.info(buf=buffer)\n >>> s = buffer.getvalue()\n >>> with open(\"df_info.txt\", \"w\",\n ... encoding=\"utf-8\") as f: # doctest: +SKIP\n ... f.write(s)\n 260\n\n The `memory_usage` parameter allows deep introspection mode, specially\n useful for big DataFrames and fine-tune memory optimization:\n\n >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6)\n >>> df = pd.DataFrame({\n ... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6),\n ... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6),\n ... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6)\n ... })\n >>> df.info()\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 1000000 entries, 0 to 999999\n Data columns (total 3 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 column_1 1000000 non-null object\n 1 column_2 1000000 non-null object\n 2 column_3 1000000 non-null object\n dtypes: object(3)\n memory usage: 22.9+ MB\n\n >>> df.info(memory_usage='deep')\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 1000000 entries, 0 to 999999\n Data columns (total 3 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 column_1 1000000 non-null object\n 1 column_2 1000000 non-null object\n 2 column_3 1000000 non-null object\n dtypes: object(3)\n memory usage: 165.9 MB\"\"\"\n ),\n see_also_sub=dedent(\n \"\"\"\\\n DataFrame.describe: Generate descriptive statistics of DataFrame\n columns.\n DataFrame.memory_usage: Memory usage of DataFrame columns.\"\"\"\n ),\n version_added_sub=\"\",\n )\n @doc(BaseInfo.render)\n def info(\n self,\n verbose: Optional[bool] = None,\n buf: Optional[IO[str]] = None,\n max_cols: Optional[int] = None,\n memory_usage: Optional[Union[bool, str]] = None,\n show_counts: Optional[bool] = None,\n null_counts: Optional[bool] = None,\n ) -> None:\n if null_counts is not None:\n if show_counts is not None:\n raise ValueError(\"null_counts used with show_counts. Use show_counts.\")\n warnings.warn(\n \"null_counts is deprecated. Use show_counts instead\",\n FutureWarning,\n stacklevel=2,\n )\n show_counts = null_counts\n info = DataFrameInfo(\n data=self,\n memory_usage=memory_usage,\n )\n info.render(\n buf=buf,\n max_cols=max_cols,\n verbose=verbose,\n show_counts=show_counts,\n )\n\n def memory_usage(self, index=True, deep=False) -> Series:\n \"\"\"\n Return the memory usage of each column in bytes.\n\n The memory usage can optionally include the contribution of\n the index and elements of `object` dtype.\n\n This value is displayed in `DataFrame.info` by default. This can be\n suppressed by setting ``pandas.options.display.memory_usage`` to False.\n\n Parameters\n ----------\n index : bool, default True\n Specifies whether to include the memory usage of the DataFrame's\n index in returned Series. If ``index=True``, the memory usage of\n the index is the first item in the output.\n deep : bool, default False\n If True, introspect the data deeply by interrogating\n `object` dtypes for system-level memory consumption, and include\n it in the returned values.\n\n Returns\n -------\n Series\n A Series whose index is the original column names and whose values\n is the memory usage of each column in bytes.\n\n See Also\n --------\n numpy.ndarray.nbytes : Total bytes consumed by the elements of an\n ndarray.\n Series.memory_usage : Bytes consumed by a Series.\n Categorical : Memory-efficient array for string values with\n many repeated values.\n DataFrame.info : Concise summary of a DataFrame.\n\n Examples\n --------\n >>> dtypes = ['int64', 'float64', 'complex128', 'object', 'bool']\n >>> data = dict([(t, np.ones(shape=5000, dtype=int).astype(t))\n ... for t in dtypes])\n >>> df = pd.DataFrame(data)\n >>> df.head()\n int64 float64 complex128 object bool\n 0 1 1.0 1.0+0.0j 1 True\n 1 1 1.0 1.0+0.0j 1 True\n 2 1 1.0 1.0+0.0j 1 True\n 3 1 1.0 1.0+0.0j 1 True\n 4 1 1.0 1.0+0.0j 1 True\n\n >>> df.memory_usage()\n Index 128\n int64 40000\n float64 40000\n complex128 80000\n object 40000\n bool 5000\n dtype: int64\n\n >>> df.memory_usage(index=False)\n int64 40000\n float64 40000\n complex128 80000\n object 40000\n bool 5000\n dtype: int64\n\n The memory footprint of `object` dtype columns is ignored by default:\n\n >>> df.memory_usage(deep=True)\n Index 128\n int64 40000\n float64 40000\n complex128 80000\n object 180000\n bool 5000\n dtype: int64\n\n Use a Categorical for efficient storage of an object-dtype column with\n many repeated values.\n\n >>> df['object'].astype('category').memory_usage(deep=True)\n 5244\n \"\"\"\n result = self._constructor_sliced(\n [c.memory_usage(index=False, deep=deep) for col, c in self.items()],\n index=self.columns,\n )\n if index:\n result = self._constructor_sliced(\n self.index.memory_usage(deep=deep), index=[\"Index\"]\n ).append(result)\n return result\n\n def transpose(self, *args, copy: bool = False) -> DataFrame:\n \"\"\"\n Transpose index and columns.\n\n Reflect the DataFrame over its main diagonal by writing rows as columns\n and vice-versa. The property :attr:`.T` is an accessor to the method\n :meth:`transpose`.\n\n Parameters\n ----------\n *args : tuple, optional\n Accepted for compatibility with NumPy.\n copy : bool, default False\n Whether to copy the data after transposing, even for DataFrames\n with a single dtype.\n\n Note that a copy is always required for mixed dtype DataFrames,\n or for DataFrames with any extension types.\n\n Returns\n -------\n DataFrame\n The transposed DataFrame.\n\n See Also\n --------\n numpy.transpose : Permute the dimensions of a given array.\n\n Notes\n -----\n Transposing a DataFrame with mixed dtypes will result in a homogeneous\n DataFrame with the `object` dtype. In such a case, a copy of the data\n is always made.\n\n Examples\n --------\n **Square DataFrame with homogeneous dtype**\n\n >>> d1 = {'col1': [1, 2], 'col2': [3, 4]}\n >>> df1 = pd.DataFrame(data=d1)\n >>> df1\n col1 col2\n 0 1 3\n 1 2 4\n\n >>> df1_transposed = df1.T # or df1.transpose()\n >>> df1_transposed\n 0 1\n col1 1 2\n col2 3 4\n\n When the dtype is homogeneous in the original DataFrame, we get a\n transposed DataFrame with the same dtype:\n\n >>> df1.dtypes\n col1 int64\n col2 int64\n dtype: object\n >>> df1_transposed.dtypes\n 0 int64\n 1 int64\n dtype: object\n\n **Non-square DataFrame with mixed dtypes**\n\n >>> d2 = {'name': ['Alice', 'Bob'],\n ... 'score': [9.5, 8],\n ... 'employed': [False, True],\n ... 'kids': [0, 0]}\n >>> df2 = pd.DataFrame(data=d2)\n >>> df2\n name score employed kids\n 0 Alice 9.5 False 0\n 1 Bob 8.0 True 0\n\n >>> df2_transposed = df2.T # or df2.transpose()\n >>> df2_transposed\n 0 1\n name Alice Bob\n score 9.5 8.0\n employed False True\n kids 0 0\n\n When the DataFrame has mixed dtypes, we get a transposed DataFrame with\n the `object` dtype:\n\n >>> df2.dtypes\n name object\n score float64\n employed bool\n kids int64\n dtype: object\n >>> df2_transposed.dtypes\n 0 object\n 1 object\n dtype: object\n \"\"\"\n nv.validate_transpose(args, {})\n # construct the args\n\n dtypes = list(self.dtypes)\n if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]):\n # We have EAs with the same dtype. We can preserve that dtype in transpose.\n dtype = dtypes[0]\n arr_type = dtype.construct_array_type()\n values = self.values\n\n new_values = [arr_type._from_sequence(row, dtype=dtype) for row in values]\n result = self._constructor(\n dict(zip(self.index, new_values)), index=self.columns\n )\n\n else:\n new_values = self.values.T\n if copy:\n new_values = new_values.copy()\n result = self._constructor(\n new_values, index=self.columns, columns=self.index\n )\n\n return result.__finalize__(self, method=\"transpose\")\n\n @property\n def T(self) -> DataFrame:\n return self.transpose()\n\n # ----------------------------------------------------------------------\n # Indexing Methods\n\n def _ixs(self, i: int, axis: int = 0):\n \"\"\"\n Parameters\n ----------\n i : int\n axis : int\n\n Notes\n -----\n If slice passed, the resulting data will be a view.\n \"\"\"\n # irow\n if axis == 0:\n new_values = self._mgr.fast_xs(i)\n\n # if we are a copy, mark as such\n copy = isinstance(new_values, np.ndarray) and new_values.base is None\n result = self._constructor_sliced(\n new_values,\n index=self.columns,\n name=self.index[i],\n dtype=new_values.dtype,\n )\n result._set_is_copy(self, copy=copy)\n return result\n\n # icol\n else:\n label = self.columns[i]\n\n values = self._mgr.iget(i)\n result = self._box_col_values(values, i)\n\n # this is a cached value, mark it so\n result._set_as_cached(label, self)\n\n return result\n\n def _get_column_array(self, i: int) -> ArrayLike:\n \"\"\"\n Get the values of the i'th column (ndarray or ExtensionArray, as stored\n in the Block)\n \"\"\"\n return self._mgr.iget_values(i)\n\n def _iter_column_arrays(self) -> Iterator[ArrayLike]:\n \"\"\"\n Iterate over the arrays of all columns in order.\n This returns the values as stored in the Block (ndarray or ExtensionArray).\n \"\"\"\n for i in range(len(self.columns)):\n yield self._get_column_array(i)\n\n def __getitem__(self, key):\n key = lib.item_from_zerodim(key)\n key = com.apply_if_callable(key, self)\n\n if is_hashable(key):\n # shortcut if the key is in columns\n if self.columns.is_unique and key in self.columns:\n if isinstance(self.columns, MultiIndex):\n return self._getitem_multilevel(key)\n return self._get_item_cache(key)\n\n # Do we have a slicer (on rows)?\n indexer = convert_to_index_sliceable(self, key)\n if indexer is not None:\n if isinstance(indexer, np.ndarray):\n indexer = lib.maybe_indices_to_slice(\n indexer.astype(np.intp, copy=False), len(self)\n )\n # either we have a slice or we have a string that can be converted\n # to a slice for partial-string date indexing\n return self._slice(indexer, axis=0)\n\n # Do we have a (boolean) DataFrame?\n if isinstance(key, DataFrame):\n return self.where(key)\n\n # Do we have a (boolean) 1d indexer?\n if com.is_bool_indexer(key):\n return self._getitem_bool_array(key)\n\n # We are left with two options: a single key, and a collection of keys,\n # We interpret tuples as collections only for non-MultiIndex\n is_single_key = isinstance(key, tuple) or not is_list_like(key)\n\n if is_single_key:\n if self.columns.nlevels > 1:\n return self._getitem_multilevel(key)\n indexer = self.columns.get_loc(key)\n if is_integer(indexer):\n indexer = [indexer]\n else:\n if is_iterator(key):\n key = list(key)\n indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]\n\n # take() does not accept boolean indexers\n if getattr(indexer, \"dtype\", None) == bool:\n indexer = np.where(indexer)[0]\n\n data = self._take_with_is_copy(indexer, axis=1)\n\n if is_single_key:\n # What does looking for a single key in a non-unique index return?\n # The behavior is inconsistent. It returns a Series, except when\n # - the key itself is repeated (test on data.shape, #9519), or\n # - we have a MultiIndex on columns (test on self.columns, #21309)\n if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):\n # GH#26490 using data[key] can cause RecursionError\n data = data._get_item_cache(key)\n\n return data\n\n def _getitem_bool_array(self, key):\n # also raises Exception if object array with NA values\n # warning here just in case -- previously __setitem__ was\n # reindexing but __getitem__ was not; it seems more reasonable to\n # go with the __setitem__ behavior since that is more consistent\n # with all other indexing behavior\n if isinstance(key, Series) and not key.index.equals(self.index):\n warnings.warn(\n \"Boolean Series key will be reindexed to match DataFrame index.\",\n UserWarning,\n stacklevel=3,\n )\n elif len(key) != len(self.index):\n raise ValueError(\n f\"Item wrong length {len(key)} instead of {len(self.index)}.\"\n )\n\n # check_bool_indexer will throw exception if Series key cannot\n # be reindexed to match DataFrame rows\n key = check_bool_indexer(self.index, key)\n indexer = key.nonzero()[0]\n return self._take_with_is_copy(indexer, axis=0)\n\n def _getitem_multilevel(self, key):\n # self.columns is a MultiIndex\n loc = self.columns.get_loc(key)\n if isinstance(loc, (slice, np.ndarray)):\n new_columns = self.columns[loc]\n result_columns = maybe_droplevels(new_columns, key)\n if self._is_mixed_type:\n result = self.reindex(columns=new_columns)\n result.columns = result_columns\n else:\n new_values = self.values[:, loc]\n result = self._constructor(\n new_values, index=self.index, columns=result_columns\n )\n result = result.__finalize__(self)\n\n # If there is only one column being returned, and its name is\n # either an empty string, or a tuple with an empty string as its\n # first element, then treat the empty string as a placeholder\n # and return the column as if the user had provided that empty\n # string in the key. If the result is a Series, exclude the\n # implied empty string from its name.\n if len(result.columns) == 1:\n top = result.columns[0]\n if isinstance(top, tuple):\n top = top[0]\n if top == \"\":\n result = result[\"\"]\n if isinstance(result, Series):\n result = self._constructor_sliced(\n result, index=self.index, name=key\n )\n\n result._set_is_copy(self)\n return result\n else:\n # loc is neither a slice nor ndarray, so must be an int\n return self._ixs(loc, axis=1)\n\n def _get_value(self, index, col, takeable: bool = False):\n \"\"\"\n Quickly retrieve single value at passed column and index.\n\n Parameters\n ----------\n index : row label\n col : column label\n takeable : interpret the index/col as indexers, default False\n\n Returns\n -------\n scalar\n \"\"\"\n if takeable:\n series = self._ixs(col, axis=1)\n return series._values[index]\n\n series = self._get_item_cache(col)\n engine = self.index._engine\n\n try:\n loc = engine.get_loc(index)\n return series._values[loc]\n except KeyError:\n # GH 20629\n if self.index.nlevels > 1:\n # partial indexing forbidden\n raise\n\n # we cannot handle direct indexing\n # use positional\n col = self.columns.get_loc(col)\n index = self.index.get_loc(index)\n return self._get_value(index, col, takeable=True)\n\n def __setitem__(self, key, value):\n key = com.apply_if_callable(key, self)\n\n # see if we can slice the rows\n indexer = convert_to_index_sliceable(self, key)\n if indexer is not None:\n # either we have a slice or we have a string that can be converted\n # to a slice for partial-string date indexing\n return self._setitem_slice(indexer, value)\n\n if isinstance(key, DataFrame) or getattr(key, \"ndim\", None) == 2:\n self._setitem_frame(key, value)\n elif isinstance(key, (Series, np.ndarray, list, Index)):\n self._setitem_array(key, value)\n else:\n # set column\n self._set_item(key, value)\n\n def _setitem_slice(self, key: slice, value):\n # NB: we can't just use self.loc[key] = value because that\n # operates on labels and we need to operate positional for\n # backwards-compat, xref GH#31469\n self._check_setitem_copy()\n self.iloc._setitem_with_indexer(key, value)\n\n def _setitem_array(self, key, value):\n # also raises Exception if object array with NA values\n if com.is_bool_indexer(key):\n if len(key) != len(self.index):\n raise ValueError(\n f\"Item wrong length {len(key)} instead of {len(self.index)}!\"\n )\n key = check_bool_indexer(self.index, key)\n indexer = key.nonzero()[0]\n self._check_setitem_copy()\n self.iloc._setitem_with_indexer(indexer, value)\n else:\n if isinstance(value, DataFrame):\n if len(value.columns) != len(key):\n raise ValueError(\"Columns must be same length as key\")\n for k1, k2 in zip(key, value.columns):\n self[k1] = value[k2]\n else:\n self.loc._ensure_listlike_indexer(key, axis=1, value=value)\n indexer = self.loc._get_listlike_indexer(\n key, axis=1, raise_missing=False\n )[1]\n self._check_setitem_copy()\n self.iloc._setitem_with_indexer((slice(None), indexer), value)\n\n def _setitem_frame(self, key, value):\n # support boolean setting with DataFrame input, e.g.\n # df[df > df2] = 0\n if isinstance(key, np.ndarray):\n if key.shape != self.shape:\n raise ValueError(\"Array conditional must be same shape as self\")\n key = self._constructor(key, **self._construct_axes_dict())\n\n if key.size and not is_bool_dtype(key.values):\n raise TypeError(\n \"Must pass DataFrame or 2-d ndarray with boolean values only\"\n )\n\n self._check_inplace_setting(value)\n self._check_setitem_copy()\n self._where(-key, value, inplace=True)\n\n def _iset_item(self, loc: int, value):\n self._ensure_valid_index(value)\n\n # technically _sanitize_column expects a label, not a position,\n # but the behavior is the same as long as we pass broadcast=False\n value = self._sanitize_column(loc, value, broadcast=False)\n NDFrame._iset_item(self, loc, value)\n\n # check if we are modifying a copy\n # try to set first as we want an invalid\n # value exception to occur first\n if len(self):\n self._check_setitem_copy()\n\n def _set_item(self, key, value):\n \"\"\"\n Add series to DataFrame in specified column.\n\n If series is a numpy-array (not a Series/TimeSeries), it must be the\n same length as the DataFrames index or an error will be thrown.\n\n Series/TimeSeries will be conformed to the DataFrames index to\n ensure homogeneity.\n \"\"\"\n self._ensure_valid_index(value)\n value = self._sanitize_column(key, value)\n NDFrame._set_item(self, key, value)\n\n # check if we are modifying a copy\n # try to set first as we want an invalid\n # value exception to occur first\n if len(self):\n self._check_setitem_copy()\n\n def _set_value(self, index, col, value, takeable: bool = False):\n \"\"\"\n Put single value at passed column and index.\n\n Parameters\n ----------\n index : row label\n col : column label\n value : scalar\n takeable : interpret the index/col as indexers, default False\n \"\"\"\n try:\n if takeable is True:\n series = self._ixs(col, axis=1)\n series._set_value(index, value, takeable=True)\n return\n\n series = self._get_item_cache(col)\n engine = self.index._engine\n loc = engine.get_loc(index)\n validate_numeric_casting(series.dtype, value)\n\n series._values[loc] = value\n # Note: trying to use series._set_value breaks tests in\n # tests.frame.indexing.test_indexing and tests.indexing.test_partial\n except (KeyError, TypeError):\n # set using a non-recursive method & reset the cache\n if takeable:\n self.iloc[index, col] = value\n else:\n self.loc[index, col] = value\n self._item_cache.pop(col, None)\n\n def _ensure_valid_index(self, value):\n \"\"\"\n Ensure that if we don't have an index, that we can create one from the\n passed value.\n \"\"\"\n # GH5632, make sure that we are a Series convertible\n if not len(self.index) and is_list_like(value) and len(value):\n try:\n value = Series(value)\n except (ValueError, NotImplementedError, TypeError) as err:\n raise ValueError(\n \"Cannot set a frame with no defined index \"\n \"and a value that cannot be converted to a Series\"\n ) from err\n\n # GH31368 preserve name of index\n index_copy = value.index.copy()\n if self.index.name is not None:\n index_copy.name = self.index.name\n\n self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)\n\n def _box_col_values(self, values, loc: int) -> Series:\n \"\"\"\n Provide boxed values for a column.\n \"\"\"\n # Lookup in columns so that if e.g. a str datetime was passed\n # we attach the Timestamp object as the name.\n name = self.columns[loc]\n klass = self._constructor_sliced\n return klass(values, index=self.index, name=name, fastpath=True)\n\n # ----------------------------------------------------------------------\n # Unsorted\n\n def query(self, expr, inplace=False, **kwargs):\n \"\"\"\n Query the columns of a DataFrame with a boolean expression.\n\n Parameters\n ----------\n expr : str\n The query string to evaluate.\n\n You can refer to variables\n in the environment by prefixing them with an '@' character like\n ``@a + b``.\n\n You can refer to column names that are not valid Python variable names\n by surrounding them in backticks. Thus, column names containing spaces\n or punctuations (besides underscores) or starting with digits must be\n surrounded by backticks. (For example, a column named \"Area (cm^2) would\n be referenced as `Area (cm^2)`). Column names which are Python keywords\n (like \"list\", \"for\", \"import\", etc) cannot be used.\n\n For example, if one of your columns is called ``a a`` and you want\n to sum it with ``b``, your query should be ```a a` + b``.\n\n .. versionadded:: 0.25.0\n Backtick quoting introduced.\n\n .. versionadded:: 1.0.0\n Expanding functionality of backtick quoting for more than only spaces.\n\n inplace : bool\n Whether the query should modify the data in place or return\n a modified copy.\n **kwargs\n See the documentation for :func:`eval` for complete details\n on the keyword arguments accepted by :meth:`DataFrame.query`.\n\n Returns\n -------\n DataFrame or None\n DataFrame resulting from the provided query expression or\n None if ``inplace=True``.\n\n See Also\n --------\n eval : Evaluate a string describing operations on\n DataFrame columns.\n DataFrame.eval : Evaluate a string describing operations on\n DataFrame columns.\n\n Notes\n -----\n The result of the evaluation of this expression is first passed to\n :attr:`DataFrame.loc` and if that fails because of a\n multidimensional key (e.g., a DataFrame) then the result will be passed\n to :meth:`DataFrame.__getitem__`.\n\n This method uses the top-level :func:`eval` function to\n evaluate the passed query.\n\n The :meth:`~pandas.DataFrame.query` method uses a slightly\n modified Python syntax by default. For example, the ``&`` and ``|``\n (bitwise) operators have the precedence of their boolean cousins,\n :keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,\n however the semantics are different.\n\n You can change the semantics of the expression by passing the keyword\n argument ``parser='python'``. This enforces the same semantics as\n evaluation in Python space. Likewise, you can pass ``engine='python'``\n to evaluate an expression using Python itself as a backend. This is not\n recommended as it is inefficient compared to using ``numexpr`` as the\n engine.\n\n The :attr:`DataFrame.index` and\n :attr:`DataFrame.columns` attributes of the\n :class:`~pandas.DataFrame` instance are placed in the query namespace\n by default, which allows you to treat both the index and columns of the\n frame as a column in the frame.\n The identifier ``index`` is used for the frame index; you can also\n use the name of the index to identify it in a query. Please note that\n Python keywords may not be used as identifiers.\n\n For further details and examples see the ``query`` documentation in\n :ref:`indexing <indexing.query>`.\n\n *Backtick quoted variables*\n\n Backtick quoted variables are parsed as literal Python code and\n are converted internally to a Python valid identifier.\n This can lead to the following problems.\n\n During parsing a number of disallowed characters inside the backtick\n quoted string are replaced by strings that are allowed as a Python identifier.\n These characters include all operators in Python, the space character, the\n question mark, the exclamation mark, the dollar sign, and the euro sign.\n For other characters that fall outside the ASCII range (U+0001..U+007F)\n and those that are not further specified in PEP 3131,\n the query parser will raise an error.\n This excludes whitespace different than the space character,\n but also the hashtag (as it is used for comments) and the backtick\n itself (backtick can also not be escaped).\n\n In a special case, quotes that make a pair around a backtick can\n confuse the parser.\n For example, ```it's` > `that's``` will raise an error,\n as it forms a quoted string (``'s > `that'``) with a backtick inside.\n\n See also the Python documentation about lexical analysis\n (https://docs.python.org/3/reference/lexical_analysis.html)\n in combination with the source code in :mod:`pandas.core.computation.parsing`.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': range(1, 6),\n ... 'B': range(10, 0, -2),\n ... 'C C': range(10, 5, -1)})\n >>> df\n A B C C\n 0 1 10 10\n 1 2 8 9\n 2 3 6 8\n 3 4 4 7\n 4 5 2 6\n >>> df.query('A > B')\n A B C C\n 4 5 2 6\n\n The previous expression is equivalent to\n\n >>> df[df.A > df.B]\n A B C C\n 4 5 2 6\n\n For columns with spaces in their name, you can use backtick quoting.\n\n >>> df.query('B == `C C`')\n A B C C\n 0 1 10 10\n\n The previous expression is equivalent to\n\n >>> df[df.B == df['C C']]\n A B C C\n 0 1 10 10\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n if not isinstance(expr, str):\n msg = f\"expr must be a string to be evaluated, {type(expr)} given\"\n raise ValueError(msg)\n kwargs[\"level\"] = kwargs.pop(\"level\", 0) + 1\n kwargs[\"target\"] = None\n res = self.eval(expr, **kwargs)\n\n try:\n result = self.loc[res]\n except ValueError:\n # when res is multi-dimensional loc raises, but this is sometimes a\n # valid query\n result = self[res]\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def eval(self, expr, inplace=False, **kwargs):\n \"\"\"\n Evaluate a string describing operations on DataFrame columns.\n\n Operates on columns only, not specific rows or elements. This allows\n `eval` to run arbitrary code, which can make you vulnerable to code\n injection if you pass user input to this function.\n\n Parameters\n ----------\n expr : str\n The expression string to evaluate.\n inplace : bool, default False\n If the expression contains an assignment, whether to perform the\n operation inplace and mutate the existing DataFrame. Otherwise,\n a new DataFrame is returned.\n **kwargs\n See the documentation for :func:`eval` for complete details\n on the keyword arguments accepted by\n :meth:`~pandas.DataFrame.query`.\n\n Returns\n -------\n ndarray, scalar, pandas object, or None\n The result of the evaluation or None if ``inplace=True``.\n\n See Also\n --------\n DataFrame.query : Evaluates a boolean expression to query the columns\n of a frame.\n DataFrame.assign : Can evaluate an expression or function to create new\n values for a column.\n eval : Evaluate a Python expression as a string using various\n backends.\n\n Notes\n -----\n For more details see the API documentation for :func:`~eval`.\n For detailed examples see :ref:`enhancing performance with eval\n <enhancingperf.eval>`.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': range(1, 6), 'B': range(10, 0, -2)})\n >>> df\n A B\n 0 1 10\n 1 2 8\n 2 3 6\n 3 4 4\n 4 5 2\n >>> df.eval('A + B')\n 0 11\n 1 10\n 2 9\n 3 8\n 4 7\n dtype: int64\n\n Assignment is allowed though by default the original DataFrame is not\n modified.\n\n >>> df.eval('C = A + B')\n A B C\n 0 1 10 11\n 1 2 8 10\n 2 3 6 9\n 3 4 4 8\n 4 5 2 7\n >>> df\n A B\n 0 1 10\n 1 2 8\n 2 3 6\n 3 4 4\n 4 5 2\n\n Use ``inplace=True`` to modify the original DataFrame.\n\n >>> df.eval('C = A + B', inplace=True)\n >>> df\n A B C\n 0 1 10 11\n 1 2 8 10\n 2 3 6 9\n 3 4 4 8\n 4 5 2 7\n\n Multiple columns can be assigned to using multi-line expressions:\n\n >>> df.eval(\n ... '''\n ... C = A + B\n ... D = A - B\n ... '''\n ... )\n A B C D\n 0 1 10 11 -9\n 1 2 8 10 -6\n 2 3 6 9 -3\n 3 4 4 8 0\n 4 5 2 7 3\n \"\"\"\n from pandas.core.computation.eval import eval as _eval\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n resolvers = kwargs.pop(\"resolvers\", None)\n kwargs[\"level\"] = kwargs.pop(\"level\", 0) + 1\n if resolvers is None:\n index_resolvers = self._get_index_resolvers()\n column_resolvers = self._get_cleaned_column_resolvers()\n resolvers = column_resolvers, index_resolvers\n if \"target\" not in kwargs:\n kwargs[\"target\"] = self\n kwargs[\"resolvers\"] = kwargs.get(\"resolvers\", ()) + tuple(resolvers)\n\n return _eval(expr, inplace=inplace, **kwargs)\n\n def select_dtypes(self, include=None, exclude=None) -> DataFrame:\n \"\"\"\n Return a subset of the DataFrame's columns based on the column dtypes.\n\n Parameters\n ----------\n include, exclude : scalar or list-like\n A selection of dtypes or strings to be included/excluded. At least\n one of these parameters must be supplied.\n\n Returns\n -------\n DataFrame\n The subset of the frame including the dtypes in ``include`` and\n excluding the dtypes in ``exclude``.\n\n Raises\n ------\n ValueError\n * If both of ``include`` and ``exclude`` are empty\n * If ``include`` and ``exclude`` have overlapping elements\n * If any kind of string dtype is passed in.\n\n See Also\n --------\n DataFrame.dtypes: Return Series with the data type of each column.\n\n Notes\n -----\n * To select all *numeric* types, use ``np.number`` or ``'number'``\n * To select strings you must use the ``object`` dtype, but note that\n this will return *all* object dtype columns\n * See the `numpy dtype hierarchy\n <https://numpy.org/doc/stable/reference/arrays.scalars.html>`__\n * To select datetimes, use ``np.datetime64``, ``'datetime'`` or\n ``'datetime64'``\n * To select timedeltas, use ``np.timedelta64``, ``'timedelta'`` or\n ``'timedelta64'``\n * To select Pandas categorical dtypes, use ``'category'``\n * To select Pandas datetimetz dtypes, use ``'datetimetz'`` (new in\n 0.20.0) or ``'datetime64[ns, tz]'``\n\n Examples\n --------\n >>> df = pd.DataFrame({'a': [1, 2] * 3,\n ... 'b': [True, False] * 3,\n ... 'c': [1.0, 2.0] * 3})\n >>> df\n a b c\n 0 1 True 1.0\n 1 2 False 2.0\n 2 1 True 1.0\n 3 2 False 2.0\n 4 1 True 1.0\n 5 2 False 2.0\n\n >>> df.select_dtypes(include='bool')\n b\n 0 True\n 1 False\n 2 True\n 3 False\n 4 True\n 5 False\n\n >>> df.select_dtypes(include=['float64'])\n c\n 0 1.0\n 1 2.0\n 2 1.0\n 3 2.0\n 4 1.0\n 5 2.0\n\n >>> df.select_dtypes(exclude=['int64'])\n b c\n 0 True 1.0\n 1 False 2.0\n 2 True 1.0\n 3 False 2.0\n 4 True 1.0\n 5 False 2.0\n \"\"\"\n if not is_list_like(include):\n include = (include,) if include is not None else ()\n if not is_list_like(exclude):\n exclude = (exclude,) if exclude is not None else ()\n\n selection = (frozenset(include), frozenset(exclude))\n\n if not any(selection):\n raise ValueError(\"at least one of include or exclude must be nonempty\")\n\n # convert the myriad valid dtypes object to a single representation\n include = frozenset(infer_dtype_from_object(x) for x in include)\n exclude = frozenset(infer_dtype_from_object(x) for x in exclude)\n for dtypes in (include, exclude):\n invalidate_string_dtypes(dtypes)\n\n # can't both include AND exclude!\n if not include.isdisjoint(exclude):\n raise ValueError(f\"include and exclude overlap on {(include & exclude)}\")\n\n # We raise when both include and exclude are empty\n # Hence, we can just shrink the columns we want to keep\n keep_these = np.full(self.shape[1], True)\n\n def extract_unique_dtypes_from_dtypes_set(\n dtypes_set: FrozenSet[Dtype], unique_dtypes: np.ndarray\n ) -> List[Dtype]:\n extracted_dtypes = [\n unique_dtype\n for unique_dtype in unique_dtypes\n # error: Argument 1 to \"tuple\" has incompatible type\n # \"FrozenSet[Union[ExtensionDtype, str, Any, Type[str],\n # Type[float], Type[int], Type[complex], Type[bool]]]\";\n # expected \"Iterable[Union[type, Tuple[Any, ...]]]\"\n if issubclass(\n unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type]\n )\n ]\n return extracted_dtypes\n\n unique_dtypes = self.dtypes.unique()\n\n if include:\n included_dtypes = extract_unique_dtypes_from_dtypes_set(\n include, unique_dtypes\n )\n keep_these &= self.dtypes.isin(included_dtypes)\n\n if exclude:\n excluded_dtypes = extract_unique_dtypes_from_dtypes_set(\n exclude, unique_dtypes\n )\n keep_these &= ~self.dtypes.isin(excluded_dtypes)\n\n return self.iloc[:, keep_these.values]\n\n def insert(self, loc, column, value, allow_duplicates=False) -> None:\n \"\"\"\n Insert column into DataFrame at specified location.\n\n Raises a ValueError if `column` is already contained in the DataFrame,\n unless `allow_duplicates` is set to True.\n\n Parameters\n ----------\n loc : int\n Insertion index. Must verify 0 <= loc <= len(columns).\n column : str, number, or hashable object\n Label of the inserted column.\n value : int, Series, or array-like\n allow_duplicates : bool, optional\n \"\"\"\n if allow_duplicates and not self.flags.allows_duplicate_labels:\n raise ValueError(\n \"Cannot specify 'allow_duplicates=True' when \"\n \"'self.flags.allows_duplicate_labels' is False.\"\n )\n self._ensure_valid_index(value)\n value = self._sanitize_column(column, value, broadcast=False)\n self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)\n\n def assign(self, **kwargs) -> DataFrame:\n r\"\"\"\n Assign new columns to a DataFrame.\n\n Returns a new object with all original columns in addition to new ones.\n Existing columns that are re-assigned will be overwritten.\n\n Parameters\n ----------\n **kwargs : dict of {str: callable or Series}\n The column names are keywords. If the values are\n callable, they are computed on the DataFrame and\n assigned to the new columns. The callable must not\n change input DataFrame (though pandas doesn't check it).\n If the values are not callable, (e.g. a Series, scalar, or array),\n they are simply assigned.\n\n Returns\n -------\n DataFrame\n A new DataFrame with the new columns in addition to\n all the existing columns.\n\n Notes\n -----\n Assigning multiple columns within the same ``assign`` is possible.\n Later items in '\\*\\*kwargs' may refer to newly created or modified\n columns in 'df'; items are computed and assigned into 'df' in order.\n\n Examples\n --------\n >>> df = pd.DataFrame({'temp_c': [17.0, 25.0]},\n ... index=['Portland', 'Berkeley'])\n >>> df\n temp_c\n Portland 17.0\n Berkeley 25.0\n\n Where the value is a callable, evaluated on `df`:\n\n >>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)\n temp_c temp_f\n Portland 17.0 62.6\n Berkeley 25.0 77.0\n\n Alternatively, the same behavior can be achieved by directly\n referencing an existing Series or sequence:\n\n >>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)\n temp_c temp_f\n Portland 17.0 62.6\n Berkeley 25.0 77.0\n\n You can create multiple columns within the same assign where one\n of the columns depends on another one defined within the same assign:\n\n >>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32,\n ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9)\n temp_c temp_f temp_k\n Portland 17.0 62.6 290.15\n Berkeley 25.0 77.0 298.15\n \"\"\"\n data = self.copy()\n\n for k, v in kwargs.items():\n data[k] = com.apply_if_callable(v, data)\n return data\n\n def _sanitize_column(self, key, value, broadcast=True):\n \"\"\"\n Ensures new columns (which go into the BlockManager as new blocks) are\n always copied and converted into an array.\n\n Parameters\n ----------\n key : object\n value : scalar, Series, or array-like\n broadcast : bool, default True\n If ``key`` matches multiple duplicate column names in the\n DataFrame, this parameter indicates whether ``value`` should be\n tiled so that the returned array contains a (duplicated) column for\n each occurrence of the key. If False, ``value`` will not be tiled.\n\n Returns\n -------\n numpy.ndarray\n \"\"\"\n\n def reindexer(value):\n # reindex if necessary\n\n if value.index.equals(self.index) or not len(self.index):\n value = value._values.copy()\n else:\n\n # GH 4107\n try:\n value = value.reindex(self.index)._values\n except ValueError as err:\n # raised in MultiIndex.from_tuples, see test_insert_error_msmgs\n if not value.index.is_unique:\n # duplicate axis\n raise err\n\n # other\n raise TypeError(\n \"incompatible index of inserted column with frame index\"\n ) from err\n return value\n\n if isinstance(value, Series):\n value = reindexer(value)\n\n elif isinstance(value, DataFrame):\n # align right-hand-side columns if self.columns\n # is multi-index and self[key] is a sub-frame\n if isinstance(self.columns, MultiIndex) and key in self.columns:\n loc = self.columns.get_loc(key)\n if isinstance(loc, (slice, Series, np.ndarray, Index)):\n cols = maybe_droplevels(self.columns[loc], key)\n if len(cols) and not cols.equals(value.columns):\n value = value.reindex(cols, axis=1)\n # now align rows\n value = reindexer(value).T\n\n elif isinstance(value, ExtensionArray):\n # Explicitly copy here, instead of in sanitize_index,\n # as sanitize_index won't copy an EA, even with copy=True\n value = value.copy()\n value = sanitize_index(value, self.index)\n\n elif isinstance(value, Index) or is_sequence(value):\n\n # turn me into an ndarray\n value = sanitize_index(value, self.index)\n if not isinstance(value, (np.ndarray, Index)):\n if isinstance(value, list) and len(value) > 0:\n value = maybe_convert_platform(value)\n else:\n value = com.asarray_tuplesafe(value)\n elif value.ndim == 2:\n value = value.copy().T\n elif isinstance(value, Index):\n value = value.copy(deep=True)\n else:\n value = value.copy()\n\n # possibly infer to datetimelike\n if is_object_dtype(value.dtype):\n value = maybe_infer_to_datetimelike(value)\n\n else:\n # cast ignores pandas dtypes. so save the dtype first\n infer_dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)\n\n # upcast\n if is_extension_array_dtype(infer_dtype):\n value = construct_1d_arraylike_from_scalar(\n value, len(self.index), infer_dtype\n )\n else:\n # pandas\\core\\frame.py:3827: error: Argument 1 to\n # \"cast_scalar_to_array\" has incompatible type \"int\"; expected\n # \"Tuple[Any, ...]\" [arg-type]\n value = cast_scalar_to_array(\n len(self.index), value # type: ignore[arg-type]\n )\n\n value = maybe_cast_to_datetime(value, infer_dtype)\n\n # return internal types directly\n if is_extension_array_dtype(value):\n return value\n\n # broadcast across multiple columns if necessary\n if broadcast and key in self.columns and value.ndim == 1:\n if not self.columns.is_unique or isinstance(self.columns, MultiIndex):\n existing_piece = self[key]\n if isinstance(existing_piece, DataFrame):\n value = np.tile(value, (len(existing_piece.columns), 1))\n\n return np.atleast_2d(np.asarray(value))\n\n @property\n def _series(self):\n return {\n item: Series(\n self._mgr.iget(idx), index=self.index, name=item, fastpath=True\n )\n for idx, item in enumerate(self.columns)\n }\n\n def lookup(self, row_labels, col_labels) -> np.ndarray:\n \"\"\"\n Label-based \"fancy indexing\" function for DataFrame.\n Given equal-length arrays of row and column labels, return an\n array of the values corresponding to each (row, col) pair.\n\n .. deprecated:: 1.2.0\n DataFrame.lookup is deprecated,\n use DataFrame.melt and DataFrame.loc instead.\n For an example see :meth:`~pandas.DataFrame.lookup`\n in the user guide.\n\n Parameters\n ----------\n row_labels : sequence\n The row labels to use for lookup.\n col_labels : sequence\n The column labels to use for lookup.\n\n Returns\n -------\n numpy.ndarray\n The found values.\n \"\"\"\n msg = (\n \"The 'lookup' method is deprecated and will be\"\n \"removed in a future version.\"\n \"You can use DataFrame.melt and DataFrame.loc\"\n \"as a substitute.\"\n )\n warnings.warn(msg, FutureWarning, stacklevel=2)\n\n n = len(row_labels)\n if n != len(col_labels):\n raise ValueError(\"Row labels must have same size as column labels\")\n if not (self.index.is_unique and self.columns.is_unique):\n # GH#33041\n raise ValueError(\"DataFrame.lookup requires unique index and columns\")\n\n thresh = 1000\n if not self._is_mixed_type or n > thresh:\n values = self.values\n ridx = self.index.get_indexer(row_labels)\n cidx = self.columns.get_indexer(col_labels)\n if (ridx == -1).any():\n raise KeyError(\"One or more row labels was not found\")\n if (cidx == -1).any():\n raise KeyError(\"One or more column labels was not found\")\n flat_index = ridx * len(self.columns) + cidx\n result = values.flat[flat_index]\n else:\n result = np.empty(n, dtype=\"O\")\n for i, (r, c) in enumerate(zip(row_labels, col_labels)):\n result[i] = self._get_value(r, c)\n\n if is_object_dtype(result):\n result = lib.maybe_convert_objects(result)\n\n return result\n\n # ----------------------------------------------------------------------\n # Reindexing and alignment\n\n def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy):\n frame = self\n\n columns = axes[\"columns\"]\n if columns is not None:\n frame = frame._reindex_columns(\n columns, method, copy, level, fill_value, limit, tolerance\n )\n\n index = axes[\"index\"]\n if index is not None:\n frame = frame._reindex_index(\n index, method, copy, level, fill_value, limit, tolerance\n )\n\n return frame\n\n def _reindex_index(\n self,\n new_index,\n method,\n copy,\n level,\n fill_value=np.nan,\n limit=None,\n tolerance=None,\n ):\n new_index, indexer = self.index.reindex(\n new_index, method=method, level=level, limit=limit, tolerance=tolerance\n )\n return self._reindex_with_indexers(\n {0: [new_index, indexer]},\n copy=copy,\n fill_value=fill_value,\n allow_dups=False,\n )\n\n def _reindex_columns(\n self,\n new_columns,\n method,\n copy,\n level,\n fill_value=None,\n limit=None,\n tolerance=None,\n ):\n new_columns, indexer = self.columns.reindex(\n new_columns, method=method, level=level, limit=limit, tolerance=tolerance\n )\n return self._reindex_with_indexers(\n {1: [new_columns, indexer]},\n copy=copy,\n fill_value=fill_value,\n allow_dups=False,\n )\n\n def _reindex_multi(self, axes, copy, fill_value) -> DataFrame:\n \"\"\"\n We are guaranteed non-Nones in the axes.\n \"\"\"\n new_index, row_indexer = self.index.reindex(axes[\"index\"])\n new_columns, col_indexer = self.columns.reindex(axes[\"columns\"])\n\n if row_indexer is not None and col_indexer is not None:\n indexer = row_indexer, col_indexer\n new_values = algorithms.take_2d_multi(\n self.values, indexer, fill_value=fill_value\n )\n return self._constructor(new_values, index=new_index, columns=new_columns)\n else:\n return self._reindex_with_indexers(\n {0: [new_index, row_indexer], 1: [new_columns, col_indexer]},\n copy=copy,\n fill_value=fill_value,\n )\n\n @doc(NDFrame.align, **_shared_doc_kwargs)\n def align(\n self,\n other,\n join=\"outer\",\n axis=None,\n level=None,\n copy=True,\n fill_value=None,\n method=None,\n limit=None,\n fill_axis=0,\n broadcast_axis=None,\n ) -> DataFrame:\n return super().align(\n other,\n join=join,\n axis=axis,\n level=level,\n copy=copy,\n fill_value=fill_value,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n broadcast_axis=broadcast_axis,\n )\n\n @Appender(\n \"\"\"\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n\n Change the row labels.\n\n >>> df.set_axis(['a', 'b', 'c'], axis='index')\n A B\n a 1 4\n b 2 5\n c 3 6\n\n Change the column labels.\n\n >>> df.set_axis(['I', 'II'], axis='columns')\n I II\n 0 1 4\n 1 2 5\n 2 3 6\n\n Now, update the labels inplace.\n\n >>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)\n >>> df\n i ii\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n )\n @Substitution(\n **_shared_doc_kwargs,\n extended_summary_sub=\" column or\",\n axis_description_sub=\", and 1 identifies the columns\",\n see_also_sub=\" or columns\",\n )\n @Appender(NDFrame.set_axis.__doc__)\n def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):\n return super().set_axis(labels, axis=axis, inplace=inplace)\n\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.reindex.__doc__)\n @rewrite_axis_style_signature(\n \"labels\",\n [\n (\"method\", None),\n (\"copy\", True),\n (\"level\", None),\n (\"fill_value\", np.nan),\n (\"limit\", None),\n (\"tolerance\", None),\n ],\n )\n def reindex(self, *args, **kwargs) -> DataFrame:\n axes = validate_axis_style_args(self, args, kwargs, \"labels\", \"reindex\")\n kwargs.update(axes)\n # Pop these, since the values are in `kwargs` under different names\n kwargs.pop(\"axis\", None)\n kwargs.pop(\"labels\", None)\n return super().reindex(**kwargs)\n\n def drop(\n self,\n labels=None,\n axis=0,\n index=None,\n columns=None,\n level=None,\n inplace=False,\n errors=\"raise\",\n ):\n \"\"\"\n Drop specified labels from rows or columns.\n\n Remove rows or columns by specifying label names and corresponding\n axis, or by specifying directly index or column names. When using a\n multi-index, labels on different levels can be removed by specifying\n the level.\n\n Parameters\n ----------\n labels : single label or list-like\n Index or column labels to drop.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Whether to drop labels from the index (0 or 'index') or\n columns (1 or 'columns').\n index : single label or list-like\n Alternative to specifying axis (``labels, axis=0``\n is equivalent to ``index=labels``).\n columns : single label or list-like\n Alternative to specifying axis (``labels, axis=1``\n is equivalent to ``columns=labels``).\n level : int or level name, optional\n For MultiIndex, level from which the labels will be removed.\n inplace : bool, default False\n If False, return a copy. Otherwise, do operation\n inplace and return None.\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and only existing labels are\n dropped.\n\n Returns\n -------\n DataFrame or None\n DataFrame without the removed index or column labels or\n None if ``inplace=True``.\n\n Raises\n ------\n KeyError\n If any of the labels is not found in the selected axis.\n\n See Also\n --------\n DataFrame.loc : Label-location based indexer for selection by label.\n DataFrame.dropna : Return DataFrame with labels on given axis omitted\n where (all or any) data are missing.\n DataFrame.drop_duplicates : Return DataFrame with duplicate rows\n removed, optionally only considering certain columns.\n Series.drop : Return Series with specified index labels removed.\n\n Examples\n --------\n >>> df = pd.DataFrame(np.arange(12).reshape(3, 4),\n ... columns=['A', 'B', 'C', 'D'])\n >>> df\n A B C D\n 0 0 1 2 3\n 1 4 5 6 7\n 2 8 9 10 11\n\n Drop columns\n\n >>> df.drop(['B', 'C'], axis=1)\n A D\n 0 0 3\n 1 4 7\n 2 8 11\n\n >>> df.drop(columns=['B', 'C'])\n A D\n 0 0 3\n 1 4 7\n 2 8 11\n\n Drop a row by index\n\n >>> df.drop([0, 1])\n A B C D\n 2 8 9 10 11\n\n Drop columns and/or rows of MultiIndex DataFrame\n\n >>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],\n ... ['speed', 'weight', 'length']],\n ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],\n ... [0, 1, 2, 0, 1, 2, 0, 1, 2]])\n >>> df = pd.DataFrame(index=midx, columns=['big', 'small'],\n ... data=[[45, 30], [200, 100], [1.5, 1], [30, 20],\n ... [250, 150], [1.5, 0.8], [320, 250],\n ... [1, 0.8], [0.3, 0.2]])\n >>> df\n big small\n lama speed 45.0 30.0\n weight 200.0 100.0\n length 1.5 1.0\n cow speed 30.0 20.0\n weight 250.0 150.0\n length 1.5 0.8\n falcon speed 320.0 250.0\n weight 1.0 0.8\n length 0.3 0.2\n\n >>> df.drop(index='cow', columns='small')\n big\n lama speed 45.0\n weight 200.0\n length 1.5\n falcon speed 320.0\n weight 1.0\n length 0.3\n\n >>> df.drop(index='length', level=1)\n big small\n lama speed 45.0 30.0\n weight 200.0 100.0\n cow speed 30.0 20.0\n weight 250.0 150.0\n falcon speed 320.0 250.0\n weight 1.0 0.8\n \"\"\"\n return super().drop(\n labels=labels,\n axis=axis,\n index=index,\n columns=columns,\n level=level,\n inplace=inplace,\n errors=errors,\n )\n\n @rewrite_axis_style_signature(\n \"mapper\",\n [(\"copy\", True), (\"inplace\", False), (\"level\", None), (\"errors\", \"ignore\")],\n )\n def rename(\n self,\n mapper: Optional[Renamer] = None,\n *,\n index: Optional[Renamer] = None,\n columns: Optional[Renamer] = None,\n axis: Optional[Axis] = None,\n copy: bool = True,\n inplace: bool = False,\n level: Optional[Level] = None,\n errors: str = \"ignore\",\n ) -> Optional[DataFrame]:\n \"\"\"\n Alter axes labels.\n\n Function / dict values must be unique (1-to-1). Labels not contained in\n a dict / Series will be left as-is. Extra labels listed don't throw an\n error.\n\n See the :ref:`user guide <basics.rename>` for more.\n\n Parameters\n ----------\n mapper : dict-like or function\n Dict-like or function transformations to apply to\n that axis' values. Use either ``mapper`` and ``axis`` to\n specify the axis to target with ``mapper``, or ``index`` and\n ``columns``.\n index : dict-like or function\n Alternative to specifying axis (``mapper, axis=0``\n is equivalent to ``index=mapper``).\n columns : dict-like or function\n Alternative to specifying axis (``mapper, axis=1``\n is equivalent to ``columns=mapper``).\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Axis to target with ``mapper``. Can be either the axis name\n ('index', 'columns') or number (0, 1). The default is 'index'.\n copy : bool, default True\n Also copy underlying data.\n inplace : bool, default False\n Whether to return a new DataFrame. If True then value of copy is\n ignored.\n level : int or level name, default None\n In case of a MultiIndex, only rename labels in the specified\n level.\n errors : {'ignore', 'raise'}, default 'ignore'\n If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,\n or `columns` contains labels that are not present in the Index\n being transformed.\n If 'ignore', existing keys will be renamed and extra keys will be\n ignored.\n\n Returns\n -------\n DataFrame or None\n DataFrame with the renamed axis labels or None if ``inplace=True``.\n\n Raises\n ------\n KeyError\n If any of the labels is not found in the selected axis and\n \"errors='raise'\".\n\n See Also\n --------\n DataFrame.rename_axis : Set the name of the axis.\n\n Examples\n --------\n ``DataFrame.rename`` supports two calling conventions\n\n * ``(index=index_mapper, columns=columns_mapper, ...)``\n * ``(mapper, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n Rename columns using a mapping:\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n >>> df.rename(columns={\"A\": \"a\", \"B\": \"c\"})\n a c\n 0 1 4\n 1 2 5\n 2 3 6\n\n Rename index using a mapping:\n\n >>> df.rename(index={0: \"x\", 1: \"y\", 2: \"z\"})\n A B\n x 1 4\n y 2 5\n z 3 6\n\n Cast index labels to a different type:\n\n >>> df.index\n RangeIndex(start=0, stop=3, step=1)\n >>> df.rename(index=str).index\n Index(['0', '1', '2'], dtype='object')\n\n >>> df.rename(columns={\"A\": \"a\", \"B\": \"b\", \"C\": \"c\"}, errors=\"raise\")\n Traceback (most recent call last):\n KeyError: ['C'] not found in axis\n\n Using axis-style parameters:\n\n >>> df.rename(str.lower, axis='columns')\n a b\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename({1: 2, 2: 4}, axis='index')\n A B\n 0 1 4\n 2 2 5\n 4 3 6\n \"\"\"\n return super().rename(\n mapper=mapper,\n index=index,\n columns=columns,\n axis=axis,\n copy=copy,\n inplace=inplace,\n level=level,\n errors=errors,\n )\n\n @doc(NDFrame.fillna, **_shared_doc_kwargs)\n def fillna(\n self,\n value=None,\n method=None,\n axis=None,\n inplace=False,\n limit=None,\n downcast=None,\n ) -> Optional[DataFrame]:\n return super().fillna(\n value=value,\n method=method,\n axis=axis,\n inplace=inplace,\n limit=limit,\n downcast=downcast,\n )\n\n def pop(self, item: Label) -> Series:\n \"\"\"\n Return item and drop from frame. Raise KeyError if not found.\n\n Parameters\n ----------\n item : label\n Label of column to be popped.\n\n Returns\n -------\n Series\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0),\n ... ('parrot', 'bird', 24.0),\n ... ('lion', 'mammal', 80.5),\n ... ('monkey', 'mammal', np.nan)],\n ... columns=('name', 'class', 'max_speed'))\n >>> df\n name class max_speed\n 0 falcon bird 389.0\n 1 parrot bird 24.0\n 2 lion mammal 80.5\n 3 monkey mammal NaN\n\n >>> df.pop('class')\n 0 bird\n 1 bird\n 2 mammal\n 3 mammal\n Name: class, dtype: object\n\n >>> df\n name max_speed\n 0 falcon 389.0\n 1 parrot 24.0\n 2 lion 80.5\n 3 monkey NaN\n \"\"\"\n return super().pop(item=item)\n\n @doc(NDFrame.replace, **_shared_doc_kwargs)\n def replace(\n self,\n to_replace=None,\n value=None,\n inplace=False,\n limit=None,\n regex=False,\n method=\"pad\",\n ):\n return super().replace(\n to_replace=to_replace,\n value=value,\n inplace=inplace,\n limit=limit,\n regex=regex,\n method=method,\n )\n\n def _replace_columnwise(\n self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex\n ):\n \"\"\"\n Dispatch to Series.replace column-wise.\n\n\n Parameters\n ----------\n mapping : dict\n of the form {col: (target, value)}\n inplace : bool\n regex : bool or same types as `to_replace` in DataFrame.replace\n\n Returns\n -------\n DataFrame or None\n \"\"\"\n # Operate column-wise\n res = self if inplace else self.copy()\n ax = self.columns\n\n for i in range(len(ax)):\n if ax[i] in mapping:\n ser = self.iloc[:, i]\n\n target, value = mapping[ax[i]]\n newobj = ser.replace(target, value, regex=regex)\n\n res.iloc[:, i] = newobj\n\n if inplace:\n return\n return res.__finalize__(self)\n\n @doc(NDFrame.shift, klass=_shared_doc_kwargs[\"klass\"])\n def shift(\n self, periods=1, freq=None, axis=0, fill_value=lib.no_default\n ) -> DataFrame:\n axis = self._get_axis_number(axis)\n\n ncols = len(self.columns)\n if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:\n # We will infer fill_value to match the closest column\n\n if periods > 0:\n result = self.iloc[:, :-periods]\n for col in range(min(ncols, abs(periods))):\n # TODO(EA2D): doing this in a loop unnecessary with 2D EAs\n # Define filler inside loop so we get a copy\n filler = self.iloc[:, 0].shift(len(self))\n result.insert(0, col, filler, allow_duplicates=True)\n else:\n result = self.iloc[:, -periods:]\n for col in range(min(ncols, abs(periods))):\n # Define filler inside loop so we get a copy\n filler = self.iloc[:, -1].shift(len(self))\n result.insert(\n len(result.columns), col, filler, allow_duplicates=True\n )\n\n result.columns = self.columns.copy()\n return result\n\n return super().shift(\n periods=periods, freq=freq, axis=axis, fill_value=fill_value\n )\n\n def set_index(\n self, keys, drop=True, append=False, inplace=False, verify_integrity=False\n ):\n \"\"\"\n Set the DataFrame index using existing columns.\n\n Set the DataFrame index (row labels) using one or more existing\n columns or arrays (of the correct length). The index can replace the\n existing index or expand on it.\n\n Parameters\n ----------\n keys : label or array-like or list of labels/arrays\n This parameter can be either a single column key, a single array of\n the same length as the calling DataFrame, or a list containing an\n arbitrary combination of column keys and arrays. Here, \"array\"\n encompasses :class:`Series`, :class:`Index`, ``np.ndarray``, and\n instances of :class:`~collections.abc.Iterator`.\n drop : bool, default True\n Delete columns to be used as the new index.\n append : bool, default False\n Whether to append columns to existing index.\n inplace : bool, default False\n If True, modifies the DataFrame in place (do not create a new object).\n verify_integrity : bool, default False\n Check the new index for duplicates. Otherwise defer the check until\n necessary. Setting to False will improve the performance of this\n method.\n\n Returns\n -------\n DataFrame or None\n Changed row labels or None if ``inplace=True``.\n\n See Also\n --------\n DataFrame.reset_index : Opposite of set_index.\n DataFrame.reindex : Change to new indices or expand indices.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame({'month': [1, 4, 7, 10],\n ... 'year': [2012, 2014, 2013, 2014],\n ... 'sale': [55, 40, 84, 31]})\n >>> df\n month year sale\n 0 1 2012 55\n 1 4 2014 40\n 2 7 2013 84\n 3 10 2014 31\n\n Set the index to become the 'month' column:\n\n >>> df.set_index('month')\n year sale\n month\n 1 2012 55\n 4 2014 40\n 7 2013 84\n 10 2014 31\n\n Create a MultiIndex using columns 'year' and 'month':\n\n >>> df.set_index(['year', 'month'])\n sale\n year month\n 2012 1 55\n 2014 4 40\n 2013 7 84\n 2014 10 31\n\n Create a MultiIndex using an Index and a column:\n\n >>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])\n month sale\n year\n 1 2012 1 55\n 2 2014 4 40\n 3 2013 7 84\n 4 2014 10 31\n\n Create a MultiIndex using two Series:\n\n >>> s = pd.Series([1, 2, 3, 4])\n >>> df.set_index([s, s**2])\n month year sale\n 1 1 1 2012 55\n 2 4 4 2014 40\n 3 9 7 2013 84\n 4 16 10 2014 31\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n self._check_inplace_and_allows_duplicate_labels(inplace)\n if not isinstance(keys, list):\n keys = [keys]\n\n err_msg = (\n 'The parameter \"keys\" may be a column key, one-dimensional '\n \"array, or a list containing only valid column keys and \"\n \"one-dimensional arrays.\"\n )\n\n missing: List[Label] = []\n for col in keys:\n if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)):\n # arrays are fine as long as they are one-dimensional\n # iterators get converted to list below\n if getattr(col, \"ndim\", 1) != 1:\n raise ValueError(err_msg)\n else:\n # everything else gets tried as a key; see GH 24969\n try:\n found = col in self.columns\n except TypeError as err:\n raise TypeError(\n f\"{err_msg}. Received column of type {type(col)}\"\n ) from err\n else:\n if not found:\n missing.append(col)\n\n if missing:\n raise KeyError(f\"None of {missing} are in the columns\")\n\n if inplace:\n frame = self\n else:\n frame = self.copy()\n\n arrays = []\n names: List[Label] = []\n if append:\n names = list(self.index.names)\n if isinstance(self.index, MultiIndex):\n for i in range(self.index.nlevels):\n arrays.append(self.index._get_level_values(i))\n else:\n arrays.append(self.index)\n\n to_remove: List[Label] = []\n for col in keys:\n if isinstance(col, MultiIndex):\n for n in range(col.nlevels):\n arrays.append(col._get_level_values(n))\n names.extend(col.names)\n elif isinstance(col, (Index, Series)):\n # if Index then not MultiIndex (treated above)\n arrays.append(col)\n names.append(col.name)\n elif isinstance(col, (list, np.ndarray)):\n arrays.append(col)\n names.append(None)\n elif isinstance(col, abc.Iterator):\n arrays.append(list(col))\n names.append(None)\n # from here, col can only be a column label\n else:\n arrays.append(frame[col]._values)\n names.append(col)\n if drop:\n to_remove.append(col)\n\n if len(arrays[-1]) != len(self):\n # check newest element against length of calling frame, since\n # ensure_index_from_sequences would not raise for append=False.\n raise ValueError(\n f\"Length mismatch: Expected {len(self)} rows, \"\n f\"received array of length {len(arrays[-1])}\"\n )\n\n index = ensure_index_from_sequences(arrays, names)\n\n if verify_integrity and not index.is_unique:\n duplicates = index[index.duplicated()].unique()\n raise ValueError(f\"Index has duplicate keys: {duplicates}\")\n\n # use set to handle duplicate column names gracefully in case of drop\n for c in set(to_remove):\n del frame[c]\n\n # clear up memory usage\n index._cleanup()\n\n frame.index = index\n\n if not inplace:\n return frame\n\n @overload\n # https://github.com/python/mypy/issues/6580\n # Overloaded function signatures 1 and 2 overlap with incompatible return types\n def reset_index( # type: ignore[misc]\n self,\n level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,\n drop: bool = ...,\n inplace: Literal[False] = ...,\n col_level: Hashable = ...,\n col_fill: Label = ...,\n ) -> DataFrame:\n ...\n\n @overload\n def reset_index(\n self,\n level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,\n drop: bool = ...,\n inplace: Literal[True] = ...,\n col_level: Hashable = ...,\n col_fill: Label = ...,\n ) -> None:\n ...\n\n def reset_index(\n self,\n level: Optional[Union[Hashable, Sequence[Hashable]]] = None,\n drop: bool = False,\n inplace: bool = False,\n col_level: Hashable = 0,\n col_fill: Label = \"\",\n ) -> Optional[DataFrame]:\n \"\"\"\n Reset the index, or a level of it.\n\n Reset the index of the DataFrame, and use the default one instead.\n If the DataFrame has a MultiIndex, this method can remove one or more\n levels.\n\n Parameters\n ----------\n level : int, str, tuple, or list, default None\n Only remove the given levels from the index. Removes all levels by\n default.\n drop : bool, default False\n Do not try to insert index into dataframe columns. This resets\n the index to the default integer index.\n inplace : bool, default False\n Modify the DataFrame in place (do not create a new object).\n col_level : int or str, default 0\n If the columns have multiple levels, determines which level the\n labels are inserted into. By default it is inserted into the first\n level.\n col_fill : object, default ''\n If the columns have multiple levels, determines how the other\n levels are named. If None then the index name is repeated.\n\n Returns\n -------\n DataFrame or None\n DataFrame with the new index or None if ``inplace=True``.\n\n See Also\n --------\n DataFrame.set_index : Opposite of reset_index.\n DataFrame.reindex : Change to new indices or expand indices.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame([('bird', 389.0),\n ... ('bird', 24.0),\n ... ('mammal', 80.5),\n ... ('mammal', np.nan)],\n ... index=['falcon', 'parrot', 'lion', 'monkey'],\n ... columns=('class', 'max_speed'))\n >>> df\n class max_speed\n falcon bird 389.0\n parrot bird 24.0\n lion mammal 80.5\n monkey mammal NaN\n\n When we reset the index, the old index is added as a column, and a\n new sequential index is used:\n\n >>> df.reset_index()\n index class max_speed\n 0 falcon bird 389.0\n 1 parrot bird 24.0\n 2 lion mammal 80.5\n 3 monkey mammal NaN\n\n We can use the `drop` parameter to avoid the old index being added as\n a column:\n\n >>> df.reset_index(drop=True)\n class max_speed\n 0 bird 389.0\n 1 bird 24.0\n 2 mammal 80.5\n 3 mammal NaN\n\n You can also use `reset_index` with `MultiIndex`.\n\n >>> index = pd.MultiIndex.from_tuples([('bird', 'falcon'),\n ... ('bird', 'parrot'),\n ... ('mammal', 'lion'),\n ... ('mammal', 'monkey')],\n ... names=['class', 'name'])\n >>> columns = pd.MultiIndex.from_tuples([('speed', 'max'),\n ... ('species', 'type')])\n >>> df = pd.DataFrame([(389.0, 'fly'),\n ... ( 24.0, 'fly'),\n ... ( 80.5, 'run'),\n ... (np.nan, 'jump')],\n ... index=index,\n ... columns=columns)\n >>> df\n speed species\n max type\n class name\n bird falcon 389.0 fly\n parrot 24.0 fly\n mammal lion 80.5 run\n monkey NaN jump\n\n If the index has multiple levels, we can reset a subset of them:\n\n >>> df.reset_index(level='class')\n class speed species\n max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n If we are not dropping the index, by default, it is placed in the top\n level. We can place it in another level:\n\n >>> df.reset_index(level='class', col_level=1)\n speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n When the index is inserted under another level, we can specify under\n which one with the parameter `col_fill`:\n\n >>> df.reset_index(level='class', col_level=1, col_fill='species')\n species speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n\n If we specify a nonexistent level for `col_fill`, it is created:\n\n >>> df.reset_index(level='class', col_level=1, col_fill='genus')\n genus speed species\n class max type\n name\n falcon bird 389.0 fly\n parrot bird 24.0 fly\n lion mammal 80.5 run\n monkey mammal NaN jump\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n self._check_inplace_and_allows_duplicate_labels(inplace)\n if inplace:\n new_obj = self\n else:\n new_obj = self.copy()\n\n new_index = ibase.default_index(len(new_obj))\n if level is not None:\n if not isinstance(level, (tuple, list)):\n level = [level]\n level = [self.index._get_level_number(lev) for lev in level]\n if len(level) < self.index.nlevels:\n new_index = self.index.droplevel(level)\n\n if not drop:\n to_insert: Iterable[Tuple[Any, Optional[Any]]]\n if isinstance(self.index, MultiIndex):\n names = [\n (n if n is not None else f\"level_{i}\")\n for i, n in enumerate(self.index.names)\n ]\n to_insert = zip(self.index.levels, self.index.codes)\n else:\n default = \"index\" if \"index\" not in self else \"level_0\"\n names = [default] if self.index.name is None else [self.index.name]\n to_insert = ((self.index, None),)\n\n multi_col = isinstance(self.columns, MultiIndex)\n for i, (lev, lab) in reversed(list(enumerate(to_insert))):\n if not (level is None or i in level):\n continue\n name = names[i]\n if multi_col:\n col_name = list(name) if isinstance(name, tuple) else [name]\n if col_fill is None:\n if len(col_name) not in (1, self.columns.nlevels):\n raise ValueError(\n \"col_fill=None is incompatible \"\n f\"with incomplete column name {name}\"\n )\n col_fill = col_name[0]\n\n lev_num = self.columns._get_level_number(col_level)\n name_lst = [col_fill] * lev_num + col_name\n missing = self.columns.nlevels - len(name_lst)\n name_lst += [col_fill] * missing\n name = tuple(name_lst)\n # to ndarray and maybe infer different dtype\n level_values = maybe_casted_values(lev, lab)\n new_obj.insert(0, name, level_values)\n\n new_obj.index = new_index\n if not inplace:\n return new_obj\n\n return None\n\n # ----------------------------------------------------------------------\n # Reindex-based selection methods\n\n @doc(NDFrame.isna, klass=_shared_doc_kwargs[\"klass\"])\n def isna(self) -> DataFrame:\n result = self._constructor(self._mgr.isna(func=isna))\n return result.__finalize__(self, method=\"isna\")\n\n @doc(NDFrame.isna, klass=_shared_doc_kwargs[\"klass\"])\n def isnull(self) -> DataFrame:\n return self.isna()\n\n @doc(NDFrame.notna, klass=_shared_doc_kwargs[\"klass\"])\n def notna(self) -> DataFrame:\n return ~self.isna()\n\n @doc(NDFrame.notna, klass=_shared_doc_kwargs[\"klass\"])\n def notnull(self) -> DataFrame:\n return ~self.isna()\n\n def dropna(self, axis=0, how=\"any\", thresh=None, subset=None, inplace=False):\n \"\"\"\n Remove missing values.\n\n See the :ref:`User Guide <missing_data>` for more on which values are\n considered missing, and how to work with missing data.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Determine if rows or columns which contain missing values are\n removed.\n\n * 0, or 'index' : Drop rows which contain missing values.\n * 1, or 'columns' : Drop columns which contain missing value.\n\n .. versionchanged:: 1.0.0\n\n Pass tuple or list to drop on multiple axes.\n Only a single axis is allowed.\n\n how : {'any', 'all'}, default 'any'\n Determine if row or column is removed from DataFrame, when we have\n at least one NA or all NA.\n\n * 'any' : If any NA values are present, drop that row or column.\n * 'all' : If all values are NA, drop that row or column.\n\n thresh : int, optional\n Require that many non-NA values.\n subset : array-like, optional\n Labels along other axis to consider, e.g. if you are dropping rows\n these would be a list of columns to include.\n inplace : bool, default False\n If True, do operation inplace and return None.\n\n Returns\n -------\n DataFrame or None\n DataFrame with NA entries dropped from it or None if ``inplace=True``.\n\n See Also\n --------\n DataFrame.isna: Indicate missing values.\n DataFrame.notna : Indicate existing (non-missing) values.\n DataFrame.fillna : Replace missing values.\n Series.dropna : Drop missing values.\n Index.dropna : Drop missing indices.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"name\": ['Alfred', 'Batman', 'Catwoman'],\n ... \"toy\": [np.nan, 'Batmobile', 'Bullwhip'],\n ... \"born\": [pd.NaT, pd.Timestamp(\"1940-04-25\"),\n ... pd.NaT]})\n >>> df\n name toy born\n 0 Alfred NaN NaT\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Drop the rows where at least one element is missing.\n\n >>> df.dropna()\n name toy born\n 1 Batman Batmobile 1940-04-25\n\n Drop the columns where at least one element is missing.\n\n >>> df.dropna(axis='columns')\n name\n 0 Alfred\n 1 Batman\n 2 Catwoman\n\n Drop the rows where all elements are missing.\n\n >>> df.dropna(how='all')\n name toy born\n 0 Alfred NaN NaT\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Keep only the rows with at least 2 non-NA values.\n\n >>> df.dropna(thresh=2)\n name toy born\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Define in which columns to look for missing values.\n\n >>> df.dropna(subset=['name', 'toy'])\n name toy born\n 1 Batman Batmobile 1940-04-25\n 2 Catwoman Bullwhip NaT\n\n Keep the DataFrame with valid entries in the same variable.\n\n >>> df.dropna(inplace=True)\n >>> df\n name toy born\n 1 Batman Batmobile 1940-04-25\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n if isinstance(axis, (tuple, list)):\n # GH20987\n raise TypeError(\"supplying multiple axes to axis is no longer supported.\")\n\n axis = self._get_axis_number(axis)\n agg_axis = 1 - axis\n\n agg_obj = self\n if subset is not None:\n ax = self._get_axis(agg_axis)\n indices = ax.get_indexer_for(subset)\n check = indices == -1\n if check.any():\n raise KeyError(list(np.compress(check, subset)))\n agg_obj = self.take(indices, axis=agg_axis)\n\n count = agg_obj.count(axis=agg_axis)\n\n if thresh is not None:\n mask = count >= thresh\n elif how == \"any\":\n mask = count == len(agg_obj._get_axis(agg_axis))\n elif how == \"all\":\n mask = count > 0\n else:\n if how is not None:\n raise ValueError(f\"invalid how option: {how}\")\n else:\n raise TypeError(\"must specify how or thresh\")\n\n result = self.loc(axis=axis)[mask]\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def drop_duplicates(\n self,\n subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,\n keep: Union[str, bool] = \"first\",\n inplace: bool = False,\n ignore_index: bool = False,\n ) -> Optional[DataFrame]:\n \"\"\"\n Return DataFrame with duplicate rows removed.\n\n Considering certain columns is optional. Indexes, including time indexes\n are ignored.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use all of the columns.\n keep : {'first', 'last', False}, default 'first'\n Determines which duplicates (if any) to keep.\n - ``first`` : Drop duplicates except for the first occurrence.\n - ``last`` : Drop duplicates except for the last occurrence.\n - False : Drop all duplicates.\n inplace : bool, default False\n Whether to drop duplicates in place or to return a copy.\n ignore_index : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n\n .. versionadded:: 1.0.0\n\n Returns\n -------\n DataFrame or None\n DataFrame with duplicates removed or None if ``inplace=True``.\n\n See Also\n --------\n DataFrame.value_counts: Count unique combinations of columns.\n\n Examples\n --------\n Consider dataset containing ramen rating.\n\n >>> df = pd.DataFrame({\n ... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],\n ... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],\n ... 'rating': [4, 4, 3.5, 15, 5]\n ... })\n >>> df\n brand style rating\n 0 Yum Yum cup 4.0\n 1 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 3 Indomie pack 15.0\n 4 Indomie pack 5.0\n\n By default, it removes duplicate rows based on all columns.\n\n >>> df.drop_duplicates()\n brand style rating\n 0 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 3 Indomie pack 15.0\n 4 Indomie pack 5.0\n\n To remove duplicates on specific column(s), use ``subset``.\n\n >>> df.drop_duplicates(subset=['brand'])\n brand style rating\n 0 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n\n To remove duplicates and keep last occurrences, use ``keep``.\n\n >>> df.drop_duplicates(subset=['brand', 'style'], keep='last')\n brand style rating\n 1 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 4 Indomie pack 5.0\n \"\"\"\n if self.empty:\n return self.copy()\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n ignore_index = validate_bool_kwarg(ignore_index, \"ignore_index\")\n duplicated = self.duplicated(subset, keep=keep)\n\n result = self[-duplicated]\n if ignore_index:\n result.index = ibase.default_index(len(result))\n\n if inplace:\n self._update_inplace(result)\n return None\n else:\n return result\n\n def duplicated(\n self,\n subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,\n keep: Union[str, bool] = \"first\",\n ) -> Series:\n \"\"\"\n Return boolean Series denoting duplicate rows.\n\n Considering certain columns is optional.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use all of the columns.\n keep : {'first', 'last', False}, default 'first'\n Determines which duplicates (if any) to mark.\n\n - ``first`` : Mark duplicates as ``True`` except for the first occurrence.\n - ``last`` : Mark duplicates as ``True`` except for the last occurrence.\n - False : Mark all duplicates as ``True``.\n\n Returns\n -------\n Series\n Boolean series for each duplicated rows.\n\n See Also\n --------\n Index.duplicated : Equivalent method on index.\n Series.duplicated : Equivalent method on Series.\n Series.drop_duplicates : Remove duplicate values from Series.\n DataFrame.drop_duplicates : Remove duplicate values from DataFrame.\n\n Examples\n --------\n Consider dataset containing ramen rating.\n\n >>> df = pd.DataFrame({\n ... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],\n ... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],\n ... 'rating': [4, 4, 3.5, 15, 5]\n ... })\n >>> df\n brand style rating\n 0 Yum Yum cup 4.0\n 1 Yum Yum cup 4.0\n 2 Indomie cup 3.5\n 3 Indomie pack 15.0\n 4 Indomie pack 5.0\n\n By default, for each set of duplicated values, the first occurrence\n is set on False and all others on True.\n\n >>> df.duplicated()\n 0 False\n 1 True\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n By using 'last', the last occurrence of each set of duplicated values\n is set on False and all others on True.\n\n >>> df.duplicated(keep='last')\n 0 True\n 1 False\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n By setting ``keep`` on False, all duplicates are True.\n\n >>> df.duplicated(keep=False)\n 0 True\n 1 True\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n To find duplicates on specific column(s), use ``subset``.\n\n >>> df.duplicated(subset=['brand'])\n 0 False\n 1 True\n 2 False\n 3 True\n 4 True\n dtype: bool\n \"\"\"\n from pandas._libs.hashtable import SIZE_HINT_LIMIT, duplicated_int64\n\n if self.empty:\n return self._constructor_sliced(dtype=bool)\n\n def f(vals):\n labels, shape = algorithms.factorize(\n vals, size_hint=min(len(self), SIZE_HINT_LIMIT)\n )\n return labels.astype(\"i8\", copy=False), len(shape)\n\n if subset is None:\n subset = self.columns\n elif (\n not np.iterable(subset)\n or isinstance(subset, str)\n or isinstance(subset, tuple)\n and subset in self.columns\n ):\n subset = (subset,)\n\n # needed for mypy since can't narrow types using np.iterable\n subset = cast(Iterable, subset)\n\n # Verify all columns in subset exist in the queried dataframe\n # Otherwise, raise a KeyError, same as if you try to __getitem__ with a\n # key that doesn't exist.\n diff = Index(subset).difference(self.columns)\n if not diff.empty:\n raise KeyError(diff)\n\n vals = (col.values for name, col in self.items() if name in subset)\n labels, shape = map(list, zip(*map(f, vals)))\n\n ids = get_group_index(labels, shape, sort=False, xnull=False)\n result = self._constructor_sliced(duplicated_int64(ids, keep), index=self.index)\n return result.__finalize__(self, method=\"duplicated\")\n\n # ----------------------------------------------------------------------\n # Sorting\n # TODO: Just move the sort_values doc here.\n @Substitution(**_shared_doc_kwargs)\n @Appender(NDFrame.sort_values.__doc__)\n # error: Signature of \"sort_values\" incompatible with supertype \"NDFrame\"\n def sort_values( # type: ignore[override]\n self,\n by,\n axis=0,\n ascending=True,\n inplace=False,\n kind=\"quicksort\",\n na_position=\"last\",\n ignore_index=False,\n key: ValueKeyFunc = None,\n ):\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n axis = self._get_axis_number(axis)\n\n if not isinstance(by, list):\n by = [by]\n if is_sequence(ascending) and len(by) != len(ascending):\n raise ValueError(\n f\"Length of ascending ({len(ascending)}) != length of by ({len(by)})\"\n )\n if len(by) > 1:\n\n keys = [self._get_label_or_level_values(x, axis=axis) for x in by]\n\n # need to rewrap columns in Series to apply key function\n if key is not None:\n keys = [Series(k, name=name) for (k, name) in zip(keys, by)]\n\n indexer = lexsort_indexer(\n keys, orders=ascending, na_position=na_position, key=key\n )\n indexer = ensure_platform_int(indexer)\n else:\n\n by = by[0]\n k = self._get_label_or_level_values(by, axis=axis)\n\n # need to rewrap column in Series to apply key function\n if key is not None:\n k = Series(k, name=by)\n\n if isinstance(ascending, (tuple, list)):\n ascending = ascending[0]\n\n indexer = nargsort(\n k, kind=kind, ascending=ascending, na_position=na_position, key=key\n )\n\n new_data = self._mgr.take(\n indexer, axis=self._get_block_manager_axis(axis), verify=False\n )\n\n if ignore_index:\n new_data.axes[1] = ibase.default_index(len(indexer))\n\n result = self._constructor(new_data)\n if inplace:\n return self._update_inplace(result)\n else:\n return result.__finalize__(self, method=\"sort_values\")\n\n def sort_index(\n self,\n axis=0,\n level=None,\n ascending: bool = True,\n inplace: bool = False,\n kind: str = \"quicksort\",\n na_position: str = \"last\",\n sort_remaining: bool = True,\n ignore_index: bool = False,\n key: IndexKeyFunc = None,\n ):\n \"\"\"\n Sort object by labels (along an axis).\n\n Returns a new DataFrame sorted by label if `inplace` argument is\n ``False``, otherwise updates the original DataFrame and returns None.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis along which to sort. The value 0 identifies the rows,\n and 1 identifies the columns.\n level : int or level name or list of ints or list of level names\n If not None, sort on values in specified index level(s).\n ascending : bool or list of bools, default True\n Sort ascending vs. descending. When the index is a MultiIndex the\n sort direction can be controlled for each level individually.\n inplace : bool, default False\n If True, perform operation in-place.\n kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n Choice of sorting algorithm. See also ndarray.np.sort for more\n information. `mergesort` is the only stable algorithm. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position : {'first', 'last'}, default 'last'\n Puts NaNs at the beginning if `first`; `last` puts NaNs at the end.\n Not implemented for MultiIndex.\n sort_remaining : bool, default True\n If True and sorting by level and index is multilevel, sort by other\n levels too (in order) after sorting by specified level.\n ignore_index : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n\n .. versionadded:: 1.0.0\n\n key : callable, optional\n If not None, apply the key function to the index values\n before sorting. This is similar to the `key` argument in the\n builtin :meth:`sorted` function, with the notable difference that\n this `key` function should be *vectorized*. It should expect an\n ``Index`` and return an ``Index`` of the same shape. For MultiIndex\n inputs, the key is applied *per level*.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n DataFrame or None\n The original DataFrame sorted by the labels or None if ``inplace=True``.\n\n See Also\n --------\n Series.sort_index : Sort Series by the index.\n DataFrame.sort_values : Sort DataFrame by the value.\n Series.sort_values : Sort Series by the value.\n\n Examples\n --------\n >>> df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150],\n ... columns=['A'])\n >>> df.sort_index()\n A\n 1 4\n 29 2\n 100 1\n 150 5\n 234 3\n\n By default, it sorts in ascending order, to sort in descending order,\n use ``ascending=False``\n\n >>> df.sort_index(ascending=False)\n A\n 234 3\n 150 5\n 100 1\n 29 2\n 1 4\n\n A key function can be specified which is applied to the index before\n sorting. For a ``MultiIndex`` this is applied to each level separately.\n\n >>> df = pd.DataFrame({\"a\": [1, 2, 3, 4]}, index=['A', 'b', 'C', 'd'])\n >>> df.sort_index(key=lambda x: x.str.lower())\n a\n A 1\n b 2\n C 3\n d 4\n \"\"\"\n return super().sort_index(\n axis,\n level,\n ascending,\n inplace,\n kind,\n na_position,\n sort_remaining,\n ignore_index,\n key,\n )\n\n def value_counts(\n self,\n subset: Optional[Sequence[Label]] = None,\n normalize: bool = False,\n sort: bool = True,\n ascending: bool = False,\n ):\n \"\"\"\n Return a Series containing counts of unique rows in the DataFrame.\n\n .. versionadded:: 1.1.0\n\n Parameters\n ----------\n subset : list-like, optional\n Columns to use when counting unique combinations.\n normalize : bool, default False\n Return proportions rather than frequencies.\n sort : bool, default True\n Sort by frequencies.\n ascending : bool, default False\n Sort in ascending order.\n\n Returns\n -------\n Series\n\n See Also\n --------\n Series.value_counts: Equivalent method on Series.\n\n Notes\n -----\n The returned Series will have a MultiIndex with one level per input\n column. By default, rows that contain any NA values are omitted from\n the result. By default, the resulting Series will be in descending\n order so that the first element is the most frequently-occurring row.\n\n Examples\n --------\n >>> df = pd.DataFrame({'num_legs': [2, 4, 4, 6],\n ... 'num_wings': [2, 0, 0, 0]},\n ... index=['falcon', 'dog', 'cat', 'ant'])\n >>> df\n num_legs num_wings\n falcon 2 2\n dog 4 0\n cat 4 0\n ant 6 0\n\n >>> df.value_counts()\n num_legs num_wings\n 4 0 2\n 2 2 1\n 6 0 1\n dtype: int64\n\n >>> df.value_counts(sort=False)\n num_legs num_wings\n 2 2 1\n 4 0 2\n 6 0 1\n dtype: int64\n\n >>> df.value_counts(ascending=True)\n num_legs num_wings\n 2 2 1\n 6 0 1\n 4 0 2\n dtype: int64\n\n >>> df.value_counts(normalize=True)\n num_legs num_wings\n 4 0 0.50\n 2 2 0.25\n 6 0 0.25\n dtype: float64\n \"\"\"\n if subset is None:\n subset = self.columns.tolist()\n\n counts = self.groupby(subset).grouper.size()\n\n if sort:\n counts = counts.sort_values(ascending=ascending)\n if normalize:\n counts /= counts.sum()\n\n # Force MultiIndex for single column\n if len(subset) == 1:\n counts.index = MultiIndex.from_arrays(\n [counts.index], names=[counts.index.name]\n )\n\n return counts\n\n def nlargest(self, n, columns, keep=\"first\") -> DataFrame:\n \"\"\"\n Return the first `n` rows ordered by `columns` in descending order.\n\n Return the first `n` rows with the largest values in `columns`, in\n descending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to\n ``df.sort_values(columns, ascending=False).head(n)``, but more\n performant.\n\n Parameters\n ----------\n n : int\n Number of rows to return.\n columns : label or list of labels\n Column label(s) to order by.\n keep : {'first', 'last', 'all'}, default 'first'\n Where there are duplicate values:\n\n - `first` : prioritize the first occurrence(s)\n - `last` : prioritize the last occurrence(s)\n - ``all`` : do not drop any duplicates, even it means\n selecting more than `n` items.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n The first `n` rows ordered by the given columns in descending\n order.\n\n See Also\n --------\n DataFrame.nsmallest : Return the first `n` rows ordered by `columns` in\n ascending order.\n DataFrame.sort_values : Sort DataFrame by the values.\n DataFrame.head : Return the first `n` rows without re-ordering.\n\n Notes\n -----\n This function cannot be used with all column types. For example, when\n specifying columns with `object` or `category` dtypes, ``TypeError`` is\n raised.\n\n Examples\n --------\n >>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,\n ... 434000, 434000, 337000, 11300,\n ... 11300, 11300],\n ... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,\n ... 17036, 182, 38, 311],\n ... 'alpha-2': [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\",\n ... \"IS\", \"NR\", \"TV\", \"AI\"]},\n ... index=[\"Italy\", \"France\", \"Malta\",\n ... \"Maldives\", \"Brunei\", \"Iceland\",\n ... \"Nauru\", \"Tuvalu\", \"Anguilla\"])\n >>> df\n population GDP alpha-2\n Italy 59000000 1937894 IT\n France 65000000 2583560 FR\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n Iceland 337000 17036 IS\n Nauru 11300 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n In the following example, we will use ``nlargest`` to select the three\n rows having the largest values in column \"population\".\n\n >>> df.nlargest(3, 'population')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Malta 434000 12011 MT\n\n When using ``keep='last'``, ties are resolved in reverse order:\n\n >>> df.nlargest(3, 'population', keep='last')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Brunei 434000 12128 BN\n\n When using ``keep='all'``, all duplicate items are maintained:\n\n >>> df.nlargest(3, 'population', keep='all')\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n\n To order by the largest values in column \"population\" and then \"GDP\",\n we can specify multiple columns like in the next example.\n\n >>> df.nlargest(3, ['population', 'GDP'])\n population GDP alpha-2\n France 65000000 2583560 FR\n Italy 59000000 1937894 IT\n Brunei 434000 12128 BN\n \"\"\"\n return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest()\n\n def nsmallest(self, n, columns, keep=\"first\") -> DataFrame:\n \"\"\"\n Return the first `n` rows ordered by `columns` in ascending order.\n\n Return the first `n` rows with the smallest values in `columns`, in\n ascending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to\n ``df.sort_values(columns, ascending=True).head(n)``, but more\n performant.\n\n Parameters\n ----------\n n : int\n Number of items to retrieve.\n columns : list or str\n Column name or names to order by.\n keep : {'first', 'last', 'all'}, default 'first'\n Where there are duplicate values:\n\n - ``first`` : take the first occurrence.\n - ``last`` : take the last occurrence.\n - ``all`` : do not drop any duplicates, even it means\n selecting more than `n` items.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n DataFrame.nlargest : Return the first `n` rows ordered by `columns` in\n descending order.\n DataFrame.sort_values : Sort DataFrame by the values.\n DataFrame.head : Return the first `n` rows without re-ordering.\n\n Examples\n --------\n >>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,\n ... 434000, 434000, 337000, 337000,\n ... 11300, 11300],\n ... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,\n ... 17036, 182, 38, 311],\n ... 'alpha-2': [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\",\n ... \"IS\", \"NR\", \"TV\", \"AI\"]},\n ... index=[\"Italy\", \"France\", \"Malta\",\n ... \"Maldives\", \"Brunei\", \"Iceland\",\n ... \"Nauru\", \"Tuvalu\", \"Anguilla\"])\n >>> df\n population GDP alpha-2\n Italy 59000000 1937894 IT\n France 65000000 2583560 FR\n Malta 434000 12011 MT\n Maldives 434000 4520 MV\n Brunei 434000 12128 BN\n Iceland 337000 17036 IS\n Nauru 337000 182 NR\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n\n In the following example, we will use ``nsmallest`` to select the\n three rows having the smallest values in column \"population\".\n\n >>> df.nsmallest(3, 'population')\n population GDP alpha-2\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n Iceland 337000 17036 IS\n\n When using ``keep='last'``, ties are resolved in reverse order:\n\n >>> df.nsmallest(3, 'population', keep='last')\n population GDP alpha-2\n Anguilla 11300 311 AI\n Tuvalu 11300 38 TV\n Nauru 337000 182 NR\n\n When using ``keep='all'``, all duplicate items are maintained:\n\n >>> df.nsmallest(3, 'population', keep='all')\n population GDP alpha-2\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n Iceland 337000 17036 IS\n Nauru 337000 182 NR\n\n To order by the smallest values in column \"population\" and then \"GDP\", we can\n specify multiple columns like in the next example.\n\n >>> df.nsmallest(3, ['population', 'GDP'])\n population GDP alpha-2\n Tuvalu 11300 38 TV\n Anguilla 11300 311 AI\n Nauru 337000 182 NR\n \"\"\"\n return algorithms.SelectNFrame(\n self, n=n, keep=keep, columns=columns\n ).nsmallest()\n\n def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame:\n \"\"\"\n Swap levels i and j in a MultiIndex on a particular axis.\n\n Parameters\n ----------\n i, j : int or str\n Levels of the indices to be swapped. Can pass level name as string.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to swap levels on. 0 or 'index' for row-wise, 1 or\n 'columns' for column-wise.\n\n Returns\n -------\n DataFrame\n \"\"\"\n result = self.copy()\n\n axis = self._get_axis_number(axis)\n\n if not isinstance(result._get_axis(axis), MultiIndex): # pragma: no cover\n raise TypeError(\"Can only swap levels on a hierarchical axis.\")\n\n if axis == 0:\n assert isinstance(result.index, MultiIndex)\n result.index = result.index.swaplevel(i, j)\n else:\n assert isinstance(result.columns, MultiIndex)\n result.columns = result.columns.swaplevel(i, j)\n return result\n\n def reorder_levels(self, order, axis=0) -> DataFrame:\n \"\"\"\n Rearrange index levels using input order. May not drop or duplicate levels.\n\n Parameters\n ----------\n order : list of int or list of str\n List representing new level order. Reference level by number\n (position) or by key (label).\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Where to reorder levels.\n\n Returns\n -------\n DataFrame\n \"\"\"\n axis = self._get_axis_number(axis)\n if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover\n raise TypeError(\"Can only reorder levels on a hierarchical axis.\")\n\n result = self.copy()\n\n if axis == 0:\n assert isinstance(result.index, MultiIndex)\n result.index = result.index.reorder_levels(order)\n else:\n assert isinstance(result.columns, MultiIndex)\n result.columns = result.columns.reorder_levels(order)\n return result\n\n # ----------------------------------------------------------------------\n # Arithmetic Methods\n\n def _cmp_method(self, other, op):\n axis = 1 # only relevant for Series other case\n\n self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)\n\n # See GH#4537 for discussion of scalar op behavior\n new_data = self._dispatch_frame_op(other, op, axis=axis)\n return self._construct_result(new_data)\n\n def _arith_method(self, other, op):\n if ops.should_reindex_frame_op(self, other, op, 1, 1, None, None):\n return ops.frame_arith_method_with_reindex(self, other, op)\n\n axis = 1 # only relevant for Series other case\n\n self, other = ops.align_method_FRAME(self, other, axis, flex=True, level=None)\n\n new_data = self._dispatch_frame_op(other, op, axis=axis)\n return self._construct_result(new_data)\n\n _logical_method = _arith_method\n\n def _dispatch_frame_op(self, right, func, axis: Optional[int] = None):\n \"\"\"\n Evaluate the frame operation func(left, right) by evaluating\n column-by-column, dispatching to the Series implementation.\n\n Parameters\n ----------\n right : scalar, Series, or DataFrame\n func : arithmetic or comparison operator\n axis : {None, 0, 1}\n\n Returns\n -------\n DataFrame\n \"\"\"\n # Get the appropriate array-op to apply to each column/block's values.\n array_op = ops.get_array_op(func)\n\n right = lib.item_from_zerodim(right)\n if not is_list_like(right):\n # i.e. scalar, faster than checking np.ndim(right) == 0\n bm = self._mgr.apply(array_op, right=right)\n return type(self)(bm)\n\n elif isinstance(right, DataFrame):\n assert self.index.equals(right.index)\n assert self.columns.equals(right.columns)\n # TODO: The previous assertion `assert right._indexed_same(self)`\n # fails in cases with empty columns reached via\n # _frame_arith_method_with_reindex\n\n bm = self._mgr.operate_blockwise(right._mgr, array_op)\n return type(self)(bm)\n\n elif isinstance(right, Series) and axis == 1:\n # axis=1 means we want to operate row-by-row\n assert right.index.equals(self.columns)\n\n right = right._values\n # maybe_align_as_frame ensures we do not have an ndarray here\n assert not isinstance(right, np.ndarray)\n\n arrays = [\n array_op(_left, _right)\n for _left, _right in zip(self._iter_column_arrays(), right)\n ]\n\n elif isinstance(right, Series):\n assert right.index.equals(self.index) # Handle other cases later\n right = right._values\n\n arrays = [array_op(left, right) for left in self._iter_column_arrays()]\n\n else:\n # Remaining cases have less-obvious dispatch rules\n raise NotImplementedError(right)\n\n return type(self)._from_arrays(\n arrays, self.columns, self.index, verify_integrity=False\n )\n\n def _combine_frame(self, other: DataFrame, func, fill_value=None):\n # at this point we have `self._indexed_same(other)`\n\n if fill_value is None:\n # since _arith_op may be called in a loop, avoid function call\n # overhead if possible by doing this check once\n _arith_op = func\n\n else:\n\n def _arith_op(left, right):\n # for the mixed_type case where we iterate over columns,\n # _arith_op(left, right) is equivalent to\n # left._binop(right, func, fill_value=fill_value)\n left, right = ops.fill_binop(left, right, fill_value)\n return func(left, right)\n\n new_data = self._dispatch_frame_op(other, _arith_op)\n return new_data\n\n def _construct_result(self, result) -> DataFrame:\n \"\"\"\n Wrap the result of an arithmetic, comparison, or logical operation.\n\n Parameters\n ----------\n result : DataFrame\n\n Returns\n -------\n DataFrame\n \"\"\"\n out = self._constructor(result, copy=False)\n # Pin columns instead of passing to constructor for compat with\n # non-unique columns case\n out.columns = self.columns\n out.index = self.index\n return out\n\n def __divmod__(self, other) -> Tuple[DataFrame, DataFrame]:\n # Naive implementation, room for optimization\n div = self // other\n mod = self - div * other\n return div, mod\n\n def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]:\n # Naive implementation, room for optimization\n div = other // self\n mod = other - div * self\n return div, mod\n\n # ----------------------------------------------------------------------\n # Combination-Related\n\n @doc(\n _shared_docs[\"compare\"],\n \"\"\"\nReturns\n-------\nDataFrame\n DataFrame that shows the differences stacked side by side.\n\n The resulting index will be a MultiIndex with 'self' and 'other'\n stacked alternately at the inner level.\n\nRaises\n------\nValueError\n When the two DataFrames don't have identical labels or shape.\n\nSee Also\n--------\nSeries.compare : Compare with another Series and show differences.\nDataFrame.equals : Test whether two objects contain the same elements.\n\nNotes\n-----\nMatching NaNs will not appear as a difference.\n\nCan only compare identically-labeled\n(i.e. same shape, identical row and column labels) DataFrames\n\nExamples\n--------\n>>> df = pd.DataFrame(\n... {{\n... \"col1\": [\"a\", \"a\", \"b\", \"b\", \"a\"],\n... \"col2\": [1.0, 2.0, 3.0, np.nan, 5.0],\n... \"col3\": [1.0, 2.0, 3.0, 4.0, 5.0]\n... }},\n... columns=[\"col1\", \"col2\", \"col3\"],\n... )\n>>> df\n col1 col2 col3\n0 a 1.0 1.0\n1 a 2.0 2.0\n2 b 3.0 3.0\n3 b NaN 4.0\n4 a 5.0 5.0\n\n>>> df2 = df.copy()\n>>> df2.loc[0, 'col1'] = 'c'\n>>> df2.loc[2, 'col3'] = 4.0\n>>> df2\n col1 col2 col3\n0 c 1.0 1.0\n1 a 2.0 2.0\n2 b 3.0 4.0\n3 b NaN 4.0\n4 a 5.0 5.0\n\nAlign the differences on columns\n\n>>> df.compare(df2)\n col1 col3\n self other self other\n0 a c NaN NaN\n2 NaN NaN 3.0 4.0\n\nStack the differences on rows\n\n>>> df.compare(df2, align_axis=0)\n col1 col3\n0 self a NaN\n other c NaN\n2 self NaN 3.0\n other NaN 4.0\n\nKeep the equal values\n\n>>> df.compare(df2, keep_equal=True)\n col1 col3\n self other self other\n0 a c 1.0 1.0\n2 b b 3.0 4.0\n\nKeep all original rows and columns\n\n>>> df.compare(df2, keep_shape=True)\n col1 col2 col3\n self other self other self other\n0 a c NaN NaN NaN NaN\n1 NaN NaN NaN NaN NaN NaN\n2 NaN NaN NaN NaN 3.0 4.0\n3 NaN NaN NaN NaN NaN NaN\n4 NaN NaN NaN NaN NaN NaN\n\nKeep all original rows and columns and also all original values\n\n>>> df.compare(df2, keep_shape=True, keep_equal=True)\n col1 col2 col3\n self other self other self other\n0 a c 1.0 1.0 1.0 1.0\n1 a a 2.0 2.0 2.0 2.0\n2 b b 3.0 3.0 3.0 4.0\n3 b b NaN NaN 4.0 4.0\n4 a a 5.0 5.0 5.0 5.0\n\"\"\",\n klass=_shared_doc_kwargs[\"klass\"],\n )\n def compare(\n self,\n other: DataFrame,\n align_axis: Axis = 1,\n keep_shape: bool = False,\n keep_equal: bool = False,\n ) -> DataFrame:\n return super().compare(\n other=other,\n align_axis=align_axis,\n keep_shape=keep_shape,\n keep_equal=keep_equal,\n )\n\n def combine(\n self, other: DataFrame, func, fill_value=None, overwrite=True\n ) -> DataFrame:\n \"\"\"\n Perform column-wise combine with another DataFrame.\n\n Combines a DataFrame with `other` DataFrame using `func`\n to element-wise combine columns. The row and column indexes of the\n resulting DataFrame will be the union of the two.\n\n Parameters\n ----------\n other : DataFrame\n The DataFrame to merge column-wise.\n func : function\n Function that takes two series as inputs and return a Series or a\n scalar. Used to merge the two dataframes column by columns.\n fill_value : scalar value, default None\n The value to fill NaNs with prior to passing any column to the\n merge func.\n overwrite : bool, default True\n If True, columns in `self` that do not exist in `other` will be\n overwritten with NaNs.\n\n Returns\n -------\n DataFrame\n Combination of the provided DataFrames.\n\n See Also\n --------\n DataFrame.combine_first : Combine two DataFrame objects and default to\n non-null values in frame calling the method.\n\n Examples\n --------\n Combine using a simple function that chooses the smaller column.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2\n >>> df1.combine(df2, take_smaller)\n A B\n 0 0 3\n 1 0 3\n\n Example using a true element-wise combine function.\n\n >>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine(df2, np.minimum)\n A B\n 0 1 2\n 1 0 3\n\n Using `fill_value` fills Nones prior to passing the column to the\n merge function.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine(df2, take_smaller, fill_value=-5)\n A B\n 0 0 -5.0\n 1 0 4.0\n\n However, if the same element in both dataframes is None, that None\n is preserved\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})\n >>> df1.combine(df2, take_smaller, fill_value=-5)\n A B\n 0 0 -5.0\n 1 0 3.0\n\n Example that demonstrates the use of `overwrite` and behavior when\n the axis differ between the dataframes.\n\n >>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1], }, index=[1, 2])\n >>> df1.combine(df2, take_smaller)\n A B C\n 0 NaN NaN NaN\n 1 NaN 3.0 -10.0\n 2 NaN 3.0 1.0\n\n >>> df1.combine(df2, take_smaller, overwrite=False)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 -10.0\n 2 NaN 3.0 1.0\n\n Demonstrating the preference of the passed in dataframe.\n\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1], }, index=[1, 2])\n >>> df2.combine(df1, take_smaller)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 NaN\n 2 NaN 3.0 NaN\n\n >>> df2.combine(df1, take_smaller, overwrite=False)\n A B C\n 0 0.0 NaN NaN\n 1 0.0 3.0 1.0\n 2 NaN 3.0 1.0\n \"\"\"\n other_idxlen = len(other.index) # save for compare\n\n this, other = self.align(other, copy=False)\n new_index = this.index\n\n if other.empty and len(new_index) == len(self.index):\n return self.copy()\n\n if self.empty and len(other) == other_idxlen:\n return other.copy()\n\n # sorts if possible\n new_columns = this.columns.union(other.columns)\n do_fill = fill_value is not None\n result = {}\n for col in new_columns:\n series = this[col]\n otherSeries = other[col]\n\n this_dtype = series.dtype\n other_dtype = otherSeries.dtype\n\n this_mask = isna(series)\n other_mask = isna(otherSeries)\n\n # don't overwrite columns unnecessarily\n # DO propagate if this column is not in the intersection\n if not overwrite and other_mask.all():\n result[col] = this[col].copy()\n continue\n\n if do_fill:\n series = series.copy()\n otherSeries = otherSeries.copy()\n series[this_mask] = fill_value\n otherSeries[other_mask] = fill_value\n\n if col not in self.columns:\n # If self DataFrame does not have col in other DataFrame,\n # try to promote series, which is all NaN, as other_dtype.\n new_dtype = other_dtype\n try:\n series = series.astype(new_dtype, copy=False)\n except ValueError:\n # e.g. new_dtype is integer types\n pass\n else:\n # if we have different dtypes, possibly promote\n new_dtype = find_common_type([this_dtype, other_dtype])\n if not is_dtype_equal(this_dtype, new_dtype):\n series = series.astype(new_dtype)\n if not is_dtype_equal(other_dtype, new_dtype):\n otherSeries = otherSeries.astype(new_dtype)\n\n arr = func(series, otherSeries)\n arr = maybe_downcast_to_dtype(arr, new_dtype)\n\n result[col] = arr\n\n # convert_objects just in case\n return self._constructor(result, index=new_index, columns=new_columns)\n\n def combine_first(self, other: DataFrame) -> DataFrame:\n \"\"\"\n Update null elements with value in the same location in `other`.\n\n Combine two DataFrame objects by filling null values in one DataFrame\n with non-null values from other DataFrame. The row and column indexes\n of the resulting DataFrame will be the union of the two.\n\n Parameters\n ----------\n other : DataFrame\n Provided DataFrame to use to fill null values.\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n DataFrame.combine : Perform series-wise operation on two DataFrames\n using a given function.\n\n Examples\n --------\n >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})\n >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n >>> df1.combine_first(df2)\n A B\n 0 1.0 3.0\n 1 0.0 4.0\n\n Null values still persist if the location of that null value\n does not exist in `other`\n\n >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})\n >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])\n >>> df1.combine_first(df2)\n A B C\n 0 NaN 4.0 NaN\n 1 0.0 3.0 1.0\n 2 NaN 3.0 1.0\n \"\"\"\n import pandas.core.computation.expressions as expressions\n\n def combiner(x, y):\n mask = extract_array(isna(x))\n\n x_values = extract_array(x, extract_numpy=True)\n y_values = extract_array(y, extract_numpy=True)\n\n # If the column y in other DataFrame is not in first DataFrame,\n # just return y_values.\n if y.name not in self.columns:\n return y_values\n\n return expressions.where(mask, y_values, x_values)\n\n return self.combine(other, combiner, overwrite=False)\n\n def update(\n self, other, join=\"left\", overwrite=True, filter_func=None, errors=\"ignore\"\n ) -> None:\n \"\"\"\n Modify in place using non-NA values from another DataFrame.\n\n Aligns on indices. There is no return value.\n\n Parameters\n ----------\n other : DataFrame, or object coercible into a DataFrame\n Should have at least one matching index/column label\n with the original DataFrame. If a Series is passed,\n its name attribute must be set, and that will be\n used as the column name to align with the original DataFrame.\n join : {'left'}, default 'left'\n Only left join is implemented, keeping the index and columns of the\n original object.\n overwrite : bool, default True\n How to handle non-NA values for overlapping keys:\n\n * True: overwrite original DataFrame's values\n with values from `other`.\n * False: only update values that are NA in\n the original DataFrame.\n\n filter_func : callable(1d-array) -> bool 1d-array, optional\n Can choose to replace values other than NA. Return True for values\n that should be updated.\n errors : {'raise', 'ignore'}, default 'ignore'\n If 'raise', will raise a ValueError if the DataFrame and `other`\n both contain non-NA data in the same place.\n\n .. versionchanged:: 0.24.0\n Changed from `raise_conflict=False|True`\n to `errors='ignore'|'raise'`.\n\n Returns\n -------\n None : method directly changes calling object\n\n Raises\n ------\n ValueError\n * When `errors='raise'` and there's overlapping non-NA data.\n * When `errors` is not either `'ignore'` or `'raise'`\n NotImplementedError\n * If `join != 'left'`\n\n See Also\n --------\n dict.update : Similar method for dictionaries.\n DataFrame.merge : For column(s)-on-column(s) operations.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3],\n ... 'B': [400, 500, 600]})\n >>> new_df = pd.DataFrame({'B': [4, 5, 6],\n ... 'C': [7, 8, 9]})\n >>> df.update(new_df)\n >>> df\n A B\n 0 1 4\n 1 2 5\n 2 3 6\n\n The DataFrame's length does not increase as a result of the update,\n only values at matching index/column labels are updated.\n\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_df = pd.DataFrame({'B': ['d', 'e', 'f', 'g', 'h', 'i']})\n >>> df.update(new_df)\n >>> df\n A B\n 0 a d\n 1 b e\n 2 c f\n\n For Series, its name attribute must be set.\n\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2])\n >>> df.update(new_column)\n >>> df\n A B\n 0 a d\n 1 b y\n 2 c e\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c'],\n ... 'B': ['x', 'y', 'z']})\n >>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2])\n >>> df.update(new_df)\n >>> df\n A B\n 0 a x\n 1 b d\n 2 c e\n\n If `other` contains NaNs the corresponding values are not updated\n in the original dataframe.\n\n >>> df = pd.DataFrame({'A': [1, 2, 3],\n ... 'B': [400, 500, 600]})\n >>> new_df = pd.DataFrame({'B': [4, np.nan, 6]})\n >>> df.update(new_df)\n >>> df\n A B\n 0 1 4.0\n 1 2 500.0\n 2 3 6.0\n \"\"\"\n import pandas.core.computation.expressions as expressions\n\n # TODO: Support other joins\n if join != \"left\": # pragma: no cover\n raise NotImplementedError(\"Only left join is supported\")\n if errors not in [\"ignore\", \"raise\"]:\n raise ValueError(\"The parameter errors must be either 'ignore' or 'raise'\")\n\n if not isinstance(other, DataFrame):\n other = DataFrame(other)\n\n other = other.reindex_like(self)\n\n for col in self.columns:\n this = self[col]._values\n that = other[col]._values\n if filter_func is not None:\n with np.errstate(all=\"ignore\"):\n mask = ~filter_func(this) | isna(that)\n else:\n if errors == \"raise\":\n mask_this = notna(that)\n mask_that = notna(this)\n if any(mask_this & mask_that):\n raise ValueError(\"Data overlaps.\")\n\n if overwrite:\n mask = isna(that)\n else:\n mask = notna(this)\n\n # don't overwrite columns unnecessarily\n if mask.all():\n continue\n\n self[col] = expressions.where(mask, this, that)\n\n # ----------------------------------------------------------------------\n # Data reshaping\n @Appender(\n \"\"\"\nExamples\n--------\n>>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',\n... 'Parrot', 'Parrot'],\n... 'Max Speed': [380., 370., 24., 26.]})\n>>> df\n Animal Max Speed\n0 Falcon 380.0\n1 Falcon 370.0\n2 Parrot 24.0\n3 Parrot 26.0\n>>> df.groupby(['Animal']).mean()\n Max Speed\nAnimal\nFalcon 375.0\nParrot 25.0\n\n**Hierarchical Indexes**\n\nWe can groupby different levels of a hierarchical index\nusing the `level` parameter:\n\n>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],\n... ['Captive', 'Wild', 'Captive', 'Wild']]\n>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))\n>>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},\n... index=index)\n>>> df\n Max Speed\nAnimal Type\nFalcon Captive 390.0\n Wild 350.0\nParrot Captive 30.0\n Wild 20.0\n>>> df.groupby(level=0).mean()\n Max Speed\nAnimal\nFalcon 370.0\nParrot 25.0\n>>> df.groupby(level=\"Type\").mean()\n Max Speed\nType\nCaptive 210.0\nWild 185.0\n\nWe can also choose to include NA in group keys or not by setting\n`dropna` parameter, the default setting is `True`:\n\n>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]\n>>> df = pd.DataFrame(l, columns=[\"a\", \"b\", \"c\"])\n\n>>> df.groupby(by=[\"b\"]).sum()\n a c\nb\n1.0 2 3\n2.0 2 5\n\n>>> df.groupby(by=[\"b\"], dropna=False).sum()\n a c\nb\n1.0 2 3\n2.0 2 5\nNaN 1 4\n\n>>> l = [[\"a\", 12, 12], [None, 12.3, 33.], [\"b\", 12.3, 123], [\"a\", 1, 1]]\n>>> df = pd.DataFrame(l, columns=[\"a\", \"b\", \"c\"])\n\n>>> df.groupby(by=\"a\").sum()\n b c\na\na 13.0 13.0\nb 12.3 123.0\n\n>>> df.groupby(by=\"a\", dropna=False).sum()\n b c\na\na 13.0 13.0\nb 12.3 123.0\nNaN 12.3 33.0\n\"\"\"\n )\n @Appender(_shared_docs[\"groupby\"] % _shared_doc_kwargs)\n def groupby(\n self,\n by=None,\n axis=0,\n level=None,\n as_index: bool = True,\n sort: bool = True,\n group_keys: bool = True,\n squeeze: bool = no_default,\n observed: bool = False,\n dropna: bool = True,\n ) -> DataFrameGroupBy:\n from pandas.core.groupby.generic import DataFrameGroupBy\n\n if squeeze is not no_default:\n warnings.warn(\n (\n \"The `squeeze` parameter is deprecated and \"\n \"will be removed in a future version.\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n else:\n squeeze = False\n\n if level is None and by is None:\n raise TypeError(\"You have to supply one of 'by' and 'level'\")\n axis = self._get_axis_number(axis)\n\n return DataFrameGroupBy(\n obj=self,\n keys=by,\n axis=axis,\n level=level,\n as_index=as_index,\n sort=sort,\n group_keys=group_keys,\n squeeze=squeeze,\n observed=observed,\n dropna=dropna,\n )\n\n _shared_docs[\n \"pivot\"\n ] = \"\"\"\n Return reshaped DataFrame organized by given index / column values.\n\n Reshape data (produce a \"pivot\" table) based on column values. Uses\n unique values from specified `index` / `columns` to form axes of the\n resulting DataFrame. This function does not support data\n aggregation, multiple values will result in a MultiIndex in the\n columns. See the :ref:`User Guide <reshaping>` for more on reshaping.\n\n Parameters\n ----------%s\n index : str or object or a list of str, optional\n Column to use to make new frame's index. If None, uses\n existing index.\n\n .. versionchanged:: 1.1.0\n Also accept list of index names.\n\n columns : str or object or a list of str\n Column to use to make new frame's columns.\n\n .. versionchanged:: 1.1.0\n Also accept list of columns names.\n\n values : str, object or a list of the previous, optional\n Column(s) to use for populating new frame's values. If not\n specified, all remaining columns will be used and the result will\n have hierarchically indexed columns.\n\n Returns\n -------\n DataFrame\n Returns reshaped DataFrame.\n\n Raises\n ------\n ValueError:\n When there are any `index`, `columns` combinations with multiple\n values. `DataFrame.pivot_table` when you need to aggregate.\n\n See Also\n --------\n DataFrame.pivot_table : Generalization of pivot that can handle\n duplicate values for one index/column pair.\n DataFrame.unstack : Pivot based on the index values instead of a\n column.\n wide_to_long : Wide panel to long format. Less flexible but more\n user-friendly than melt.\n\n Notes\n -----\n For finer-tuned control, see hierarchical indexing documentation along\n with the related stack/unstack methods.\n\n Examples\n --------\n >>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',\n ... '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 >>> df\n foo bar baz zoo\n 0 one A 1 x\n 1 one B 2 y\n 2 one C 3 z\n 3 two A 4 q\n 4 two B 5 w\n 5 two C 6 t\n\n >>> df.pivot(index='foo', columns='bar', values='baz')\n bar A B C\n foo\n one 1 2 3\n two 4 5 6\n\n >>> df.pivot(index='foo', columns='bar')['baz']\n bar A B C\n foo\n one 1 2 3\n two 4 5 6\n\n >>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])\n baz zoo\n bar A B C A B C\n foo\n one 1 2 3 x y z\n two 4 5 6 q w t\n\n You could also assign a list of column names or a list of index names.\n\n >>> df = pd.DataFrame({\n ... \"lev1\": [1, 1, 1, 2, 2, 2],\n ... \"lev2\": [1, 1, 2, 1, 1, 2],\n ... \"lev3\": [1, 2, 1, 2, 1, 2],\n ... \"lev4\": [1, 2, 3, 4, 5, 6],\n ... \"values\": [0, 1, 2, 3, 4, 5]})\n >>> df\n lev1 lev2 lev3 lev4 values\n 0 1 1 1 1 0\n 1 1 1 2 2 1\n 2 1 2 1 3 2\n 3 2 1 2 4 3\n 4 2 1 1 5 4\n 5 2 2 2 6 5\n\n >>> df.pivot(index=\"lev1\", columns=[\"lev2\", \"lev3\"],values=\"values\")\n lev2 1 2\n lev3 1 2 1 2\n lev1\n 1 0.0 1.0 2.0 NaN\n 2 4.0 3.0 NaN 5.0\n\n >>> df.pivot(index=[\"lev1\", \"lev2\"], columns=[\"lev3\"],values=\"values\")\n lev3 1 2\n lev1 lev2\n 1 1 0.0 1.0\n 2 2.0 NaN\n 2 1 4.0 3.0\n 2 NaN 5.0\n\n A ValueError is raised if there are any duplicates.\n\n >>> df = pd.DataFrame({\"foo\": ['one', 'one', 'two', 'two'],\n ... \"bar\": ['A', 'A', 'B', 'C'],\n ... \"baz\": [1, 2, 3, 4]})\n >>> df\n foo bar baz\n 0 one A 1\n 1 one A 2\n 2 two B 3\n 3 two C 4\n\n Notice that the first two rows are the same for our `index`\n and `columns` arguments.\n\n >>> df.pivot(index='foo', columns='bar', values='baz')\n Traceback (most recent call last):\n ...\n ValueError: Index contains duplicate entries, cannot reshape\n \"\"\"\n\n @Substitution(\"\")\n @Appender(_shared_docs[\"pivot\"])\n def pivot(self, index=None, columns=None, values=None) -> DataFrame:\n from pandas.core.reshape.pivot import pivot\n\n return pivot(self, index=index, columns=columns, values=values)\n\n _shared_docs[\n \"pivot_table\"\n ] = \"\"\"\n Create a spreadsheet-style pivot table as a DataFrame.\n\n The levels in the pivot table will be stored in MultiIndex objects\n (hierarchical indexes) on the index and columns of the result DataFrame.\n\n Parameters\n ----------%s\n values : column to aggregate, optional\n index : column, Grouper, array, or list of the previous\n If an array is passed, it must be the same length as the data. The\n list can contain any of the other types (except list).\n Keys to group by on the pivot table index. If an array is passed,\n it is being used as the same manner as column values.\n columns : column, Grouper, array, or list of the previous\n If an array is passed, it must be the same length as the data. The\n list can contain any of the other types (except list).\n Keys to group by on the pivot table column. If an array is passed,\n it is being used as the same manner as column values.\n aggfunc : function, list of functions, dict, default numpy.mean\n If list of functions passed, the resulting pivot table will have\n hierarchical columns whose top level are the function names\n (inferred from the function objects themselves)\n If dict is passed, the key is column to aggregate and value\n is function or list of functions.\n fill_value : scalar, default None\n Value to replace missing values with (in the resulting pivot table,\n after aggregation).\n margins : bool, default False\n Add all row / columns (e.g. for subtotal / grand totals).\n dropna : bool, default True\n Do not include columns whose entries are all NaN.\n margins_name : str, default 'All'\n Name of the row / column that will contain the totals\n when margins is True.\n observed : bool, default False\n This only applies if any of the groupers are Categoricals.\n If True: only show observed values for categorical groupers.\n If False: show all values for categorical groupers.\n\n .. versionchanged:: 0.25.0\n\n Returns\n -------\n DataFrame\n An Excel style pivot table.\n\n See Also\n --------\n DataFrame.pivot : Pivot without aggregation that can handle\n non-numeric data.\n DataFrame.melt: Unpivot a DataFrame from wide to long format,\n optionally leaving identifiers set.\n wide_to_long : Wide panel to long format. Less flexible but more\n user-friendly than melt.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [\"foo\", \"foo\", \"foo\", \"foo\", \"foo\",\n ... \"bar\", \"bar\", \"bar\", \"bar\"],\n ... \"B\": [\"one\", \"one\", \"one\", \"two\", \"two\",\n ... \"one\", \"one\", \"two\", \"two\"],\n ... \"C\": [\"small\", \"large\", \"large\", \"small\",\n ... \"small\", \"large\", \"small\", \"small\",\n ... \"large\"],\n ... \"D\": [1, 2, 2, 3, 3, 4, 5, 6, 7],\n ... \"E\": [2, 4, 5, 5, 6, 6, 8, 9, 9]})\n >>> df\n A B C D E\n 0 foo one small 1 2\n 1 foo one large 2 4\n 2 foo one large 2 5\n 3 foo two small 3 5\n 4 foo two small 3 6\n 5 bar one large 4 6\n 6 bar one small 5 8\n 7 bar two small 6 9\n 8 bar two large 7 9\n\n This first example aggregates values by taking the sum.\n\n >>> table = pd.pivot_table(df, values='D', index=['A', 'B'],\n ... columns=['C'], aggfunc=np.sum)\n >>> table\n C large small\n A B\n bar one 4.0 5.0\n two 7.0 6.0\n foo one 4.0 1.0\n two NaN 6.0\n\n We can also fill missing values using the `fill_value` parameter.\n\n >>> table = pd.pivot_table(df, values='D', index=['A', 'B'],\n ... columns=['C'], aggfunc=np.sum, fill_value=0)\n >>> table\n C large small\n A B\n bar one 4 5\n two 7 6\n foo one 4 1\n two 0 6\n\n The next example aggregates by taking the mean across multiple columns.\n\n >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n ... aggfunc={'D': np.mean,\n ... 'E': np.mean})\n >>> table\n D E\n A C\n bar large 5.500000 7.500000\n small 5.500000 8.500000\n foo large 2.000000 4.500000\n small 2.333333 4.333333\n\n We can also calculate multiple types of aggregations for any given\n value column.\n\n >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n ... aggfunc={'D': np.mean,\n ... 'E': [min, max, np.mean]})\n >>> table\n D E\n mean max mean min\n A C\n bar large 5.500000 9.0 7.500000 6.0\n small 5.500000 9.0 8.500000 8.0\n foo large 2.000000 5.0 4.500000 4.0\n small 2.333333 6.0 4.333333 2.0\n \"\"\"\n\n @Substitution(\"\")\n @Appender(_shared_docs[\"pivot_table\"])\n def pivot_table(\n self,\n values=None,\n index=None,\n columns=None,\n aggfunc=\"mean\",\n fill_value=None,\n margins=False,\n dropna=True,\n margins_name=\"All\",\n observed=False,\n ) -> DataFrame:\n from pandas.core.reshape.pivot import pivot_table\n\n return pivot_table(\n self,\n values=values,\n index=index,\n columns=columns,\n aggfunc=aggfunc,\n fill_value=fill_value,\n margins=margins,\n dropna=dropna,\n margins_name=margins_name,\n observed=observed,\n )\n\n def stack(self, level=-1, dropna=True):\n \"\"\"\n Stack the prescribed level(s) from columns to index.\n\n Return a reshaped DataFrame or Series having a multi-level\n index with one or more new inner-most levels compared to the current\n DataFrame. The new inner-most levels are created by pivoting the\n columns of the current dataframe:\n\n - if the columns have a single level, the output is a Series;\n - if the columns have multiple levels, the new index\n level(s) is (are) taken from the prescribed level(s) and\n the output is a DataFrame.\n\n Parameters\n ----------\n level : int, str, list, default -1\n Level(s) to stack from the column axis onto the index\n axis, defined as one index or label, or a list of indices\n or labels.\n dropna : bool, default True\n Whether to drop rows in the resulting Frame/Series with\n missing values. Stacking a column level onto the index\n axis can create combinations of index and column values\n that are missing from the original dataframe. See Examples\n section.\n\n Returns\n -------\n DataFrame or Series\n Stacked dataframe or series.\n\n See Also\n --------\n DataFrame.unstack : Unstack prescribed level(s) from index axis\n onto column axis.\n DataFrame.pivot : Reshape dataframe from long format to wide\n format.\n DataFrame.pivot_table : Create a spreadsheet-style pivot table\n as a DataFrame.\n\n Notes\n -----\n The function is named by analogy with a collection of books\n being reorganized from being side by side on a horizontal\n position (the columns of the dataframe) to being stacked\n vertically on top of each other (in the index of the\n dataframe).\n\n Examples\n --------\n **Single level columns**\n\n >>> df_single_level_cols = pd.DataFrame([[0, 1], [2, 3]],\n ... index=['cat', 'dog'],\n ... columns=['weight', 'height'])\n\n Stacking a dataframe with a single level column axis returns a Series:\n\n >>> df_single_level_cols\n weight height\n cat 0 1\n dog 2 3\n >>> df_single_level_cols.stack()\n cat weight 0\n height 1\n dog weight 2\n height 3\n dtype: int64\n\n **Multi level columns: simple case**\n\n >>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n ... ('weight', 'pounds')])\n >>> df_multi_level_cols1 = pd.DataFrame([[1, 2], [2, 4]],\n ... index=['cat', 'dog'],\n ... columns=multicol1)\n\n Stacking a dataframe with a multi-level column axis:\n\n >>> df_multi_level_cols1\n weight\n kg pounds\n cat 1 2\n dog 2 4\n >>> df_multi_level_cols1.stack()\n weight\n cat kg 1\n pounds 2\n dog kg 2\n pounds 4\n\n **Missing values**\n\n >>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),\n ... ('height', 'm')])\n >>> df_multi_level_cols2 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]],\n ... index=['cat', 'dog'],\n ... columns=multicol2)\n\n It is common to have missing values when stacking a dataframe\n with multi-level columns, as the stacked dataframe typically\n has more values than the original dataframe. Missing values\n are filled with NaNs:\n\n >>> df_multi_level_cols2\n weight height\n kg m\n cat 1.0 2.0\n dog 3.0 4.0\n >>> df_multi_level_cols2.stack()\n height weight\n cat kg NaN 1.0\n m 2.0 NaN\n dog kg NaN 3.0\n m 4.0 NaN\n\n **Prescribing the level(s) to be stacked**\n\n The first parameter controls which level or levels are stacked:\n\n >>> df_multi_level_cols2.stack(0)\n kg m\n cat height NaN 2.0\n weight 1.0 NaN\n dog height NaN 4.0\n weight 3.0 NaN\n >>> df_multi_level_cols2.stack([0, 1])\n cat height m 2.0\n weight kg 1.0\n dog height m 4.0\n weight kg 3.0\n dtype: float64\n\n **Dropping missing values**\n\n >>> df_multi_level_cols3 = pd.DataFrame([[None, 1.0], [2.0, 3.0]],\n ... index=['cat', 'dog'],\n ... columns=multicol2)\n\n Note that rows where all values are missing are dropped by\n default but this behaviour can be controlled via the dropna\n keyword parameter:\n\n >>> df_multi_level_cols3\n weight height\n kg m\n cat NaN 1.0\n dog 2.0 3.0\n >>> df_multi_level_cols3.stack(dropna=False)\n height weight\n cat kg NaN NaN\n m 1.0 NaN\n dog kg NaN 2.0\n m 3.0 NaN\n >>> df_multi_level_cols3.stack(dropna=True)\n height weight\n cat m 1.0 NaN\n dog kg NaN 2.0\n m 3.0 NaN\n \"\"\"\n from pandas.core.reshape.reshape import stack, stack_multiple\n\n if isinstance(level, (tuple, list)):\n result = stack_multiple(self, level, dropna=dropna)\n else:\n result = stack(self, level, dropna=dropna)\n\n return result.__finalize__(self, method=\"stack\")\n\n def explode(\n self, column: Union[str, Tuple], ignore_index: bool = False\n ) -> DataFrame:\n \"\"\"\n Transform each element of a list-like to a row, replicating index values.\n\n .. versionadded:: 0.25.0\n\n Parameters\n ----------\n column : str or tuple\n Column to explode.\n ignore_index : bool, default False\n If True, the resulting index will be labeled 0, 1, …, n - 1.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n DataFrame\n Exploded lists to rows of the subset columns;\n index will be duplicated for these rows.\n\n Raises\n ------\n ValueError :\n if columns of the frame are not unique.\n\n See Also\n --------\n DataFrame.unstack : Pivot a level of the (necessarily hierarchical)\n index labels.\n DataFrame.melt : Unpivot a DataFrame from wide format to long format.\n Series.explode : Explode a DataFrame from list-like columns to long format.\n\n Notes\n -----\n This routine will explode list-likes including lists, tuples, sets,\n Series, and np.ndarray. The result dtype of the subset rows will\n be object. Scalars will be returned unchanged, and empty list-likes will\n result in a np.nan for that row. In addition, the ordering of rows in the\n output will be non-deterministic when exploding sets.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [[1, 2, 3], 'foo', [], [3, 4]], 'B': 1})\n >>> df\n A B\n 0 [1, 2, 3] 1\n 1 foo 1\n 2 [] 1\n 3 [3, 4] 1\n\n >>> df.explode('A')\n A B\n 0 1 1\n 0 2 1\n 0 3 1\n 1 foo 1\n 2 NaN 1\n 3 3 1\n 3 4 1\n \"\"\"\n if not (is_scalar(column) or isinstance(column, tuple)):\n raise ValueError(\"column must be a scalar\")\n if not self.columns.is_unique:\n raise ValueError(\"columns must be unique\")\n\n df = self.reset_index(drop=True)\n result = df[column].explode()\n result = df.drop([column], axis=1).join(result)\n if ignore_index:\n result.index = ibase.default_index(len(result))\n else:\n result.index = self.index.take(result.index)\n result = result.reindex(columns=self.columns, copy=False)\n\n return result\n\n def unstack(self, level=-1, fill_value=None):\n \"\"\"\n Pivot a level of the (necessarily hierarchical) index labels.\n\n Returns a DataFrame having a new level of column labels whose inner-most level\n consists of the pivoted index labels.\n\n If the index is not a MultiIndex, the output will be a Series\n (the analogue of stack when the columns are not a MultiIndex).\n\n Parameters\n ----------\n level : int, str, or list of these, default -1 (last level)\n Level(s) of index to unstack, can pass level name.\n fill_value : int, str or dict\n Replace NaN with this value if the unstack produces missing values.\n\n Returns\n -------\n Series or DataFrame\n\n See Also\n --------\n DataFrame.pivot : Pivot a table based on column values.\n DataFrame.stack : Pivot a level of the column labels (inverse operation\n from `unstack`).\n\n Examples\n --------\n >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),\n ... ('two', 'a'), ('two', 'b')])\n >>> s = pd.Series(np.arange(1.0, 5.0), index=index)\n >>> s\n one a 1.0\n b 2.0\n two a 3.0\n b 4.0\n dtype: float64\n\n >>> s.unstack(level=-1)\n a b\n one 1.0 2.0\n two 3.0 4.0\n\n >>> s.unstack(level=0)\n one two\n a 1.0 3.0\n b 2.0 4.0\n\n >>> df = s.unstack(level=0)\n >>> df.unstack()\n one a 1.0\n b 2.0\n two a 3.0\n b 4.0\n dtype: float64\n \"\"\"\n from pandas.core.reshape.reshape import unstack\n\n result = unstack(self, level, fill_value)\n\n return result.__finalize__(self, method=\"unstack\")\n\n @Appender(_shared_docs[\"melt\"] % {\"caller\": \"df.melt(\", \"other\": \"melt\"})\n def melt(\n self,\n id_vars=None,\n value_vars=None,\n var_name=None,\n value_name=\"value\",\n col_level=None,\n ignore_index=True,\n ) -> DataFrame:\n\n return melt(\n self,\n id_vars=id_vars,\n value_vars=value_vars,\n var_name=var_name,\n value_name=value_name,\n col_level=col_level,\n ignore_index=ignore_index,\n )\n\n # ----------------------------------------------------------------------\n # Time series-related\n\n @doc(\n Series.diff,\n klass=\"Dataframe\",\n extra_params=\"axis : {0 or 'index', 1 or 'columns'}, default 0\\n \"\n \"Take difference over rows (0) or columns (1).\\n\",\n other_klass=\"Series\",\n examples=dedent(\n \"\"\"\n Difference with previous row\n\n >>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],\n ... 'b': [1, 1, 2, 3, 5, 8],\n ... 'c': [1, 4, 9, 16, 25, 36]})\n >>> df\n a b c\n 0 1 1 1\n 1 2 1 4\n 2 3 2 9\n 3 4 3 16\n 4 5 5 25\n 5 6 8 36\n\n >>> df.diff()\n a b c\n 0 NaN NaN NaN\n 1 1.0 0.0 3.0\n 2 1.0 1.0 5.0\n 3 1.0 1.0 7.0\n 4 1.0 2.0 9.0\n 5 1.0 3.0 11.0\n\n Difference with previous column\n\n >>> df.diff(axis=1)\n a b c\n 0 NaN 0 0\n 1 NaN -1 3\n 2 NaN -1 7\n 3 NaN -1 13\n 4 NaN 0 20\n 5 NaN 2 28\n\n Difference with 3rd previous row\n\n >>> df.diff(periods=3)\n a b c\n 0 NaN NaN NaN\n 1 NaN NaN NaN\n 2 NaN NaN NaN\n 3 3.0 2.0 15.0\n 4 3.0 4.0 21.0\n 5 3.0 6.0 27.0\n\n Difference with following row\n\n >>> df.diff(periods=-1)\n a b c\n 0 -1.0 0.0 -3.0\n 1 -1.0 -1.0 -5.0\n 2 -1.0 -1.0 -7.0\n 3 -1.0 -2.0 -9.0\n 4 -1.0 -3.0 -11.0\n 5 NaN NaN NaN\n\n Overflow in input dtype\n\n >>> df = pd.DataFrame({'a': [1, 0]}, dtype=np.uint8)\n >>> df.diff()\n a\n 0 NaN\n 1 255.0\"\"\"\n ),\n )\n def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:\n if not isinstance(periods, int):\n if not (is_float(periods) and periods.is_integer()):\n raise ValueError(\"periods must be an integer\")\n periods = int(periods)\n\n bm_axis = self._get_block_manager_axis(axis)\n\n if bm_axis == 0 and periods != 0:\n return self - self.shift(periods, axis=axis)\n\n new_data = self._mgr.diff(n=periods, axis=bm_axis)\n return self._constructor(new_data).__finalize__(self, \"diff\")\n\n # ----------------------------------------------------------------------\n # Function application\n\n def _gotitem(\n self,\n key: Union[Label, List[Label]],\n ndim: int,\n subset: Optional[FrameOrSeriesUnion] = None,\n ) -> FrameOrSeriesUnion:\n \"\"\"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n \"\"\"\n if subset is None:\n subset = self\n elif subset.ndim == 1: # is Series\n return subset\n\n # TODO: _shallow_copy(subset)?\n return subset[key]\n\n _agg_summary_and_see_also_doc = dedent(\n \"\"\"\n The aggregation operations are always performed over an axis, either the\n index (default) or the column axis. This behavior is different from\n `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,\n `var`), where the default is to compute the aggregation of the flattened\n array, e.g., ``numpy.mean(arr_2d)`` as opposed to\n ``numpy.mean(arr_2d, axis=0)``.\n\n `agg` is an alias for `aggregate`. Use the alias.\n\n See Also\n --------\n DataFrame.apply : Perform any type of operations.\n DataFrame.transform : Perform transformation type operations.\n core.groupby.GroupBy : Perform operations over groups.\n core.resample.Resampler : Perform operations over resampled bins.\n core.window.Rolling : Perform operations over rolling window.\n core.window.Expanding : Perform operations over expanding window.\n core.window.ExponentialMovingWindow : Perform operation over exponential weighted\n window.\n \"\"\"\n )\n\n _agg_examples_doc = dedent(\n \"\"\"\n Examples\n --------\n >>> df = pd.DataFrame([[1, 2, 3],\n ... [4, 5, 6],\n ... [7, 8, 9],\n ... [np.nan, np.nan, np.nan]],\n ... columns=['A', 'B', 'C'])\n\n Aggregate these functions over the rows.\n\n >>> df.agg(['sum', 'min'])\n A B C\n sum 12.0 15.0 18.0\n min 1.0 2.0 3.0\n\n Different aggregations per column.\n\n >>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})\n A B\n sum 12.0 NaN\n min 1.0 2.0\n max NaN 8.0\n\n Aggregate different functions over the columns and rename the index of the resulting\n DataFrame.\n\n >>> df.agg(x=('A', max), y=('B', 'min'), z=('C', np.mean))\n A B C\n x 7.0 NaN NaN\n y NaN 2.0 NaN\n z NaN NaN 6.0\n\n Aggregate over the columns.\n\n >>> df.agg(\"mean\", axis=\"columns\")\n 0 2.0\n 1 5.0\n 2 8.0\n 3 NaN\n dtype: float64\n \"\"\"\n )\n\n @doc(\n _shared_docs[\"aggregate\"],\n klass=_shared_doc_kwargs[\"klass\"],\n axis=_shared_doc_kwargs[\"axis\"],\n see_also=_agg_summary_and_see_also_doc,\n examples=_agg_examples_doc,\n )\n def aggregate(self, func=None, axis=0, *args, **kwargs):\n axis = self._get_axis_number(axis)\n\n relabeling, func, columns, order = reconstruct_func(func, **kwargs)\n\n result = None\n try:\n result, how = self._aggregate(func, axis, *args, **kwargs)\n except TypeError as err:\n exc = TypeError(\n \"DataFrame constructor called with \"\n f\"incompatible data and dtype: {err}\"\n )\n raise exc from err\n if result is None:\n return self.apply(func, axis=axis, args=args, **kwargs)\n\n if relabeling:\n # This is to keep the order to columns occurrence unchanged, and also\n # keep the order of new columns occurrence unchanged\n\n # For the return values of reconstruct_func, if relabeling is\n # False, columns and order will be None.\n assert columns is not None\n assert order is not None\n\n result_in_dict = relabel_result(result, func, columns, order)\n result = DataFrame(result_in_dict, index=columns)\n\n return result\n\n def _aggregate(self, arg, axis=0, *args, **kwargs):\n if axis == 1:\n # NDFrame.aggregate returns a tuple, and we need to transpose\n # only result\n result, how = aggregate(self.T, arg, *args, **kwargs)\n result = result.T if result is not None else result\n return result, how\n return aggregate(self, arg, *args, **kwargs)\n\n agg = aggregate\n\n @doc(\n _shared_docs[\"transform\"],\n klass=_shared_doc_kwargs[\"klass\"],\n axis=_shared_doc_kwargs[\"axis\"],\n )\n def transform(\n self, func: AggFuncType, axis: Axis = 0, *args, **kwargs\n ) -> DataFrame:\n result = transform(self, func, axis, *args, **kwargs)\n assert isinstance(result, DataFrame)\n return result\n\n def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds):\n \"\"\"\n Apply a function along an axis of the DataFrame.\n\n Objects passed to the function are Series objects whose index is\n either the DataFrame's index (``axis=0``) or the DataFrame's columns\n (``axis=1``). By default (``result_type=None``), the final return type\n is inferred from the return type of the applied function. Otherwise,\n it depends on the `result_type` argument.\n\n Parameters\n ----------\n func : function\n Function to apply to each column or row.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Axis along which the function is applied:\n\n * 0 or 'index': apply function to each column.\n * 1 or 'columns': apply function to each row.\n\n raw : bool, default False\n Determines if row or column is passed as a Series or ndarray object:\n\n * ``False`` : passes each row or column as a Series to the\n function.\n * ``True`` : the passed function will receive ndarray objects\n instead.\n If you are just applying a NumPy reduction function this will\n achieve much better performance.\n\n result_type : {'expand', 'reduce', 'broadcast', None}, default None\n These only act when ``axis=1`` (columns):\n\n * 'expand' : list-like results will be turned into columns.\n * 'reduce' : returns a Series if possible rather than expanding\n list-like results. This is the opposite of 'expand'.\n * 'broadcast' : results will be broadcast to the original shape\n of the DataFrame, the original index and columns will be\n retained.\n\n The default behaviour (None) depends on the return value of the\n applied function: list-like results will be returned as a Series\n of those. However if the apply function returns a Series these\n are expanded to columns.\n args : tuple\n Positional arguments to pass to `func` in addition to the\n array/series.\n **kwds\n Additional keyword arguments to pass as keywords arguments to\n `func`.\n\n Returns\n -------\n Series or DataFrame\n Result of applying ``func`` along the given axis of the\n DataFrame.\n\n See Also\n --------\n DataFrame.applymap: For elementwise operations.\n DataFrame.aggregate: Only perform aggregating type operations.\n DataFrame.transform: Only perform transforming type operations.\n\n Examples\n --------\n >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])\n >>> df\n A B\n 0 4 9\n 1 4 9\n 2 4 9\n\n Using a numpy universal function (in this case the same as\n ``np.sqrt(df)``):\n\n >>> df.apply(np.sqrt)\n A B\n 0 2.0 3.0\n 1 2.0 3.0\n 2 2.0 3.0\n\n Using a reducing function on either axis\n\n >>> df.apply(np.sum, axis=0)\n A 12\n B 27\n dtype: int64\n\n >>> df.apply(np.sum, axis=1)\n 0 13\n 1 13\n 2 13\n dtype: int64\n\n Returning a list-like will result in a Series\n\n >>> df.apply(lambda x: [1, 2], axis=1)\n 0 [1, 2]\n 1 [1, 2]\n 2 [1, 2]\n dtype: object\n\n Passing ``result_type='expand'`` will expand list-like results\n to columns of a Dataframe\n\n >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')\n 0 1\n 0 1 2\n 1 1 2\n 2 1 2\n\n Returning a Series inside the function is similar to passing\n ``result_type='expand'``. The resulting column names\n will be the Series index.\n\n >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)\n foo bar\n 0 1 2\n 1 1 2\n 2 1 2\n\n Passing ``result_type='broadcast'`` will ensure the same shape\n result, whether list-like or scalar is returned by the function,\n and broadcast it along the axis. The resulting column names will\n be the originals.\n\n >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')\n A B\n 0 1 2\n 1 1 2\n 2 1 2\n \"\"\"\n from pandas.core.apply import frame_apply\n\n op = frame_apply(\n self,\n func=func,\n axis=axis,\n raw=raw,\n result_type=result_type,\n args=args,\n kwds=kwds,\n )\n return op.get_result()\n\n def applymap(self, func, na_action: Optional[str] = None) -> DataFrame:\n \"\"\"\n Apply a function to a Dataframe elementwise.\n\n This method applies a function that accepts and returns a scalar\n to every element of a DataFrame.\n\n Parameters\n ----------\n func : callable\n Python function, returns a single value from a single value.\n na_action : {None, 'ignore'}, default None\n If ‘ignore’, propagate NaN values, without passing them to func.\n\n .. versionadded:: 1.2\n\n Returns\n -------\n DataFrame\n Transformed DataFrame.\n\n See Also\n --------\n DataFrame.apply : Apply a function along input axis of DataFrame.\n\n Examples\n --------\n >>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])\n >>> df\n 0 1\n 0 1.000 2.120\n 1 3.356 4.567\n\n >>> df.applymap(lambda x: len(str(x)))\n 0 1\n 0 3 4\n 1 5 5\n\n Like Series.map, NA values can be ignored:\n\n >>> df_copy = df.copy()\n >>> df_copy.iloc[0, 0] = pd.NA\n >>> df_copy.applymap(lambda x: len(str(x)), na_action='ignore')\n 0 1\n 0 <NA> 4\n 1 5 5\n\n Note that a vectorized version of `func` often exists, which will\n be much faster. You could square each number elementwise.\n\n >>> df.applymap(lambda x: x**2)\n 0 1\n 0 1.000000 4.494400\n 1 11.262736 20.857489\n\n But it's better to avoid applymap in that case.\n\n >>> df ** 2\n 0 1\n 0 1.000000 4.494400\n 1 11.262736 20.857489\n \"\"\"\n if na_action not in {\"ignore\", None}:\n raise ValueError(\n f\"na_action must be 'ignore' or None. Got {repr(na_action)}\"\n )\n ignore_na = na_action == \"ignore\"\n\n # if we have a dtype == 'M8[ns]', provide boxed values\n def infer(x):\n if x.empty:\n return lib.map_infer(x, func, ignore_na=ignore_na)\n return lib.map_infer(x.astype(object)._values, func, ignore_na=ignore_na)\n\n return self.apply(infer).__finalize__(self, \"applymap\")\n\n # ----------------------------------------------------------------------\n # Merging / joining methods\n\n def append(\n self, other, ignore_index=False, verify_integrity=False, sort=False\n ) -> DataFrame:\n \"\"\"\n Append rows of `other` to the end of caller, returning a new object.\n\n Columns in `other` that are not in the caller are added as new columns.\n\n Parameters\n ----------\n other : DataFrame or Series/dict-like object, or list of these\n The data to append.\n ignore_index : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n verify_integrity : bool, default False\n If True, raise ValueError on creating index with duplicates.\n sort : bool, default False\n Sort columns if the columns of `self` and `other` are not aligned.\n\n .. versionchanged:: 1.0.0\n\n Changed to not sort by default.\n\n Returns\n -------\n DataFrame\n\n See Also\n --------\n concat : General function to concatenate DataFrame or Series objects.\n\n Notes\n -----\n If a list of dict/series is passed and the keys are all contained in\n the DataFrame's index, the order of the columns in the resulting\n DataFrame will be unchanged.\n\n Iteratively appending rows to a DataFrame can be more computationally\n intensive than a single concatenate. A better solution is to append\n those rows to a list and then concatenate the list with the original\n DataFrame all at once.\n\n Examples\n --------\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))\n >>> df\n A B\n 0 1 2\n 1 3 4\n >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))\n >>> df.append(df2)\n A B\n 0 1 2\n 1 3 4\n 0 5 6\n 1 7 8\n\n With `ignore_index` set to True:\n\n >>> df.append(df2, ignore_index=True)\n A B\n 0 1 2\n 1 3 4\n 2 5 6\n 3 7 8\n\n The following, while not recommended methods for generating DataFrames,\n show two ways to generate a DataFrame from multiple data sources.\n\n Less efficient:\n\n >>> df = pd.DataFrame(columns=['A'])\n >>> for i in range(5):\n ... df = df.append({'A': i}, ignore_index=True)\n >>> df\n A\n 0 0\n 1 1\n 2 2\n 3 3\n 4 4\n\n More efficient:\n\n >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],\n ... ignore_index=True)\n A\n 0 0\n 1 1\n 2 2\n 3 3\n 4 4\n \"\"\"\n if isinstance(other, (Series, dict)):\n if isinstance(other, dict):\n if not ignore_index:\n raise TypeError(\"Can only append a dict if ignore_index=True\")\n other = Series(other)\n if other.name is None and not ignore_index:\n raise TypeError(\n \"Can only append a Series if ignore_index=True \"\n \"or if the Series has a name\"\n )\n\n index = Index([other.name], name=self.index.name)\n idx_diff = other.index.difference(self.columns)\n try:\n combined_columns = self.columns.append(idx_diff)\n except TypeError:\n combined_columns = self.columns.astype(object).append(idx_diff)\n other = (\n other.reindex(combined_columns, copy=False)\n .to_frame()\n .T.infer_objects()\n .rename_axis(index.names, copy=False)\n )\n if not self.columns.equals(combined_columns):\n self = self.reindex(columns=combined_columns)\n elif isinstance(other, list):\n if not other:\n pass\n elif not isinstance(other[0], DataFrame):\n other = DataFrame(other)\n if (self.columns.get_indexer(other.columns) >= 0).all():\n other = other.reindex(columns=self.columns)\n\n from pandas.core.reshape.concat import concat\n\n if isinstance(other, (list, tuple)):\n to_concat = [self, *other]\n else:\n to_concat = [self, other]\n return (\n concat(\n to_concat,\n ignore_index=ignore_index,\n verify_integrity=verify_integrity,\n sort=sort,\n )\n ).__finalize__(self, method=\"append\")\n\n def join(\n self, other, on=None, how=\"left\", lsuffix=\"\", rsuffix=\"\", sort=False\n ) -> DataFrame:\n \"\"\"\n Join columns of another DataFrame.\n\n Join columns with `other` DataFrame either on index or on a key\n column. Efficiently join multiple DataFrame objects by index at once by\n passing a list.\n\n Parameters\n ----------\n other : DataFrame, Series, or list of DataFrame\n Index should be similar to one of the columns in this one. If a\n Series is passed, its name attribute must be set, and that will be\n used as the column name in the resulting joined DataFrame.\n on : str, list of str, or array-like, optional\n Column or index level name(s) in the caller to join on the index\n in `other`, otherwise joins index-on-index. If multiple\n values given, the `other` DataFrame must have a MultiIndex. Can\n pass an array as the join key if it is not already contained in\n the calling DataFrame. Like an Excel VLOOKUP operation.\n how : {'left', 'right', 'outer', 'inner'}, default 'left'\n How to handle the operation of the two objects.\n\n * left: use calling frame's index (or column if on is specified)\n * right: use `other`'s index.\n * outer: form union of calling frame's index (or column if on is\n specified) with `other`'s index, and sort it.\n lexicographically.\n * inner: form intersection of calling frame's index (or column if\n on is specified) with `other`'s index, preserving the order\n of the calling's one.\n lsuffix : str, default ''\n Suffix to use from left frame's overlapping columns.\n rsuffix : str, default ''\n Suffix to use from right frame's overlapping columns.\n sort : bool, default False\n Order result DataFrame lexicographically by the join key. If False,\n the order of the join key depends on the join type (how keyword).\n\n Returns\n -------\n DataFrame\n A dataframe containing columns from both the caller and `other`.\n\n See Also\n --------\n DataFrame.merge : For column(s)-on-column(s) operations.\n\n Notes\n -----\n Parameters `on`, `lsuffix`, and `rsuffix` are not supported when\n passing a list of `DataFrame` objects.\n\n Support for specifying index levels as the `on` parameter was added\n in version 0.23.0.\n\n Examples\n --------\n >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],\n ... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})\n\n >>> df\n key A\n 0 K0 A0\n 1 K1 A1\n 2 K2 A2\n 3 K3 A3\n 4 K4 A4\n 5 K5 A5\n\n >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],\n ... 'B': ['B0', 'B1', 'B2']})\n\n >>> other\n key B\n 0 K0 B0\n 1 K1 B1\n 2 K2 B2\n\n Join DataFrames using their indexes.\n\n >>> df.join(other, lsuffix='_caller', rsuffix='_other')\n key_caller A key_other B\n 0 K0 A0 K0 B0\n 1 K1 A1 K1 B1\n 2 K2 A2 K2 B2\n 3 K3 A3 NaN NaN\n 4 K4 A4 NaN NaN\n 5 K5 A5 NaN NaN\n\n If we want to join using the key columns, we need to set key to be\n the index in both `df` and `other`. The joined DataFrame will have\n key as its index.\n\n >>> df.set_index('key').join(other.set_index('key'))\n A B\n key\n K0 A0 B0\n K1 A1 B1\n K2 A2 B2\n K3 A3 NaN\n K4 A4 NaN\n K5 A5 NaN\n\n Another option to join using the key columns is to use the `on`\n parameter. DataFrame.join always uses `other`'s index but we can use\n any column in `df`. This method preserves the original DataFrame's\n index in the result.\n\n >>> df.join(other.set_index('key'), on='key')\n key A B\n 0 K0 A0 B0\n 1 K1 A1 B1\n 2 K2 A2 B2\n 3 K3 A3 NaN\n 4 K4 A4 NaN\n 5 K5 A5 NaN\n \"\"\"\n return self._join_compat(\n other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort\n )\n\n def _join_compat(\n self, other, on=None, how=\"left\", lsuffix=\"\", rsuffix=\"\", sort=False\n ):\n from pandas.core.reshape.concat import concat\n from pandas.core.reshape.merge import merge\n\n if isinstance(other, Series):\n if other.name is None:\n raise ValueError(\"Other Series must have a name\")\n other = DataFrame({other.name: other})\n\n if isinstance(other, DataFrame):\n if how == \"cross\":\n return merge(\n self,\n other,\n how=how,\n on=on,\n suffixes=(lsuffix, rsuffix),\n sort=sort,\n )\n return merge(\n self,\n other,\n left_on=on,\n how=how,\n left_index=on is None,\n right_index=True,\n suffixes=(lsuffix, rsuffix),\n sort=sort,\n )\n else:\n if on is not None:\n raise ValueError(\n \"Joining multiple DataFrames only supported for joining on index\"\n )\n\n frames = [self] + list(other)\n\n can_concat = all(df.index.is_unique for df in frames)\n\n # join indexes only using concat\n if can_concat:\n if how == \"left\":\n res = concat(\n frames, axis=1, join=\"outer\", verify_integrity=True, sort=sort\n )\n return res.reindex(self.index, copy=False)\n else:\n return concat(\n frames, axis=1, join=how, verify_integrity=True, sort=sort\n )\n\n joined = frames[0]\n\n for frame in frames[1:]:\n joined = merge(\n joined, frame, how=how, left_index=True, right_index=True\n )\n\n return joined\n\n @Substitution(\"\")\n @Appender(_merge_doc, indents=2)\n def merge(\n self,\n right,\n how=\"inner\",\n on=None,\n left_on=None,\n right_on=None,\n left_index=False,\n right_index=False,\n sort=False,\n suffixes=(\"_x\", \"_y\"),\n copy=True,\n indicator=False,\n validate=None,\n ) -> DataFrame:\n from pandas.core.reshape.merge import merge\n\n return merge(\n self,\n right,\n how=how,\n on=on,\n left_on=left_on,\n right_on=right_on,\n left_index=left_index,\n right_index=right_index,\n sort=sort,\n suffixes=suffixes,\n copy=copy,\n indicator=indicator,\n validate=validate,\n )\n\n def round(self, decimals=0, *args, **kwargs) -> DataFrame:\n \"\"\"\n Round a DataFrame to a variable number of decimal places.\n\n Parameters\n ----------\n decimals : int, dict, Series\n Number of decimal places to round each column to. If an int is\n given, round each column to the same number of places.\n Otherwise dict and Series round to variable numbers of places.\n Column names should be in the keys if `decimals` is a\n dict-like, or in the index if `decimals` is a Series. Any\n columns not included in `decimals` will be left as is. Elements\n of `decimals` which are not columns of the input will be\n ignored.\n *args\n Additional keywords have no effect but might be accepted for\n compatibility with numpy.\n **kwargs\n Additional keywords have no effect but might be accepted for\n compatibility with numpy.\n\n Returns\n -------\n DataFrame\n A DataFrame with the affected columns rounded to the specified\n number of decimal places.\n\n See Also\n --------\n numpy.around : Round a numpy array to the given number of decimals.\n Series.round : Round a Series to the given number of decimals.\n\n Examples\n --------\n >>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)],\n ... columns=['dogs', 'cats'])\n >>> df\n dogs cats\n 0 0.21 0.32\n 1 0.01 0.67\n 2 0.66 0.03\n 3 0.21 0.18\n\n By providing an integer each column is rounded to the same number\n of decimal places\n\n >>> df.round(1)\n dogs cats\n 0 0.2 0.3\n 1 0.0 0.7\n 2 0.7 0.0\n 3 0.2 0.2\n\n With a dict, the number of places for specific columns can be\n specified with the column names as key and the number of decimal\n places as value\n\n >>> df.round({'dogs': 1, 'cats': 0})\n dogs cats\n 0 0.2 0.0\n 1 0.0 1.0\n 2 0.7 0.0\n 3 0.2 0.0\n\n Using a Series, the number of places for specific columns can be\n specified with the column names as index and the number of\n decimal places as value\n\n >>> decimals = pd.Series([0, 1], index=['cats', 'dogs'])\n >>> df.round(decimals)\n dogs cats\n 0 0.2 0.0\n 1 0.0 1.0\n 2 0.7 0.0\n 3 0.2 0.0\n \"\"\"\n from pandas.core.reshape.concat import concat\n\n def _dict_round(df, decimals):\n for col, vals in df.items():\n try:\n yield _series_round(vals, decimals[col])\n except KeyError:\n yield vals\n\n def _series_round(s, decimals):\n if is_integer_dtype(s) or is_float_dtype(s):\n return s.round(decimals)\n return s\n\n nv.validate_round(args, kwargs)\n\n if isinstance(decimals, (dict, Series)):\n if isinstance(decimals, Series):\n if not decimals.index.is_unique:\n raise ValueError(\"Index of decimals must be unique\")\n new_cols = list(_dict_round(self, decimals))\n elif is_integer(decimals):\n # Dispatch to Series.round\n new_cols = [_series_round(v, decimals) for _, v in self.items()]\n else:\n raise TypeError(\"decimals must be an integer, a dict-like or a Series\")\n\n if len(new_cols) > 0:\n return self._constructor(\n concat(new_cols, axis=1), index=self.index, columns=self.columns\n )\n else:\n return self\n\n # ----------------------------------------------------------------------\n # Statistical methods, etc.\n\n def corr(self, method=\"pearson\", min_periods=1) -> DataFrame:\n \"\"\"\n Compute pairwise correlation of columns, excluding NA/null values.\n\n Parameters\n ----------\n method : {'pearson', 'kendall', 'spearman'} or callable\n Method of correlation:\n\n * pearson : standard correlation coefficient\n * kendall : Kendall Tau correlation coefficient\n * spearman : Spearman rank correlation\n * callable: callable with input two 1d ndarrays\n and returning a float. Note that the returned matrix from corr\n will have 1 along the diagonals and will be symmetric\n regardless of the callable's behavior.\n\n .. versionadded:: 0.24.0\n\n min_periods : int, optional\n Minimum number of observations required per pair of columns\n to have a valid result. Currently only available for Pearson\n and Spearman correlation.\n\n Returns\n -------\n DataFrame\n Correlation matrix.\n\n See Also\n --------\n DataFrame.corrwith : Compute pairwise correlation with another\n DataFrame or Series.\n Series.corr : Compute the correlation between two Series.\n\n Examples\n --------\n >>> def histogram_intersection(a, b):\n ... v = np.minimum(a, b).sum().round(decimals=1)\n ... return v\n >>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)],\n ... columns=['dogs', 'cats'])\n >>> df.corr(method=histogram_intersection)\n dogs cats\n dogs 1.0 0.3\n cats 0.3 1.0\n \"\"\"\n numeric_df = self._get_numeric_data()\n cols = numeric_df.columns\n idx = cols.copy()\n mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)\n\n if method == \"pearson\":\n correl = libalgos.nancorr(mat, minp=min_periods)\n elif method == \"spearman\":\n correl = libalgos.nancorr_spearman(mat, minp=min_periods)\n elif method == \"kendall\" or callable(method):\n if min_periods is None:\n min_periods = 1\n mat = mat.T\n corrf = nanops.get_corr_func(method)\n K = len(cols)\n correl = np.empty((K, K), dtype=float)\n mask = np.isfinite(mat)\n for i, ac in enumerate(mat):\n for j, bc in enumerate(mat):\n if i > j:\n continue\n\n valid = mask[i] & mask[j]\n if valid.sum() < min_periods:\n c = np.nan\n elif i == j:\n c = 1.0\n elif not valid.all():\n c = corrf(ac[valid], bc[valid])\n else:\n c = corrf(ac, bc)\n correl[i, j] = c\n correl[j, i] = c\n else:\n raise ValueError(\n \"method must be either 'pearson', \"\n \"'spearman', 'kendall', or a callable, \"\n f\"'{method}' was supplied\"\n )\n\n return self._constructor(correl, index=idx, columns=cols)\n\n def cov(\n self, min_periods: Optional[int] = None, ddof: Optional[int] = 1\n ) -> DataFrame:\n \"\"\"\n Compute pairwise covariance of columns, excluding NA/null values.\n\n Compute the pairwise covariance among the series of a DataFrame.\n The returned data frame is the `covariance matrix\n <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns\n of the DataFrame.\n\n Both NA and null values are automatically excluded from the\n calculation. (See the note below about bias from missing values.)\n A threshold can be set for the minimum number of\n observations for each value created. Comparisons with observations\n below this threshold will be returned as ``NaN``.\n\n This method is generally used for the analysis of time series data to\n understand the relationship between different measures\n across time.\n\n Parameters\n ----------\n min_periods : int, optional\n Minimum number of observations required per pair of columns\n to have a valid result.\n\n ddof : int, default 1\n Delta degrees of freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n DataFrame\n The covariance matrix of the series of the DataFrame.\n\n See Also\n --------\n Series.cov : Compute covariance with another Series.\n core.window.ExponentialMovingWindow.cov: Exponential weighted sample covariance.\n core.window.Expanding.cov : Expanding sample covariance.\n core.window.Rolling.cov : Rolling sample covariance.\n\n Notes\n -----\n Returns the covariance matrix of the DataFrame's time series.\n The covariance is normalized by N-ddof.\n\n For DataFrames that have Series that are missing data (assuming that\n data is `missing at random\n <https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__)\n the returned covariance matrix will be an unbiased estimate\n of the variance and covariance between the member Series.\n\n However, for many applications this estimate may not be acceptable\n because the estimate covariance matrix is not guaranteed to be positive\n semi-definite. This could lead to estimate correlations having\n absolute values which are greater than one, and/or a non-invertible\n covariance matrix. See `Estimation of covariance matrices\n <https://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_\n matrices>`__ for more details.\n\n Examples\n --------\n >>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)],\n ... columns=['dogs', 'cats'])\n >>> df.cov()\n dogs cats\n dogs 0.666667 -1.000000\n cats -1.000000 1.666667\n\n >>> np.random.seed(42)\n >>> df = pd.DataFrame(np.random.randn(1000, 5),\n ... columns=['a', 'b', 'c', 'd', 'e'])\n >>> df.cov()\n a b c d e\n a 0.998438 -0.020161 0.059277 -0.008943 0.014144\n b -0.020161 1.059352 -0.008543 -0.024738 0.009826\n c 0.059277 -0.008543 1.010670 -0.001486 -0.000271\n d -0.008943 -0.024738 -0.001486 0.921297 -0.013692\n e 0.014144 0.009826 -0.000271 -0.013692 0.977795\n\n **Minimum number of periods**\n\n This method also supports an optional ``min_periods`` keyword\n that specifies the required minimum number of non-NA observations for\n each column pair in order to have a valid result:\n\n >>> np.random.seed(42)\n >>> df = pd.DataFrame(np.random.randn(20, 3),\n ... columns=['a', 'b', 'c'])\n >>> df.loc[df.index[:5], 'a'] = np.nan\n >>> df.loc[df.index[5:10], 'b'] = np.nan\n >>> df.cov(min_periods=12)\n a b c\n a 0.316741 NaN -0.150812\n b NaN 1.248003 0.191417\n c -0.150812 0.191417 0.895202\n \"\"\"\n numeric_df = self._get_numeric_data()\n cols = numeric_df.columns\n idx = cols.copy()\n mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)\n\n if notna(mat).all():\n if min_periods is not None and min_periods > len(mat):\n base_cov = np.empty((mat.shape[1], mat.shape[1]))\n base_cov.fill(np.nan)\n else:\n base_cov = np.cov(mat.T, ddof=ddof)\n base_cov = base_cov.reshape((len(cols), len(cols)))\n else:\n base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods)\n\n return self._constructor(base_cov, index=idx, columns=cols)\n\n def corrwith(self, other, axis=0, drop=False, method=\"pearson\") -> Series:\n \"\"\"\n Compute pairwise correlation.\n\n Pairwise correlation is computed between rows or columns of\n DataFrame with rows or columns of Series or DataFrame. DataFrames\n are first aligned along both axes before computing the\n correlations.\n\n Parameters\n ----------\n other : DataFrame, Series\n Object with which to compute correlations.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to use. 0 or 'index' to compute column-wise, 1 or 'columns' for\n row-wise.\n drop : bool, default False\n Drop missing indices from result.\n method : {'pearson', 'kendall', 'spearman'} or callable\n Method of correlation:\n\n * pearson : standard correlation coefficient\n * kendall : Kendall Tau correlation coefficient\n * spearman : Spearman rank correlation\n * callable: callable with input two 1d ndarrays\n and returning a float.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n Series\n Pairwise correlations.\n\n See Also\n --------\n DataFrame.corr : Compute pairwise correlation of columns.\n \"\"\"\n axis = self._get_axis_number(axis)\n this = self._get_numeric_data()\n\n if isinstance(other, Series):\n return this.apply(lambda x: other.corr(x, method=method), axis=axis)\n\n other = other._get_numeric_data()\n left, right = this.align(other, join=\"inner\", copy=False)\n\n if axis == 1:\n left = left.T\n right = right.T\n\n if method == \"pearson\":\n # mask missing values\n left = left + right * 0\n right = right + left * 0\n\n # demeaned data\n ldem = left - left.mean()\n rdem = right - right.mean()\n\n num = (ldem * rdem).sum()\n dom = (left.count() - 1) * left.std() * right.std()\n\n correl = num / dom\n\n elif method in [\"kendall\", \"spearman\"] or callable(method):\n\n def c(x):\n return nanops.nancorr(x[0], x[1], method=method)\n\n correl = self._constructor_sliced(\n map(c, zip(left.values.T, right.values.T)), index=left.columns\n )\n\n else:\n raise ValueError(\n f\"Invalid method {method} was passed, \"\n \"valid methods are: 'pearson', 'kendall', \"\n \"'spearman', or callable\"\n )\n\n if not drop:\n # Find non-matching labels along the given axis\n # and append missing correlations (GH 22375)\n raxis = 1 if axis == 0 else 0\n result_index = this._get_axis(raxis).union(other._get_axis(raxis))\n idx_diff = result_index.difference(correl.index)\n\n if len(idx_diff) > 0:\n correl = correl.append(Series([np.nan] * len(idx_diff), index=idx_diff))\n\n return correl\n\n # ----------------------------------------------------------------------\n # ndarray-like stats methods\n\n def count(self, axis=0, level=None, numeric_only=False):\n \"\"\"\n Count non-NA cells for each column or row.\n\n The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending\n on `pandas.options.mode.use_inf_as_na`) are considered NA.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n If 0 or 'index' counts are generated for each column.\n If 1 or 'columns' counts are generated for each row.\n level : int or str, optional\n If the axis is a `MultiIndex` (hierarchical), count along a\n particular `level`, collapsing into a `DataFrame`.\n A `str` specifies the level name.\n numeric_only : bool, default False\n Include only `float`, `int` or `boolean` data.\n\n Returns\n -------\n Series or DataFrame\n For each column/row the number of non-NA/null entries.\n If `level` is specified returns a `DataFrame`.\n\n See Also\n --------\n Series.count: Number of non-NA elements in a Series.\n DataFrame.value_counts: Count unique combinations of columns.\n DataFrame.shape: Number of DataFrame rows and columns (including NA\n elements).\n DataFrame.isna: Boolean same-sized DataFrame showing places of NA\n elements.\n\n Examples\n --------\n Constructing DataFrame from a dictionary:\n\n >>> df = pd.DataFrame({\"Person\":\n ... [\"John\", \"Myla\", \"Lewis\", \"John\", \"Myla\"],\n ... \"Age\": [24., np.nan, 21., 33, 26],\n ... \"Single\": [False, True, True, True, False]})\n >>> df\n Person Age Single\n 0 John 24.0 False\n 1 Myla NaN True\n 2 Lewis 21.0 True\n 3 John 33.0 True\n 4 Myla 26.0 False\n\n Notice the uncounted NA values:\n\n >>> df.count()\n Person 5\n Age 4\n Single 5\n dtype: int64\n\n Counts for each **row**:\n\n >>> df.count(axis='columns')\n 0 3\n 1 2\n 2 3\n 3 3\n 4 3\n dtype: int64\n\n Counts for one level of a `MultiIndex`:\n\n >>> df.set_index([\"Person\", \"Single\"]).count(level=\"Person\")\n Age\n Person\n John 2\n Lewis 1\n Myla 1\n \"\"\"\n axis = self._get_axis_number(axis)\n if level is not None:\n return self._count_level(level, axis=axis, numeric_only=numeric_only)\n\n if numeric_only:\n frame = self._get_numeric_data()\n else:\n frame = self\n\n # GH #423\n if len(frame._get_axis(axis)) == 0:\n result = self._constructor_sliced(0, index=frame._get_agg_axis(axis))\n else:\n if frame._is_mixed_type or frame._mgr.any_extension_types:\n # the or any_extension_types is really only hit for single-\n # column frames with an extension array\n result = notna(frame).sum(axis=axis)\n else:\n # GH13407\n series_counts = notna(frame).sum(axis=axis)\n counts = series_counts.values\n result = self._constructor_sliced(\n counts, index=frame._get_agg_axis(axis)\n )\n\n return result.astype(\"int64\")\n\n def _count_level(self, level, axis=0, numeric_only=False):\n if numeric_only:\n frame = self._get_numeric_data()\n else:\n frame = self\n\n count_axis = frame._get_axis(axis)\n agg_axis = frame._get_agg_axis(axis)\n\n if not isinstance(count_axis, MultiIndex):\n raise TypeError(\n f\"Can only count levels on hierarchical {self._get_axis_name(axis)}.\"\n )\n\n # Mask NaNs: Mask rows or columns where the index level is NaN, and all\n # values in the DataFrame that are NaN\n if frame._is_mixed_type:\n # Since we have mixed types, calling notna(frame.values) might\n # upcast everything to object\n values_mask = notna(frame).values\n else:\n # But use the speedup when we have homogeneous dtypes\n values_mask = notna(frame.values)\n\n index_mask = notna(count_axis.get_level_values(level=level))\n if axis == 1:\n mask = index_mask & values_mask\n else:\n mask = index_mask.reshape(-1, 1) & values_mask\n\n if isinstance(level, str):\n level = count_axis._get_level_number(level)\n\n level_name = count_axis._names[level]\n level_index = count_axis.levels[level]._shallow_copy(name=level_name)\n level_codes = ensure_int64(count_axis.codes[level])\n counts = lib.count_level_2d(mask, level_codes, len(level_index), axis=axis)\n\n if axis == 1:\n result = self._constructor(counts, index=agg_axis, columns=level_index)\n else:\n result = self._constructor(counts, index=level_index, columns=agg_axis)\n\n return result\n\n def _reduce(\n self,\n op,\n name: str,\n *,\n axis=0,\n skipna=True,\n numeric_only=None,\n filter_type=None,\n **kwds,\n ):\n\n assert filter_type is None or filter_type == \"bool\", filter_type\n out_dtype = \"bool\" if filter_type == \"bool\" else None\n\n own_dtypes = [arr.dtype for arr in self._iter_column_arrays()]\n\n dtype_is_dt = np.array(\n [is_datetime64_any_dtype(dtype) for dtype in own_dtypes],\n dtype=bool,\n )\n if numeric_only is None and name in [\"mean\", \"median\"] and dtype_is_dt.any():\n warnings.warn(\n \"DataFrame.mean and DataFrame.median with numeric_only=None \"\n \"will include datetime64 and datetime64tz columns in a \"\n \"future version.\",\n FutureWarning,\n stacklevel=5,\n )\n cols = self.columns[~dtype_is_dt]\n self = self[cols]\n\n # TODO: Make other agg func handle axis=None properly GH#21597\n axis = self._get_axis_number(axis)\n labels = self._get_agg_axis(axis)\n assert axis in [0, 1]\n\n def func(values):\n if is_extension_array_dtype(values.dtype):\n return extract_array(values)._reduce(name, skipna=skipna, **kwds)\n else:\n return op(values, axis=axis, skipna=skipna, **kwds)\n\n def blk_func(values):\n if isinstance(values, ExtensionArray):\n return values._reduce(name, skipna=skipna, **kwds)\n else:\n return op(values, axis=1, skipna=skipna, **kwds)\n\n def _get_data() -> DataFrame:\n if filter_type is None:\n data = self._get_numeric_data()\n else:\n # GH#25101, GH#24434\n assert filter_type == \"bool\"\n data = self._get_bool_data()\n return data\n\n if numeric_only is not None or axis == 0:\n # For numeric_only non-None and axis non-None, we know\n # which blocks to use and no try/except is needed.\n # For numeric_only=None only the case with axis==0 and no object\n # dtypes are unambiguous can be handled with BlockManager.reduce\n # Case with EAs see GH#35881\n df = self\n if numeric_only is True:\n df = _get_data()\n if axis == 1:\n df = df.T\n axis = 0\n\n ignore_failures = numeric_only is None\n\n # After possibly _get_data and transposing, we are now in the\n # simple case where we can use BlockManager.reduce\n res, indexer = df._mgr.reduce(blk_func, ignore_failures=ignore_failures)\n out = df._constructor(res).iloc[0]\n if out_dtype is not None:\n out = out.astype(out_dtype)\n if axis == 0 and is_object_dtype(out.dtype):\n # GH#35865 careful to cast explicitly to object\n nvs = coerce_to_dtypes(out.values, df.dtypes.iloc[np.sort(indexer)])\n out[:] = np.array(nvs, dtype=object)\n if axis == 0 and len(self) == 0 and name in [\"sum\", \"prod\"]:\n # Even if we are object dtype, follow numpy and return\n # float64, see test_apply_funcs_over_empty\n out = out.astype(np.float64)\n return out\n\n assert numeric_only is None\n\n data = self\n values = data.values\n\n try:\n result = func(values)\n\n except TypeError:\n # e.g. in nanops trying to convert strs to float\n\n data = _get_data()\n labels = data._get_agg_axis(axis)\n\n values = data.values\n with np.errstate(all=\"ignore\"):\n result = func(values)\n\n if filter_type == \"bool\" and notna(result).all():\n result = result.astype(np.bool_)\n elif filter_type is None and is_object_dtype(result.dtype):\n try:\n result = result.astype(np.float64)\n except (ValueError, TypeError):\n # try to coerce to the original dtypes item by item if we can\n if axis == 0:\n result = coerce_to_dtypes(result, data.dtypes)\n\n result = self._constructor_sliced(result, index=labels)\n return result\n\n def nunique(self, axis=0, dropna=True) -> Series:\n \"\"\"\n Count distinct observations over requested axis.\n\n Return Series with number of distinct observations. Can ignore NaN\n values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for\n column-wise.\n dropna : bool, default True\n Don't include NaN in the counts.\n\n Returns\n -------\n Series\n\n See Also\n --------\n Series.nunique: Method nunique for Series.\n DataFrame.count: Count non-NA cells for each column or row.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]})\n >>> df.nunique()\n A 3\n B 1\n dtype: int64\n\n >>> df.nunique(axis=1)\n 0 1\n 1 2\n 2 2\n dtype: int64\n \"\"\"\n return self.apply(Series.nunique, axis=axis, dropna=dropna)\n\n def idxmin(self, axis=0, skipna=True) -> Series:\n \"\"\"\n Return index of first occurrence of minimum over requested axis.\n\n NA/null values are excluded.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.\n skipna : bool, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n\n Returns\n -------\n Series\n Indexes of minima along the specified axis.\n\n Raises\n ------\n ValueError\n * If the row/column is empty\n\n See Also\n --------\n Series.idxmin : Return index of the minimum element.\n\n Notes\n -----\n This method is the DataFrame version of ``ndarray.argmin``.\n\n Examples\n --------\n Consider a dataset containing food consumption in Argentina.\n\n >>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],\n ... 'co2_emissions': [37.2, 19.66, 1712]},\n ... index=['Pork', 'Wheat Products', 'Beef'])\n\n >>> df\n consumption co2_emissions\n Pork 10.51 37.20\n Wheat Products 103.11 19.66\n Beef 55.48 1712.00\n\n By default, it returns the index for the minimum value in each column.\n\n >>> df.idxmin()\n consumption Pork\n co2_emissions Wheat Products\n dtype: object\n\n To return the index for the minimum value in each row, use ``axis=\"columns\"``.\n\n >>> df.idxmin(axis=\"columns\")\n Pork consumption\n Wheat Products co2_emissions\n Beef consumption\n dtype: object\n \"\"\"\n axis = self._get_axis_number(axis)\n\n res = self._reduce(\n nanops.nanargmin, \"argmin\", axis=axis, skipna=skipna, numeric_only=False\n )\n indices = res._values\n\n # indices will always be np.ndarray since axis is not None and\n # values is a 2d array for DataFrame\n # error: Item \"int\" of \"Union[int, Any]\" has no attribute \"__iter__\"\n assert isinstance(indices, np.ndarray) # for mypy\n\n index = self._get_axis(axis)\n result = [index[i] if i >= 0 else np.nan for i in indices]\n return self._constructor_sliced(result, index=self._get_agg_axis(axis))\n\n def idxmax(self, axis=0, skipna=True) -> Series:\n \"\"\"\n Return index of first occurrence of maximum over requested axis.\n\n NA/null values are excluded.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.\n skipna : bool, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n\n Returns\n -------\n Series\n Indexes of maxima along the specified axis.\n\n Raises\n ------\n ValueError\n * If the row/column is empty\n\n See Also\n --------\n Series.idxmax : Return index of the maximum element.\n\n Notes\n -----\n This method is the DataFrame version of ``ndarray.argmax``.\n\n Examples\n --------\n Consider a dataset containing food consumption in Argentina.\n\n >>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],\n ... 'co2_emissions': [37.2, 19.66, 1712]},\n ... index=['Pork', 'Wheat Products', 'Beef'])\n\n >>> df\n consumption co2_emissions\n Pork 10.51 37.20\n Wheat Products 103.11 19.66\n Beef 55.48 1712.00\n\n By default, it returns the index for the maximum value in each column.\n\n >>> df.idxmax()\n consumption Wheat Products\n co2_emissions Beef\n dtype: object\n\n To return the index for the maximum value in each row, use ``axis=\"columns\"``.\n\n >>> df.idxmax(axis=\"columns\")\n Pork co2_emissions\n Wheat Products consumption\n Beef co2_emissions\n dtype: object\n \"\"\"\n axis = self._get_axis_number(axis)\n\n res = self._reduce(\n nanops.nanargmax, \"argmax\", axis=axis, skipna=skipna, numeric_only=False\n )\n indices = res._values\n\n # indices will always be np.ndarray since axis is not None and\n # values is a 2d array for DataFrame\n # error: Item \"int\" of \"Union[int, Any]\" has no attribute \"__iter__\"\n assert isinstance(indices, np.ndarray) # for mypy\n\n index = self._get_axis(axis)\n result = [index[i] if i >= 0 else np.nan for i in indices]\n return self._constructor_sliced(result, index=self._get_agg_axis(axis))\n\n def _get_agg_axis(self, axis_num: int) -> Index:\n \"\"\"\n Let's be explicit about this.\n \"\"\"\n if axis_num == 0:\n return self.columns\n elif axis_num == 1:\n return self.index\n else:\n raise ValueError(f\"Axis must be 0 or 1 (got {repr(axis_num)})\")\n\n def mode(self, axis=0, numeric_only=False, dropna=True) -> DataFrame:\n \"\"\"\n Get the mode(s) of each element along the selected axis.\n\n The mode of a set of values is the value that appears most often.\n It can be multiple values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to iterate over while searching for the mode:\n\n * 0 or 'index' : get mode of each column\n * 1 or 'columns' : get mode of each row.\n\n numeric_only : bool, default False\n If True, only apply to numeric columns.\n dropna : bool, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DataFrame\n The modes of each column or row.\n\n See Also\n --------\n Series.mode : Return the highest frequency value in a Series.\n Series.value_counts : Return the counts of values in a Series.\n\n Examples\n --------\n >>> df = pd.DataFrame([('bird', 2, 2),\n ... ('mammal', 4, np.nan),\n ... ('arthropod', 8, 0),\n ... ('bird', 2, np.nan)],\n ... index=('falcon', 'horse', 'spider', 'ostrich'),\n ... columns=('species', 'legs', 'wings'))\n >>> df\n species legs wings\n falcon bird 2 2.0\n horse mammal 4 NaN\n spider arthropod 8 0.0\n ostrich bird 2 NaN\n\n By default, missing values are not considered, and the mode of wings\n are both 0 and 2. Because the resulting DataFrame has two rows,\n the second row of ``species`` and ``legs`` contains ``NaN``.\n\n >>> df.mode()\n species legs wings\n 0 bird 2.0 0.0\n 1 NaN NaN 2.0\n\n Setting ``dropna=False`` ``NaN`` values are considered and they can be\n the mode (like for wings).\n\n >>> df.mode(dropna=False)\n species legs wings\n 0 bird 2 NaN\n\n Setting ``numeric_only=True``, only the mode of numeric columns is\n computed, and columns of other types are ignored.\n\n >>> df.mode(numeric_only=True)\n legs wings\n 0 2.0 0.0\n 1 NaN 2.0\n\n To compute the mode over columns and not rows, use the axis parameter:\n\n >>> df.mode(axis='columns', numeric_only=True)\n 0 1\n falcon 2.0 NaN\n horse 4.0 NaN\n spider 0.0 8.0\n ostrich 2.0 NaN\n \"\"\"\n data = self if not numeric_only else self._get_numeric_data()\n\n def f(s):\n return s.mode(dropna=dropna)\n\n return data.apply(f, axis=axis)\n\n def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation=\"linear\"):\n \"\"\"\n Return values at the given quantile over requested axis.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n Value between 0 <= q <= 1, the quantile(s) to compute.\n axis : {0, 1, 'index', 'columns'}, default 0\n Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise.\n numeric_only : bool, default True\n If False, the quantile of datetime and timedelta data will be\n computed as well.\n interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n This optional parameter specifies the interpolation method to use,\n when the desired quantile lies between two data points `i` and `j`:\n\n * linear: `i + (j - i) * fraction`, where `fraction` is the\n fractional part of the index surrounded by `i` and `j`.\n * lower: `i`.\n * higher: `j`.\n * nearest: `i` or `j` whichever is nearest.\n * midpoint: (`i` + `j`) / 2.\n\n Returns\n -------\n Series or DataFrame\n\n If ``q`` is an array, a DataFrame will be returned where the\n index is ``q``, the columns are the columns of self, and the\n values are the quantiles.\n If ``q`` is a float, a Series will be returned where the\n index is the columns of self and the values are the quantiles.\n\n See Also\n --------\n core.window.Rolling.quantile: Rolling quantile.\n numpy.percentile: Numpy function to compute the percentile.\n\n Examples\n --------\n >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),\n ... columns=['a', 'b'])\n >>> df.quantile(.1)\n a 1.3\n b 3.7\n Name: 0.1, dtype: float64\n >>> df.quantile([.1, .5])\n a b\n 0.1 1.3 3.7\n 0.5 2.5 55.0\n\n Specifying `numeric_only=False` will also compute the quantile of\n datetime and timedelta data.\n\n >>> df = pd.DataFrame({'A': [1, 2],\n ... 'B': [pd.Timestamp('2010'),\n ... pd.Timestamp('2011')],\n ... 'C': [pd.Timedelta('1 days'),\n ... pd.Timedelta('2 days')]})\n >>> df.quantile(0.5, numeric_only=False)\n A 1.5\n B 2010-07-02 12:00:00\n C 1 days 12:00:00\n Name: 0.5, dtype: object\n \"\"\"\n validate_percentile(q)\n\n data = self._get_numeric_data() if numeric_only else self\n axis = self._get_axis_number(axis)\n is_transposed = axis == 1\n\n if is_transposed:\n data = data.T\n\n if len(data.columns) == 0:\n # GH#23925 _get_numeric_data may have dropped all columns\n cols = Index([], name=self.columns.name)\n if is_list_like(q):\n return self._constructor([], index=q, columns=cols)\n return self._constructor_sliced([], index=cols, name=q, dtype=np.float64)\n\n result = data._mgr.quantile(\n qs=q, axis=1, interpolation=interpolation, transposed=is_transposed\n )\n\n if result.ndim == 2:\n result = self._constructor(result)\n else:\n result = self._constructor_sliced(result, name=q)\n\n if is_transposed:\n result = result.T\n\n return result\n\n def to_timestamp(\n self, freq=None, how: str = \"start\", axis: Axis = 0, copy: bool = True\n ) -> DataFrame:\n \"\"\"\n Cast to DatetimeIndex of timestamps, at *beginning* of period.\n\n Parameters\n ----------\n freq : str, default frequency of PeriodIndex\n Desired frequency.\n how : {'s', 'e', 'start', 'end'}\n Convention for converting period to timestamp; start of period\n vs. end.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to convert (the index by default).\n copy : bool, default True\n If False then underlying input data is not copied.\n\n Returns\n -------\n DataFrame with DatetimeIndex\n \"\"\"\n new_obj = self.copy(deep=copy)\n\n axis_name = self._get_axis_name(axis)\n old_ax = getattr(self, axis_name)\n if not isinstance(old_ax, PeriodIndex):\n raise TypeError(f\"unsupported Type {type(old_ax).__name__}\")\n\n new_ax = old_ax.to_timestamp(freq=freq, how=how)\n\n setattr(new_obj, axis_name, new_ax)\n return new_obj\n\n def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame:\n \"\"\"\n Convert DataFrame from DatetimeIndex to PeriodIndex.\n\n Convert DataFrame from DatetimeIndex to PeriodIndex with desired\n frequency (inferred from index if not passed).\n\n Parameters\n ----------\n freq : str, default\n Frequency of the PeriodIndex.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to convert (the index by default).\n copy : bool, default True\n If False then underlying input data is not copied.\n\n Returns\n -------\n DataFrame with PeriodIndex\n \"\"\"\n new_obj = self.copy(deep=copy)\n\n axis_name = self._get_axis_name(axis)\n old_ax = getattr(self, axis_name)\n if not isinstance(old_ax, DatetimeIndex):\n raise TypeError(f\"unsupported Type {type(old_ax).__name__}\")\n\n new_ax = old_ax.to_period(freq=freq)\n\n setattr(new_obj, axis_name, new_ax)\n return new_obj\n\n def isin(self, values) -> DataFrame:\n \"\"\"\n Whether each element in the DataFrame is contained in values.\n\n Parameters\n ----------\n values : iterable, Series, DataFrame or dict\n The result will only be true at a location if all the\n labels match. If `values` is a Series, that's the index. If\n `values` is a dict, the keys must be the column names,\n which must match. If `values` is a DataFrame,\n then both the index and column labels must match.\n\n Returns\n -------\n DataFrame\n DataFrame of booleans showing whether each element in the DataFrame\n is contained in values.\n\n See Also\n --------\n DataFrame.eq: Equality test for DataFrame.\n Series.isin: Equivalent method on Series.\n Series.str.contains: Test if pattern or regex is contained within a\n string of a Series or Index.\n\n Examples\n --------\n >>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},\n ... index=['falcon', 'dog'])\n >>> df\n num_legs num_wings\n falcon 2 2\n dog 4 0\n\n When ``values`` is a list check whether every value in the DataFrame\n is present in the list (which animals have 0 or 2 legs or wings)\n\n >>> df.isin([0, 2])\n num_legs num_wings\n falcon True True\n dog False True\n\n When ``values`` is a dict, we can pass values to check for each\n column separately:\n\n >>> df.isin({'num_wings': [0, 3]})\n num_legs num_wings\n falcon False False\n dog False True\n\n When ``values`` is a Series or DataFrame the index and column must\n match. Note that 'falcon' does not match based on the number of legs\n in df2.\n\n >>> other = pd.DataFrame({'num_legs': [8, 2], 'num_wings': [0, 2]},\n ... index=['spider', 'falcon'])\n >>> df.isin(other)\n num_legs num_wings\n falcon True True\n dog False False\n \"\"\"\n if isinstance(values, dict):\n from pandas.core.reshape.concat import concat\n\n values = collections.defaultdict(list, values)\n return concat(\n (\n self.iloc[:, [i]].isin(values[col])\n for i, col in enumerate(self.columns)\n ),\n axis=1,\n )\n elif isinstance(values, Series):\n if not values.index.is_unique:\n raise ValueError(\"cannot compute isin with a duplicate axis.\")\n return self.eq(values.reindex_like(self), axis=\"index\")\n elif isinstance(values, DataFrame):\n if not (values.columns.is_unique and values.index.is_unique):\n raise ValueError(\"cannot compute isin with a duplicate axis.\")\n return self.eq(values.reindex_like(self))\n else:\n if not is_list_like(values):\n raise TypeError(\n \"only list-like or dict-like objects are allowed \"\n \"to be passed to DataFrame.isin(), \"\n f\"you passed a '{type(values).__name__}'\"\n )\n return self._constructor(\n algorithms.isin(self.values.ravel(), values).reshape(self.shape),\n self.index,\n self.columns,\n )\n\n # ----------------------------------------------------------------------\n # Add index and columns\n _AXIS_ORDERS = [\"index\", \"columns\"]\n _AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {\n **NDFrame._AXIS_TO_AXIS_NUMBER,\n 1: 1,\n \"columns\": 1,\n }\n _AXIS_REVERSED = True\n _AXIS_LEN = len(_AXIS_ORDERS)\n _info_axis_number = 1\n _info_axis_name = \"columns\"\n\n index: Index = properties.AxisProperty(\n axis=1, doc=\"The index (row labels) of the DataFrame.\"\n )\n columns: Index = properties.AxisProperty(\n axis=0, doc=\"The column labels of the DataFrame.\"\n )\n\n @property\n def _AXIS_NUMBERS(self) -> Dict[str, int]:\n \"\"\".. deprecated:: 1.1.0\"\"\"\n super()._AXIS_NUMBERS\n return {\"index\": 0, \"columns\": 1}\n\n @property\n def _AXIS_NAMES(self) -> Dict[int, str]:\n \"\"\".. deprecated:: 1.1.0\"\"\"\n super()._AXIS_NAMES\n return {0: \"index\", 1: \"columns\"}\n\n # ----------------------------------------------------------------------\n # Add plotting methods to DataFrame\n plot = CachedAccessor(\"plot\", pandas.plotting.PlotAccessor)\n hist = pandas.plotting.hist_frame\n boxplot = pandas.plotting.boxplot_frame\n sparse = CachedAccessor(\"sparse\", SparseFrameAccessor)\n\n\nDataFrame._add_numeric_operations()\n\nops.add_flex_arithmetic_methods(DataFrame)\n\n\ndef _from_nested_dict(data) -> collections.defaultdict:\n new_data: collections.defaultdict = collections.defaultdict(dict)\n for index, s in data.items():\n for col, v in s.items():\n new_data[col][index] = v\n return new_data\n" ]
[ [ "pandas.util._validators.validate_bool_kwarg", "pandas.core.dtypes.cast.maybe_box_datetimelike", "pandas.core.aggregation.transform", "pandas.core.dtypes.common.infer_dtype_from_object", "pandas.core.aggregation.reconstruct_func", "numpy.where", "pandas.core.dtypes.common.is_named_tuple", "pandas._libs.algos.nancorr", "pandas.core.common.standardize_mapping", "pandas.core.dtypes.cast.maybe_convert_platform", "numpy.full", "pandas.core.internals.construction.init_dict", "pandas._libs.lib.map_infer", "pandas.core.dtypes.common.is_iterator", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.sorting.lexsort_indexer", "pandas.core.dtypes.cast.coerce_to_dtypes", "pandas.core.dtypes.common.is_list_like", "pandas.io.formats.format.DataFrameRenderer", "pandas.core.dtypes.common.is_sequence", "pandas._libs.hashtable.duplicated_int64", "pandas.core.internals.construction.masked_rec_array_to_mgr", "numpy.array", "pandas.io.formats.format.DataFrameFormatter", "pandas.core.dtypes.cast.maybe_downcast_to_dtype", "pandas.core.reshape.reshape.stack", "pandas.core.dtypes.common.is_bool_dtype", "pandas.core.computation.eval.eval", "pandas.core.ops.fill_binop", "pandas._libs.algos.nancorr_spearman", "pandas.core.dtypes.cast.find_common_type", "pandas.core.groupby.generic.DataFrameGroupBy", "pandas.core.internals.construction.arrays_to_mgr", "numpy.shape", "pandas.io.formats.style.Styler", "pandas.core.dtypes.missing.isna", "pandas.core.internals.construction.get_names_from_index", "pandas.core.generic.NDFrame.__init__", "numpy.asarray", "pandas.core.dtypes.cast.maybe_cast_to_datetime", "pandas.compat.numpy.function.validate_round", "pandas._config.get_option", "pandas.io.gbq.to_gbq", "pandas.core.internals.construction.sanitize_index", "numpy.ma.getmaskarray", "pandas.core.dtypes.cast.invalidate_string_dtypes", "pandas.core.dtypes.common.is_dataclass", "pandas.core.common.asarray_tuplesafe", "pandas.compat._optional.import_optional_dependency", "pandas.io.formats.console.in_interactive_session", "pandas.core.nanops.nancorr", "pandas.core.internals.construction.to_arrays", "pandas.core.ops.frame_arith_method_with_reindex", "pandas.core.dtypes.cast.infer_dtype_from_scalar", "pandas.compat.numpy.function.validate_transpose", "pandas.core.indexes.api.Index", "pandas.io.stata.StataWriterUTF8", "numpy.errstate", "pandas.core.dtypes.cast.maybe_infer_to_datetimelike", "pandas.util._validators.validate_axis_style_args", "numpy.rec.fromarrays", "pandas.core.dtypes.common.is_integer", "pandas.core.aggregation.aggregate", "pandas.core.aggregation.relabel_result", "pandas.core.dtypes.cast.maybe_upcast", "pandas.core.nanops.get_corr_func", "pandas.util._decorators.doc", "pandas._libs.lib.item_from_zerodim", "numpy.empty", "pandas.core.reshape.pivot.pivot_table", "pandas.util._decorators.deprecate_kwarg", "pandas.io.formats.console.get_console_size", "pandas.core.dtypes.common.is_extension_array_dtype", "pandas.core.reshape.pivot.pivot", "pandas.core.dtypes.common.is_dtype_equal", "pandas.core.dtypes.missing.notna", "pandas.core.generic.NDFrame._iset_item", "pandas.core.sorting.get_group_index", "pandas.core.ops.should_reindex_frame_op", "pandas.core.reshape.melt.melt", "pandas.util._decorators.Substitution", "pandas.core.series.Series", "pandas.core.internals.construction.init_ndarray", "pandas.core.ops.align_method_FRAME", "pandas.core.dtypes.common.ensure_int64", "pandas.core.dtypes.common.is_dict_like", "pandas.core.dtypes.common.is_integer_dtype", "pandas.util._decorators.Appender", "pandas.core.dtypes.cast.validate_numeric_casting", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.dtypes.common.is_hashable", "numpy.cov", "numpy.transpose", "numpy.iterable", "pandas._libs.properties.AxisProperty", "pandas.util._decorators.rewrite_axis_style_signature", "pandas.core.ops.add_flex_arithmetic_methods", "pandas.core.algorithms.SelectNFrame", "pandas.core.sorting.nargsort", "pandas.core.common.is_bool_indexer", "pandas.core.dtypes.common.is_scalar", "pandas.core.accessor.CachedAccessor", "pandas.core.indexes.api.ensure_index", "pandas.core.dtypes.cast.maybe_casted_values", "pandas.core.ops.get_array_op", "pandas.util._validators.validate_percentile", "numpy.dot", "pandas.core.indexes.multi.maybe_droplevels", "pandas.core.computation.expressions.where", "pandas.core.generic.NDFrame._set_item", "pandas.io.formats.info.DataFrameInfo", "pandas.core.indexing.check_bool_indexer", "pandas.io.common.get_handle", "pandas.io.parquet.to_parquet", "pandas.core.reshape.reshape.stack_multiple", "pandas.core.dtypes.common.is_float", "pandas.core.apply.frame_apply", "pandas.core.indexes.api.ensure_index_from_sequences", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas.core.indexing.convert_to_index_sliceable", "pandas.option_context", "pandas.core.dtypes.common.ensure_platform_int", "pandas.core.reshape.concat.concat", "pandas.core.algorithms.take_2d_multi", "pandas.core.reshape.reshape.unstack", "pandas.core.internals.construction.dataclasses_to_dicts", "numpy.isfinite", "pandas.io.formats.console.in_ipython_frontend", "numpy.compress", "numpy.sort", "pandas.core.reshape.merge.merge", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.indexes.multi.MultiIndex.from_arrays", "pandas.core.common.apply_if_callable", "pandas._libs.lib.maybe_convert_objects", "pandas.io.feather_format.to_feather", "pandas.core.internals.construction.reorder_arrays", "pandas.core.construction.extract_array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.0", "1.2" ], "scipy": [], "tensorflow": [] } ]
gwtaylor/pyautodiff
[ "7973e26f1c233570ed4bb10d08634ec7378e2152" ]
[ "autodiff/examples/svm.py" ]
[ "\"\"\"\nLinear SVM\n==========\n\nThis script fits a linear support vector machine classifier to random data. It\nillustrates how a function defined purely by NumPy operations can be minimized\ndirectly with a gradient-based solver.\n\n\"\"\"\nimport numpy as np\nfrom autodiff.optimize import fmin_l_bfgs_b\n\n\ndef test_svm():\n rng = np.random.RandomState(1)\n\n # -- create some fake data\n x = rng.rand(10, 5)\n y = 2 * (rng.rand(10) > 0.5) - 1\n l2_regularization = 1e-4\n\n # -- loss function\n def loss_fn(weights, bias):\n margin = y * (np.dot(x, weights) + bias)\n loss = np.maximum(0, 1 - margin) ** 2\n l2_cost = 0.5 * l2_regularization * np.dot(weights, weights)\n loss = np.mean(loss) + l2_cost\n print('ran loss_fn(), returning {}'.format(loss))\n return loss\n\n # -- call optimizer\n w_0, b_0 = np.zeros(5), np.zeros(())\n w, b = fmin_l_bfgs_b(loss_fn, init_args=(w_0, b_0))\n\n final_loss = loss_fn(w, b)\n\n assert np.allclose(final_loss, 0.7229)\n\n print('optimization successful!')\n\n\nif __name__ == '__main__':\n test_svm()\n" ]
[ [ "numpy.dot", "numpy.maximum", "numpy.allclose", "numpy.mean", "numpy.random.RandomState", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hz-ants/CDPN-source-
[ "625f9a80858f8a2fb9e74f88ea83073495141693" ]
[ "lib/models/resnet_trans_head.py" ]
[ "import torch.nn as nn\nimport torch\n\nclass TransHeadNet(nn.Module):\n def __init__(self, in_channels, num_layers=3, num_filters=256, kernel_size=3, output_dim=3, freeze=False,\n with_bias_end=True):\n super(TransHeadNet, self).__init__()\n\n self.freeze = freeze\n\n if kernel_size == 3:\n padding = 1\n elif kernel_size == 2:\n padding = 0\n\n self.features = nn.ModuleList()\n for i in range(num_layers):\n _in_channels = in_channels if i == 0 else num_filters\n self.features.append(nn.Conv2d(_in_channels, num_filters, kernel_size=kernel_size, stride=1, padding=padding, bias=False))\n self.features.append(nn.BatchNorm2d(num_filters))\n self.features.append(nn.ReLU(inplace=True))\n\n self.linears = nn.ModuleList()\n self.linears.append(nn.Linear(256 * 8 * 8, 4096))\n self.linears.append(nn.ReLU(inplace=True))\n self.linears.append(nn.Linear(4096, 4096))\n self.linears.append(nn.ReLU(inplace=True))\n self.linears.append(nn.Linear(4096, output_dim))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, mean=0, std=0.001)\n if with_bias_end and (m.bias is not None):\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.ConvTranspose2d):\n nn.init.normal_(m.weight, mean=0, std=0.001)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=0.001)\n\n def forward(self, x):\n if self.freeze:\n with torch.no_grad():\n for i, l in enumerate(self.features):\n x = l(x)\n x = x.view(-1, 256*8*8)\n for i, l in enumerate(self.linears):\n x = l(x)\n return x.detach()\n else:\n for i, l in enumerate(self.features):\n x = l(x)\n x = x.view(-1, 256*8*8)\n for i, l in enumerate(self.linears):\n x = l(x)\n return x\n\n" ]
[ [ "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.init.normal_", "torch.no_grad", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sejaldua/duolingogogo
[ "226a2a9417238f9c3f0ce738d491b58cdf4dcbdc" ]
[ "app.py" ]
[ "import streamlit as st\nimport pandas as pd\nimport yaml\nimport duolingo\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager\nfrom datetime import timezone, timedelta\nmatplotlib.rcParams['font.family'] = ['Source Han Sans CN']\n\nwith open(\"duo_credentials.yaml\", 'r') as stream:\n creds = yaml.safe_load(stream)\n\nlingo = duolingo.Duolingo(creds['username'], creds['password'])\nst.write(\"Hello :wave: \" + lingo.get_user_info()['username'])\n\nstreak = lingo.get_streak_info()\nxp = lingo.get_daily_xp_progress()\n\nst.header(\"Calendar\")\ncal = lingo.get_calendar('zs')\ncal_df = pd.DataFrame.from_records(cal)\n# creating new datetime-based features\n# cal_df['timestamp'] = cal_df['datetime'].apply(lambda x: pytz.timezone(\"America/New_York\").localize(pd.to_datetime(x, unit='ms'), is_dst=None))\ncal_df['timestamp'] = cal_df['datetime'].apply(lambda x: pd.to_datetime(x, unit='ms') - timedelta(hours=4))\ncal_df['year'] = cal_df.timestamp.dt.year\ncal_df['month'] = cal_df.timestamp.dt.month\ncal_df['hour'] = cal_df.timestamp.dt.hour\ncal_df['weekday'] = cal_df.timestamp.dt.day_name()\ncal_df['week_num'] = cal_df['timestamp'].apply(lambda x: x.isocalendar()[1] % 52)\n\n# get weekday_num in order of MTWTFSS because we want to sort the rows of the heatmap in order\nweekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\nmapping = {k: v for k, v in zip(weekday_order, [i+1 for i in range(7)])}\ncal_df['weekday_num'] = cal_df['weekday'].apply(lambda x: mapping[x])\n# st.dataframe(cal_df)\n\ndf_to_pivot = cal_df[['week_num', 'weekday_num', 'improvement']]\npivoted_data = pd.pivot_table(df_to_pivot, values='improvement', index=['weekday_num'], columns=['week_num'], aggfunc=sum)\npivoted_data = pivoted_data.reindex([i+1 for i in range(max(pivoted_data.columns))], axis=1)\npivoted_data.dropna(axis=1, how='all', inplace=True)\n# st.dataframe(pivoted_data)\n\nfig = plt.figure(figsize=(6,4));\nsns.heatmap(pivoted_data, linewidths=6, cmap='BuGn', cbar=True,\n linecolor='white', square=True, yticklabels=weekday_order);\n # xticklabels=[*space, 'Jan', *space, 'Feb', *space, 'Mar', *space, 'Apr', \n # *space, 'May', *space, 'Jun', *space, 'Jul']);\nplt.ylabel(\"\");\nplt.xlabel(\"\");\nst.write(fig)\n\n# cal_df.sort_values(by='datetime', ascending=False, inplace=True)\n# cal_df['datetime'] = cal_df['datetime'].apply(lambda x: pd.to_datetime(x, unit='ms').date())\n# fig = plt.figure(figsize=(10,6))\n# ax = sns.barplot(data=cal_df, x='datetime', y='improvement', estimator=sum, ci=None)\n# st.write(fig)\n\nst.header(\"Language Details\")\nld = lingo.get_language_details('Chinese')\nlp = lingo.get_language_progress('zs')\nst.write(\"Streak: \", ld['streak'], \" :fire:\")\nst.write(\"Total points: \", ld['points'], \" 📈\")\nst.write(\"Skills learned: \", lp['num_skills_learned'], \" :seedling:\")\nst.write(\"Current level: \", ld['level'], \" 🤓\")\nst.write('Progress towards next level: ', lp['level_progress'], '/', lp['level_points'])\nst.progress(lp['level_percent'])\n\nst.header('Known Topics')\nst.write(', '.join(lingo.get_known_topics('zs')))\n\nst.header('Known Words')\nst.write(', '.join(lingo.get_known_words('zs')))\n" ]
[ [ "pandas.to_datetime", "matplotlib.pyplot.ylabel", "pandas.DataFrame.from_records", "matplotlib.pyplot.xlabel", "pandas.pivot_table", "matplotlib.pyplot.figure" ] ]
[ { "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": [] } ]
Henley13/paper_translation_factories_2020
[ "77558ed70467cf91062abf62e46c794bfbc08e4a" ]
[ "big-fish/bigfish/stack/postprocess.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nFunctions used to format and clean any intermediate results loaded in or\nreturned by a bigfish method.\n\"\"\"\n\nimport numpy as np\nfrom scipy import ndimage as ndi\n\nfrom .utils import check_array, check_parameter, get_offset_value\n\nfrom skimage.measure import regionprops, find_contours\nfrom skimage.draw import polygon_perimeter\n\n\n# ### Transcription sites ###\n\ndef remove_transcription_site(mask_nuc, spots_in_foci, foci):\n \"\"\"We define a transcription site as a foci detected in the nucleus.\n\n Parameters\n ----------\n mask_nuc : np.ndarray, bool\n Binary mask of the nuclei with shape (y, x).\n spots_in_foci : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 4).\n One coordinate per dimension (zyx coordinates) plus the index of the\n foci.\n foci : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index.\n\n Returns\n -------\n spots_in_foci_cleaned : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 4).\n One coordinate per dimension (zyx coordinates) plus the index of the\n foci. Transcription sites are removed.\n foci_cleaned : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index. Transcription sites are removed.\n\n \"\"\"\n # check parameters\n check_array(mask_nuc,\n ndim=2,\n dtype=[bool],\n allow_nan=False)\n check_array(spots_in_foci,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n check_array(foci,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n\n # remove foci inside nuclei\n mask_transcription_site = mask_nuc[foci[:, 1], foci[:, 2]]\n foci_cleaned = foci[~mask_transcription_site]\n\n # filter spots in transcription sites\n spots_to_keep = foci_cleaned[:, 4]\n mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)\n spots_in_foci_cleaned = spots_in_foci[mask_spots_to_keep]\n\n return spots_in_foci_cleaned, foci_cleaned\n\n\n# ### Cell extraction ###\n\ndef extract_spots_from_frame(spots, z_lim=None, y_lim=None, x_lim=None):\n \"\"\"Get spots coordinates within a given frame.\n\n Parameters\n ----------\n spots : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 3)\n or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus\n the index of the foci if necessary.\n z_lim : tuple[int, int]\n Minimum and maximum coordinate of the frame along the z axis.\n y_lim : tuple[int, int]\n Minimum and maximum coordinate of the frame along the y axis.\n x_lim : tuple[int, int]\n Minimum and maximum coordinate of the frame along the x axis.\n\n Returns\n -------\n extracted_spots : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 3)\n or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus\n the index of the foci if necessary.\n\n \"\"\"\n # check parameters\n check_array(spots,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n check_parameter(z_lim=(tuple, type(None)),\n y_lim=(tuple, type(None)),\n x_lim=(tuple, type(None)))\n\n # extract spots\n extracted_spots = spots.copy()\n if z_lim is not None:\n extracted_spots = extracted_spots[extracted_spots[:, 0] < z_lim[1]]\n extracted_spots = extracted_spots[z_lim[0] < extracted_spots[:, 0]]\n extracted_spots[:, 0] -= z_lim[0]\n if y_lim is not None:\n extracted_spots = extracted_spots[extracted_spots[:, 1] < y_lim[1]]\n extracted_spots = extracted_spots[y_lim[0] < extracted_spots[:, 1]]\n extracted_spots[:, 1] -= y_lim[0]\n if x_lim is not None:\n extracted_spots = extracted_spots[extracted_spots[:, 2] < x_lim[1]]\n extracted_spots = extracted_spots[x_lim[0] < extracted_spots[:, 2]]\n extracted_spots[:, 2] -= x_lim[0]\n\n return extracted_spots\n\n\ndef extract_coordinates_image(cyt_labelled, nuc_labelled, spots_out, spots_in,\n foci):\n \"\"\"Extract relevant coordinates from an image, based on segmentation and\n detection results.\n\n For each cell in an image we return the coordinates of the cytoplasm, the\n nucleus, the RNA spots and information about the detected foci. We extract\n 2-d coordinates for the cell and 3-d coordinates for the spots and foci.\n\n Parameters\n ----------\n cyt_labelled : np.ndarray, np.uint or np.int\n Labelled cytoplasms image with shape (y, x).\n nuc_labelled : np.ndarray, np.uint or np.int\n Labelled nuclei image with shape (y, x).\n spots_out : np.ndarray, np.int64\n Coordinate of the spots detected outside foci, with shape\n (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a\n default index (-1 for mRNAs spotted outside a foci).\n spots_in : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 4).\n One coordinate per dimension (zyx coordinates) plus the index of the\n foci.\n foci : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index.\n\n Returns\n -------\n results : List[(cyt_coord, nuc_coord, rna_coord, cell_foci, cell)]\n - cyt_coord : np.ndarray, np.int64\n Coordinates of the cytoplasm border with shape (nb_points, 2).\n - nuc_coord : np.ndarray, np.int64\n Coordinates of the nuclei border with shape (nb_points, 2).\n - rna_coord : np.ndarray, np.int64\n Coordinates of the RNA spots with shape (nb_spots, 4). One\n coordinate per dimension (zyx dimension), plus the index of a\n potential foci.\n - cell_foci : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index.\n - cell : Tuple[int]\n Box coordinate of the cell in the original image (min_y, min_x,\n max_y and max_x).\n\n \"\"\"\n # check parameters\n check_array(cyt_labelled,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64],\n allow_nan=True)\n check_array(nuc_labelled,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64],\n allow_nan=True)\n check_array(spots_out,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n check_array(spots_in,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n check_array(foci,\n ndim=2,\n dtype=[np.int64],\n allow_nan=False)\n\n # initialize results\n results = []\n borders = np.zeros(cyt_labelled.shape, dtype=bool)\n borders[:, 0] = True\n borders[0, :] = True\n borders[:, cyt_labelled.shape[1] - 1] = True\n borders[cyt_labelled.shape[0] - 1, :] = True\n cells = regionprops(cyt_labelled)\n for cell in cells:\n\n # get information about the cell\n label = cell.label\n (min_y, min_x, max_y, max_x) = cell.bbox\n\n # get masks of the cell\n cyt = cyt_labelled.copy()\n cyt = (cyt == label)\n nuc = nuc_labelled.copy()\n nuc = (nuc == label)\n\n # check if cell is not cropped by the borders\n if _check_cropped_cell(cyt, borders):\n continue\n\n # check if nucleus is in the cytoplasm\n if not _check_nucleus_in_cell(cyt, nuc):\n continue\n\n # get boundaries coordinates\n cyt_coord, nuc_coord = _get_boundaries_coordinates(cyt, nuc)\n\n # filter foci\n foci_cell, spots_in_foci_cell = _extract_foci(foci, spots_in, cyt)\n\n # get rna coordinates\n spots_out_foci_cell = _extract_spots_outside_foci(cyt, spots_out)\n rna_coord = np.concatenate([spots_out_foci_cell, spots_in_foci_cell],\n axis=0)\n\n # filter cell without enough spots\n if len(rna_coord) < 30:\n continue\n\n # initialize cell coordinates\n cyt_coord[:, 0] -= min_y\n cyt_coord[:, 1] -= min_x\n nuc_coord[:, 0] -= min_y\n nuc_coord[:, 1] -= min_x\n rna_coord[:, 1] -= min_y\n rna_coord[:, 2] -= min_x\n foci_cell[:, 1] -= min_y\n foci_cell[:, 2] -= min_x\n\n results.append((cyt_coord, nuc_coord, rna_coord, foci_cell, cell.bbox))\n\n return results\n\n\ndef _check_cropped_cell(cell_cyt_mask, border_frame):\n \"\"\"\n Check if a cell is cropped by the border frame.\n\n Parameters\n ----------\n cell_cyt_mask : np.ndarray, bool\n Binary mask of the cell cytoplasm.\n\n border_frame : np.ndarray, bool\n Binary mask of the border frame.\n\n Returns\n -------\n _ : bool\n True if cell is cropped.\n\n \"\"\"\n # check cell is not cropped by the borders\n crop = cell_cyt_mask & border_frame\n if np.any(crop):\n return True\n else:\n return False\n\n\ndef _check_nucleus_in_cell(cell_cyt_mask, cell_nuc_mask):\n \"\"\"\n Check if the nucleus is properly contained in the cell cytoplasm.\n\n Parameters\n ----------\n cell_cyt_mask : np.ndarray, bool\n Binary mask of the cell cytoplasm.\n\n cell_nuc_mask : np.ndarray, bool\n Binary mask of the nucleus cytoplasm.\n\n Returns\n -------\n _ : bool\n True if the nucleus is in the cell.\n\n \"\"\"\n diff = cell_cyt_mask | cell_nuc_mask\n if np.any(diff != cell_cyt_mask):\n return False\n else:\n return True\n\n\ndef _get_boundaries_coordinates(cell_cyt_mask, cell_nuc_mask):\n \"\"\"\n Find boundaries coordinates for cytoplasm and nucleus.\n\n Parameters\n ----------\n cell_cyt_mask : np.ndarray, bool\n Mask of the cell cytoplasm.\n cell_nuc_mask : np.ndarray, bool\n Mask of the cell nucleus.\n\n Returns\n -------\n cyt_coord : np.ndarray, np.int64\n Coordinates of the cytoplasm in 2-d (yx dimension).\n nuc_coord : np.ndarray, np.int64\n Coordinates of the nucleus in 2-d (yx dimension).\n\n \"\"\"\n cyt_coord = np.array([], dtype=np.int64).reshape((0, 2))\n nuc_coord = np.array([], dtype=np.int64).reshape((0, 2))\n\n # cyt coordinates\n cell_cyt_coord = find_contours(cell_cyt_mask, level=0)\n if len(cell_cyt_coord) == 0:\n pass\n elif len(cell_cyt_coord) == 1:\n cyt_coord = cell_cyt_coord[0].astype(np.int64)\n else:\n m = 0\n for coord in cell_cyt_coord:\n if len(coord) > m:\n m = len(coord)\n cyt_coord = coord.astype(np.int64)\n\n # nuc coordinates\n cell_nuc_coord = find_contours(cell_nuc_mask, level=0)\n if len(cell_nuc_coord) == 0:\n pass\n elif len(cell_nuc_coord) == 1:\n nuc_coord = cell_nuc_coord[0].astype(np.int64)\n else:\n m = 0\n for coord in cell_nuc_coord:\n if len(coord) > m:\n m = len(coord)\n nuc_coord = coord.astype(np.int64)\n\n return cyt_coord, nuc_coord\n\n\ndef _extract_foci(foci, spots_in_foci, cell_cyt_mask):\n \"\"\"\n Extract foci and related spots detected in a specific cell.\n\n Parameters\n ----------\n foci : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index.\n\n spots_in_foci : : np.ndarray, np.int64\n Coordinate of the spots detected inside foci, with shape (nb_spots, 4).\n One coordinate per dimension (zyx coordinates) plus the index of the\n foci.\n cell_cyt_mask : np.ndarray, bool\n Binary mask of the cell with shape (y, x).\n\n Returns\n -------\n spots_in_foci_cell : np.ndarray, np.int64\n Coordinate of the spots detected inside foci in the cell, with shape\n (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the\n index of the foci.\n foci_cell : np.ndarray, np.int64\n Array with shape (nb_foci, 5). One coordinate per dimension for the\n foci centroid (zyx coordinates), the number of RNAs detected in the\n foci and its index.\n\n \"\"\"\n # filter foci\n mask_foci_cell = cell_cyt_mask[foci[:, 1], foci[:, 2]]\n if mask_foci_cell.sum() == 0:\n foci_cell = np.array([], dtype=np.int64).reshape((0, 5))\n spots_in_foci_cell = np.array([], dtype=np.int64).reshape((0, 4))\n return foci_cell, spots_in_foci_cell\n\n foci_cell = foci[mask_foci_cell]\n\n # filter spots in foci\n spots_to_keep = foci_cell[:, 4]\n mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)\n spots_in_foci_cell = spots_in_foci[mask_spots_to_keep]\n\n return foci_cell, spots_in_foci_cell\n\n\ndef _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):\n \"\"\"\n Extract spots detected outside foci, in a specific cell.\n\n Parameters\n ----------\n cell_cyt_mask : np.ndarray, bool\n Binary mask of the cell with shape (y, x).\n spots_out_foci : np.ndarray, np.int64\n Coordinate of the spots detected outside foci, with shape\n (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a\n default index (-1 for mRNAs spotted outside a foci).\n\n Returns\n -------\n spots_out_foci_cell : np.ndarray, np.int64\n Coordinate of the spots detected outside foci in the cell, with shape\n (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the\n index of the foci.\n\n \"\"\"\n # get coordinates of rna outside foci\n mask_spots_to_keep = cell_cyt_mask[spots_out_foci[:, 1],\n spots_out_foci[:, 2]]\n spots_out_foci_cell = spots_out_foci[mask_spots_to_keep]\n\n return spots_out_foci_cell\n\n\n# ### Segmentation postprocessing ###\n\n# TODO add from_binary_surface_to_binary_boundaries\n\ndef center_binary_mask(cyt, nuc=None, rna=None):\n \"\"\"Center a 2-d binary mask (surface or boundaries) and pad it.\n\n One mask should be at least provided ('cyt'). If others masks are provided\n ('nuc' and 'rna'), they will be transformed like the main mask. All the\n provided masks should have the same shape. If others coordinates are\n provided, the values will be transformed, but an array of coordinates with\n the same format is returned\n\n Parameters\n ----------\n cyt : np.ndarray, np.uint or np.int or bool\n Binary image of cytoplasm with shape (y, x).\n nuc : np.ndarray, np.uint or np.int or bool\n Binary image of nucleus with shape (y, x) or array of nucleus\n coordinates with shape (nb_points, 2).\n rna : np.ndarray, np.uint or np.int or bool\n Binary image of mRNAs localization with shape (y, x) or array of mRNAs\n coordinates with shape (nb_points, 2) or (nb_points, 3).\n\n Returns\n -------\n cyt_centered : np.ndarray, np.uint or np.int or bool\n Centered binary image of cytoplasm with shape (y, x).\n nuc_centered : np.ndarray, np.uint or np.int or bool\n Centered binary image of nucleus with shape (y, x).\n rna_centered : np.ndarray, np.uint or np.int or bool\n Centered binary image of mRNAs localizations with shape (y, x).\n\n \"\"\"\n # check parameters\n check_array(cyt,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64, bool])\n if nuc is not None:\n check_array(nuc,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64, bool])\n if rna is not None:\n check_array(rna,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64, bool])\n\n # initialize parameter\n nuc_centered, rna_centered = None, None\n marge = get_offset_value()\n\n # center the binary mask of the cell\n coord = np.nonzero(cyt)\n coord = np.column_stack(coord)\n min_y, max_y = coord[:, 0].min(), coord[:, 0].max()\n min_x, max_x = coord[:, 1].min(), coord[:, 1].max()\n shape_y = max_y - min_y + 1\n shape_x = max_x - min_x + 1\n cyt_centered_shape = (shape_y + 2 * marge, shape_x + 2 * marge)\n cyt_centered = np.zeros(cyt_centered_shape, dtype=bool)\n crop = cyt[min_y:max_y + 1, min_x:max_x + 1]\n cyt_centered[marge:shape_y + marge, marge:shape_x + marge] = crop\n\n # center the binary mask of the nucleus with the same transformation\n if nuc is not None:\n if nuc.shape == 2:\n nuc_centered = nuc.copy()\n nuc_centered[:, 0] = nuc_centered[:, 0] - min_y + marge\n nuc_centered[:, 1] = nuc_centered[:, 1] - min_x + marge\n\n elif nuc.shape == cyt.shape:\n nuc_centered = np.zeros(cyt_centered_shape, dtype=bool)\n crop = nuc[min_y:max_y + 1, min_x:max_x + 1]\n nuc_centered[marge:shape_y + marge, marge:shape_x + marge] = crop\n\n else:\n raise ValueError(\"mRNAs mask should have the same shape than \"\n \"cytoplasm mask and coordinates should be in 2-d\")\n\n # center the binary mask of the mRNAs with the same transformation\n if rna is not None:\n if rna.shape[1] == 3:\n rna_centered = rna.copy()\n rna_centered[:, 1] = rna_centered[:, 1] - min_y + marge\n rna_centered[:, 2] = rna_centered[:, 2] - min_x + marge\n\n elif rna.shape[1] == 2:\n rna_centered = rna.copy()\n rna_centered[:, 0] = rna_centered[:, 0] - min_y + marge\n rna_centered[:, 1] = rna_centered[:, 1] - min_x + marge\n\n elif rna.shape == cyt.shape:\n rna_centered = np.zeros(cyt_centered_shape, dtype=bool)\n crop = rna[min_y:max_y + 1, min_x:max_x + 1]\n rna_centered[marge:shape_y + marge, marge:shape_x + marge] = crop\n\n else:\n raise ValueError(\"mRNAs mask should have the same shape than \"\n \"cytoplasm mask and coordinates should be in 2-d \"\n \"or 3-d\")\n\n return cyt_centered, nuc_centered, rna_centered\n\n\ndef from_surface_to_coord(binary_surface):\n \"\"\"Extract coordinates from a 2-d binary matrix.\n\n The resulting coordinates represent the external boundaries of the object.\n\n Parameters\n ----------\n binary_surface : np.ndarray, np.uint or np.int or bool\n Binary image with shape (y, x).\n\n Returns\n -------\n coord : np.ndarray, np.int64\n Array of boundaries coordinates with shape (nb_points, 2).\n\n \"\"\"\n # check parameters\n check_array(binary_surface,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64, bool])\n\n # from binary surface to 2D coordinates boundaries\n coord = find_contours(binary_surface, level=0)[0].astype(np.int64)\n\n return coord\n\n\ndef complete_coord_boundaries(coord):\n \"\"\"Complete a 2-d coordinates array, by generating/interpolating missing\n points.\n\n Parameters\n ----------\n coord : np.ndarray, np.int64\n Array of coordinates to complete, with shape (nb_points, 2).\n\n Returns\n -------\n coord_completed : np.ndarray, np.int64\n Completed coordinates arrays, with shape (nb_points, 2).\n\n \"\"\"\n # check parameters\n check_array(coord,\n ndim=2,\n dtype=[np.int64])\n\n # for each array in the list, complete its coordinates using the scikit\n # image method 'polygon_perimeter'\n coord_y, coord_x = polygon_perimeter(coord[:, 0], coord[:, 1])\n coord_y = coord_y[:, np.newaxis]\n coord_x = coord_x[:, np.newaxis]\n coord_completed = np.concatenate((coord_y, coord_x), axis=-1)\n\n return coord_completed\n\n\ndef _from_coord_to_boundaries(coord_cyt, coord_nuc=None, coord_rna=None):\n \"\"\"Convert 2-d coordinates to a binary matrix with the boundaries of the\n object.\n\n As we manipulate the coordinates of the external boundaries, the relative\n binary matrix has two extra pixels in each dimension. We compensate by\n reducing the marge by one in order to keep the same shape for the frame.\n If others coordinates are provided, the relative binary matrix is build\n with the same shape as the main coordinates.\n\n Parameters\n ----------\n coord_cyt : np.ndarray, np.int64\n Array of cytoplasm boundaries coordinates with shape (nb_points, 2).\n coord_nuc : np.ndarray, np.int64\n Array of nucleus boundaries coordinates with shape (nb_points, 2).\n coord_rna : np.ndarray, np.int64\n Array of mRNAs coordinates with shape (nb_points, 2) or\n (nb_points, 3).\n\n Returns\n -------\n cyt : np.ndarray, np.uint or np.int or bool\n Binary image of cytoplasm boundaries with shape (y, x).\n nuc : np.ndarray, np.uint or np.int or bool\n Binary image of nucleus boundaries with shape (y, x).\n rna : np.ndarray, np.uint or np.int or bool\n Binary image of mRNAs localizations with shape (y, x).\n\n \"\"\"\n # initialize parameter\n nuc, rna = None, None\n marge = get_offset_value()\n marge -= 1\n\n # from 2D coordinates boundaries to binary boundaries\n max_y = coord_cyt[:, 0].max()\n max_x = coord_cyt[:, 1].max()\n min_y = coord_cyt[:, 0].min()\n min_x = coord_cyt[:, 1].min()\n shape_y = max_y - min_y + 1\n shape_x = max_x - min_x + 1\n image_shape = (shape_y + 2 * marge, shape_x + 2 * marge)\n coord_cyt[:, 0] = coord_cyt[:, 0] - min_y + marge\n coord_cyt[:, 1] = coord_cyt[:, 1] - min_x + marge\n cyt = np.zeros(image_shape, dtype=bool)\n cyt[coord_cyt[:, 0], coord_cyt[:, 1]] = True\n\n # transform nucleus coordinates with the same parameters\n if coord_nuc is not None:\n nuc = np.zeros(image_shape, dtype=bool)\n coord_nuc[:, 0] = coord_nuc[:, 0] - min_y + marge\n coord_nuc[:, 1] = coord_nuc[:, 1] - min_x + marge\n nuc[coord_nuc[:, 0], coord_nuc[:, 1]] = True\n\n # transform mRNAs coordinates with the same parameters\n if coord_rna is not None:\n rna = np.zeros(image_shape, dtype=bool)\n if coord_rna.shape[1] == 3:\n coord_rna[:, 1] = coord_rna[:, 1] - min_y + marge\n coord_rna[:, 2] = coord_rna[:, 2] - min_x + marge\n rna[coord_rna[:, 1], coord_rna[:, 2]] = True\n else:\n coord_rna[:, 0] = coord_rna[:, 0] - min_y + marge\n coord_rna[:, 1] = coord_rna[:, 1] - min_x + marge\n rna[coord_rna[:, 0], coord_rna[:, 1]] = True\n\n return cyt, nuc, rna\n\n\ndef from_boundaries_to_surface(binary_boundaries):\n \"\"\"Fill in the binary matrix representing the boundaries of an object.\n\n Parameters\n ----------\n binary_boundaries : np.ndarray, np.uint or np.int or bool\n Binary image with shape (y, x).\n\n Returns\n -------\n binary_surface : np.ndarray, np.uint or np.int or bool\n Binary image with shape (y, x).\n\n \"\"\"\n # TODO check dtype input & output\n # check parameters\n check_array(binary_boundaries,\n ndim=2,\n dtype=[np.uint8, np.uint16, np.int64, bool])\n\n # from binary boundaries to binary surface\n binary_surface = ndi.binary_fill_holes(binary_boundaries)\n\n return binary_surface\n\n\ndef from_coord_to_surface(coord_cyt, coord_nuc=None, coord_rna=None):\n \"\"\"Convert 2-d coordinates to a binary matrix with the surface of the\n object.\n\n As we manipulate the coordinates of the external boundaries, the relative\n binary matrix has two extra pixels in each dimension. We compensate by\n keeping only the inside pixels of the object surface.\n If others coordinates are provided, the relative binary matrix is build\n with the same shape as the main coordinates.\n\n Parameters\n ----------\n coord_cyt : np.ndarray, np.int64\n Array of cytoplasm boundaries coordinates with shape (nb_points, 2).\n coord_nuc : np.ndarray, np.int64\n Array of nucleus boundaries coordinates with shape (nb_points, 2).\n coord_rna : np.ndarray, np.int64\n Array of mRNAs coordinates with shape (nb_points, 2) or\n (nb_points, 3).\n\n Returns\n -------\n cyt_surface : np.ndarray, np.uint or np.int or bool\n Binary image of cytoplasm surface with shape (y, x).\n nuc_surface : np.ndarray, np.uint or np.int or bool\n Binary image of nucleus surface with shape (y, x).\n rna : np.ndarray, np.uint or np.int or bool\n Binary image of mRNAs localizations with shape (y, x).\n\n \"\"\"\n # check parameters\n check_array(coord_cyt,\n ndim=2,\n dtype=[np.int64])\n if coord_nuc is not None:\n check_array(coord_nuc,\n ndim=2,\n dtype=[np.int64])\n if coord_rna is not None:\n check_array(coord_rna,\n ndim=2,\n dtype=[np.int64])\n\n # from coordinates to binary boundaries\n cyt, nuc, rna = _from_coord_to_boundaries(coord_cyt, coord_nuc, coord_rna)\n\n # from binary boundaries to binary surface\n cyt_surface = from_boundaries_to_surface(cyt)\n nuc_surface = from_boundaries_to_surface(nuc)\n\n return cyt_surface, nuc_surface, rna\n" ]
[ [ "numpy.nonzero", "numpy.concatenate", "numpy.any", "numpy.column_stack", "scipy.ndimage.binary_fill_holes", "numpy.array", "numpy.zeros", "numpy.isin" ] ]
[ { "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": [] } ]
metamoles/metamoles
[ "251de6672029566d8becf2538684c0506fc297d0" ]
[ "deprecated/code/datacleaning.py" ]
[ "#!/usr/bin/env python\nimport Bio\nfrom Bio.KEGG import REST\nfrom Bio.KEGG import Enzyme\nimport re\nfrom Bio.KEGG import Compound\n\nimport gzip\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef create_enzyme_df(path_to_file):\n \"\"\"\n input:path_to_file. file.gz format\n output:enzyme dataframe\n \"\"\"\n\n enzyme_fields = [method for method in dir(Enzyme.Record()) if not method.startswith('_')]\n data_matrix = []\n\n with gzip.open(path_to_file, 'rt') as file:\n for record in enzyme.parse(file):\n data_matrix.append([getattr(record, field) for field in enzyme_fields])\n\n enzyme_df = pd.DataFrame(data_matrix, columns=enzyme_fields)\n return enzyme_df\n\n\n\ndef get_compact_promiscuous_df(enzyme_df):\n \"\"\"\n input:enzyme dataframe (dataframe)\n output:promiscuous enzyme dataframe (dataframe)\n \"\"\"\n\n promiscuous_df = enzyme_df[[True if len(rxn) > 1 else False for rxn in enzyme_df['reaction']]]\n compact_promiscuous_df = promiscuous_df[['entry','reaction','product','substrate']]\n\n return compact_promiscuous_df\n\n\n\ndef get_reaction_list(df):\n \"\"\"\n get the list of reaction from a dataframe that contains reaction column\n input:dataframe with reaction column (df)\n output: list of reaction (list)\n \"\"\"\n reaction_list = []\n for index,row in df.iterrows():\n for reaction in row['reaction']:\n reaction_split = reaction.split(\"[RN:\")[-1]\n if reaction_split.startswith(\"R\") and not reaction_split.startswith(\"RN\"):\n for i in reaction_split[:-1].split(\" \"):\n reaction_list.append(i)\n return reaction_list\n\n\n\ndef query_reversible_reaction(reaction_list):\n \"\"\"\n get the list of reversible reaction\n input:list of reactions(list) eg)[\"R00709\"]\n output:list of reversible reactions(list) \n \"\"\"\n\n reversible_reaction = []\n for reaction in reaction_list:\n reaction_file = REST.kegg_get(reaction).read()\n for i in reaction_file.rstrip().split(\"\\n\"):\n if i.startswith(\"EQUATION\") and \"<=>\" in i:\n reversible_reaction.append(reaction)\n return reversible_reaction\n\n\n\ndef combine_substrate_product(df):\n \"\"\"\n append substrates to product column.\n should not be run multiple times. \n it will append substrates multiple times\n input:dataframe with substrate and product(df)\n output:dataframe with combined substrate and product. named under product column(df)\n \"\"\"\n\n rowindex = np.arange(0,len(df))\n df_with_ordered_index = df.set_index(rowindex)\n\n newdf = df_with_ordered_index\n \n for index,row in df_with_ordered_index.iterrows():\n productlist = row['product']\n substratelist = row['substrate']\n newdf.iloc[index,2] = productlist + substratelist \n\n return newdf[[\"entry\",\"product\"]]\n\n\n\ndef get_cofactor_list(cofactor_df,CPDcolumnname):\n \"\"\"\n <input>\n cofactor_df : cofactor dataframe(df)\n CPDcolumnname : name of CPD columnname from cofactor dataframe(str) \n <output>\n cofactor_list : list of cofactors from cofactor dataframe (list)\n \"\"\"\n\n cofactor_list = [cofactor[4:10] for cofactor in cofactor_df[CPDcolumnname]]\n return cofactor_list\n\n\ndef get_cpd_id(compound_full):\n \"\"\"\n input:compound_full = compound full name (str) eg) 'oxalureate [CPD:C00802]'\n output: cpd = cpd id (str) eg) 'C01007'\n \"\"\"\n cpd = compound_full[-7:-1]\n return cpd \n\n\n\ndef rm_cofactor_only_cpd(enzyme_df,cofactor_list,compound_columnname=\"product\",keepNA=True):\n \"\"\"\n <input>\n enzyme_df : dataframe with enzyme information. should have substrate and product combined(df)\n compound_columnname : name of the column with compounds (str)\n cofactor_list : list of cofactors to be removed (list)\n keepNA : if false, will drop the row with no compounds (boolean, default:True) \n <output>\n clean dataframe (df) \n \"\"\"\n newdf = enzyme_df.drop([\"product\"],axis=1)\n cleaned_compound_column = []\n for index,row in enzyme_df.iterrows():\n cpd_compound_list =[]\n for compound in row[compound_columnname]:\n if \"CPD\" in compound:\n onlycpd = get_cpd(compound)\n if onlycpd not in cofactor_list:\n cpd_compound_list.append(onlycpd)\n else:\n pass\n if len(cpd_compound_list)==0:\n cleaned_compound_column.append(\"NA\")\n else: \n cleaned_compound_column.append(cpd_compound_list)\n newdf['product'] = cleaned_compound_column\n\n if keepNA==False:\n newdf = newdf.loc[cleaned_df_productinList['product']!='NA']\n \n return newdf\n\n\n\ndef itemlist_eachrow(df,oldcolumnname,newcolumnname,sorting_column):\n \"\"\"\n <input>\n df: dataframe with list items in one column (dataframe)\n oldcolumnname : name of the old column to be replaced (str) eg)\"products\"\n newcolumnname : name of the new column to replace (str) eg)\"product\"\n sorting_column : name of the column to be sorted by (str) eg)\"entry\"\n\n <output>\n dataframe with each item in each row. \n \n \"\"\"\n newdf = df[oldcolumnname].\\\n apply(pd.Series).\\\n merge(df, left_index=True, right_index=True).\\\n drop([oldcolumnname],axis=1).\\\n melt(id_vars=[enzymecolumn],value_name=newcolumnname).\\\n sort_values(by=[sorting_column]).\\\n dropna().\\\n drop(columns=[\"variable\"])\n return newdf\n\n\ndef compound_records_to_df(file_path):\n \"\"\"\n Function parses all records using Biopython.Bio.KEGG.Compound parser, and returns a pandas dataframe.\n <Input>\n filepath = file path to a gzipped text file of KEGG enzyme records (str) \n <output>\n compound dataframe \n \"\"\"\n compound_fields = [method for method in dir(Compound.Record()) if not method.startswith('_')]\n data_matrix = []\n\n with gzip.open(file_path, 'rt') as file:\n for record in Compound.parse(file):\n data_matrix.append([getattr(record, field) for field in compound_fields])\n \n compound_df = pd.DataFrame(data_matrix, columns=compound_fields)\n return compound_df\n\n\n\ndef extract_PubChem_id(field):\n \"\"\"\n This function uses regular expressions to extract the PubChem compound IDs from a field in a record\n input : field \n output : pubchem_id \n \"\"\"\n\n regex = \"'PubChem', \\[\\'(\\d+)\\'\\]\\)\" # matches \"'PubChem', ['\" characters exactly, then captures any number of digits (\\d+), before another literal \"']\" character match\n ids = re.findall(regex, str(field), re.IGNORECASE)\n if len(ids) > 0:\n pubchem_id = ids[0]\n else:\n pubchem_id = ''\n \n return pubchem_id\n\n\n\n\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": [] } ]
rsuderman/iree-samples
[ "e7ba8e639c1bdd763793a6cf21930fb238607b3f", "e7ba8e639c1bdd763793a6cf21930fb238607b3f" ]
[ "tflitehub/mobilenet_quant_test.py", "tflitehub/deeplab_v3.py" ]
[ "# RUN: %PYTHON %s\n\nimport absl.testing\nimport numpy\nimport test_util\nimport urllib.request\n\nfrom PIL import Image\n\nmodel_path = \"https://tfhub.dev/tensorflow/lite-model/mobilenet_v2_1.0_224_quantized/1/default/1?lite-format=tflite\"\n\nclass MobilenetQuantTest(test_util.TFLiteModelTest):\n def __init__(self, *args, **kwargs):\n super(MobilenetQuantTest, self).__init__(model_path, *args, **kwargs)\n\n def compare_results(self, iree_results, tflite_results, details):\n super(MobilenetQuantTest, self).compare_results(iree_results, tflite_results, details)\n self.assertTrue(numpy.isclose(iree_results[0], tflite_results[0], atol=1e-6).all())\n\n def generate_inputs(self, input_details):\n img_path = \"https://github.com/google-coral/test_data/raw/master/cat.bmp\"\n local_path = \"/\".join([self.workdir, \"cat.bmp\"])\n urllib.request.urlretrieve(img_path, local_path)\n\n shape = input_details[0][\"shape\"]\n im = numpy.array(Image.open(local_path).resize((shape[1], shape[2])))\n args = [im.reshape(shape)]\n return args\n\n def test_compile_tflite(self):\n self.compile_and_execute()\n\nif __name__ == '__main__':\n absl.testing.absltest.main()\n", "# RUN: %PYTHON %s\n\nimport absl.testing\nimport numpy\nimport test_util\n\nmodel_path = \"https://tfhub.dev/tensorflow/lite-model/deeplabv3/1/metadata/2?lite-format=tflite\"\n\nclass DeepLabV3Test(test_util.TFLiteModelTest):\n def __init__(self, *args, **kwargs):\n super(DeepLabV3Test, self).__init__(model_path, *args, **kwargs)\n\n def compare_results(self, iree_results, tflite_results, details):\n super(DeepLabV3Test, self).compare_results(iree_results, tflite_results, details)\n self.assertTrue(numpy.isclose(iree_results[0], tflite_results[0], atol=1e-3).all())\n\n def test_compile_tflite(self):\n self.compile_and_execute()\n\nif __name__ == '__main__':\n absl.testing.absltest.main()\n\n" ]
[ [ "numpy.isclose" ], [ "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WyckliffeAluga/data-chronicles
[ "5219fe9cdbafb9fd7be88727483952c4c13f2790", "5219fe9cdbafb9fd7be88727483952c4c13f2790", "5219fe9cdbafb9fd7be88727483952c4c13f2790", "5219fe9cdbafb9fd7be88727483952c4c13f2790" ]
[ "Core Concepts/Deep Learning/3_RELU_activation_function.py", "Core Concepts/Dimensionality Reduction/correlations.py", "Preprocessing Structured Data/detecting-outliers.py", "Model Selection/hyperparameter-tuning.py" ]
[ "import numpy as np\n\ndef relu(input):\n '''Define your relu activation function here'''\n # Calculate the value for the output of the relu function: output\n output = max(input, 0)\n \n # Return the value just calculated\n return(output)\n\ninput_data = np.array([3,5])\n\n# Calculate node 0 value: node_0_output\nnode_0_input = (input_data * weights['node_0']).sum()\nnode_0_output = relu(node_0_input)\n\n# Calculate node 1 value: node_1_output\nnode_1_input = (input_data * weights['node_1']).sum()\nnode_1_output = relu(node_1_input)\n\n# Put node values into array: hidden_layer_outputs\nhidden_layer_outputs = np.array([node_0_output, node_1_output])\n\n# Calculate model output (do not apply relu)\nmodel_output = (hidden_layer_outputs * weights['output']).sum()\n\n# Print model output\nprint(model_output)\n", "\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# create a correlation matrix\ncorr = df.corr()\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr, dtype=bool))\n# Add the mask to the heatmap\nsns.heatmap(corr, mask=mask, cmap=cmap, center=0, linewidths=1, annot=True, fmt=\".2f\")\nplt.show()\n\n\n# removing highly correlatated features\n\n# create positive correlation matrix\ncorr_df = df.corr().abs()\n\n# create and apply mask\nmask = np.triu(np.ones_line(corr_df, dtype=bool))\n\ntri_df = corr_df.mask(mask)\n\n# find columns that meet threshold\nto_drop = [c for c in tri_df.columns if any(tri_df[c] > 0.95)]\n\n# drop the columns\nreduced_df = df.drop(to_drop, axis=1)\n", "\n# load libraries\nimport numpy as np\nfrom sklearn.covariance import EllipticEnvelope\nfrom sklearn.datasets import make_blobs\n\n# Create simulated data\nX, _ = make_blobs(n_samples = 10,\n n_features = 2,\n centers = 1,\n random_state = 1)\n\n# Replace the first observation's values with extreme values\nX[0,0] = 10000\nX[0,1] = 10000\n\n\"\"\"\nEllipticEnvelope assumes the data is normally distributed and based on that assumption “draws” an ellipse around the data,\nclassifying any observation inside the ellipse as an inlier (labeled as 1) and any observation outside the ellipse as an outlier (labeled as -1).\nA major limitation of this approach is the need to specify a contamination parameter which is the proportion of observations that are outliers,\n a value that we don’t know\n\n\"\"\"\n# Create detector\noutlier_detector = EllipticEnvelope(contamination=.1)\n\n# Fit detector\noutlier_detector.fit(X)\n\n# Predict outliers\noutlier_detector.predict(X)\n", "\n# Load libraries\nimport numpy as np\nfrom sklearn import linear_model, datasets\nfrom sklearn.model_selection import GridSearchCV\n\n# Load data\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n# Create logistic regression\nlogistic = linear_model.LogisticRegression()\n\n# Create regularization penalty space\npenalty = ['l1', 'l2']\n\n# Create regularization hyperparameter space\nC = np.logspace(0, 4, 10)\n\n# Create hyperparameter options\nhyperparameters = dict(C=C, penalty=penalty)\n\n# Create grid search using 5-fold cross validation\nclf = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0)\n\n# Fit grid search\nbest_model = clf.fit(X, y)\n\n# View best hyperparameters\nprint('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])\nprint('Best C:', best_model.best_estimator_.get_params()['C'])\n\n# Predict target vector\nbest_model.predict(X)\n" ]
[ [ "numpy.array" ], [ "matplotlib.pyplot.show", "numpy.ones_like", "numpy.ones_line" ], [ "sklearn.covariance.EllipticEnvelope", "sklearn.datasets.make_blobs" ], [ "numpy.logspace", "sklearn.model_selection.GridSearchCV", "sklearn.datasets.load_iris", "sklearn.linear_model.LogisticRegression" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cwegg/astro-dynamo
[ "024f8aad8785488e9ae3328095d3d9c53b3e31b0" ]
[ "astro_dynamo/model.py" ]
[ "import math\nfrom typing import List, Union, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom astro_dynamo.snap import SnapShot\nfrom .snaptools import align_bar\n\n\ndef _symmetrize_matrix(x, dim):\n \"\"\"Symmetrize a tensor along dimension dim\"\"\"\n return (x + x.flip(dims=[dim])) / 2\n\n\nclass DynamicalModel(nn.Module):\n \"\"\"DynamicalModels class. This containts a snapshot of the particles, the potentials\n in which they move, and the targets to which the model should be fitted.\n\n Attributes:\n snap:\n Should be a SnapShot whose masses will be optimised\n\n potentials:\n The potentials add. If self gravity is not required set self_gravity_update to None.\n If self gravity is required then the potential of the snapshot should be in potentials[0]\n and self_gravity_update represents how much to update the running average of the density on\n each iteration. Default value is 0.2 which is then exponential averages the density with timescale\n 5 snapshots(=1/0.2).\n\n targets:\n A list of targets. Running\n model = DynamicalModel(snap, potentials, targets)\n current_target_list = model()\n will provide an list of theDynamicalModelse targets evaluated with the present model. These are then\n typically combined to a loss that pytorch can optimise.\n\n Methods:\n forward()\n Computes the targets by evaluating them on the current snapshot. Can also be called as DynamicalModel()\n integrate(steps=256)\n Integrates the model forward by steps. Updates potential the density assocaiates to potential[0]\n update_potential()\n Recomputes the accelerations from potential[0]. Adjust each snapshots velocity by a factor vc_new/vc_old\n resample()\n Resamples the snapshot to equal mass particles.\n \"\"\"\n\n def __init__(self, snap, potentials, targets, self_gravity_update=0.2):\n super(DynamicalModel, self).__init__()\n self.snap = snap\n self.targets = nn.ModuleList(targets)\n self.potentials = nn.ModuleList(potentials)\n self.self_gravity_update = self_gravity_update\n\n def forward(self):\n return [target(self) for target in self.targets]\n\n def integrate(self, steps=256):\n with torch.no_grad():\n self.snap.leapfrog_steps(potentials=self.potentials, steps=steps)\n if self.self_gravity_update is not None:\n self.potentials[0].update_density(self.snap.positions,\n self.snap.masses.detach(),\n fractional_update=self.self_gravity_update)\n\n def update_potential(self, dm_potential=None, update_velocities=True):\n with torch.no_grad():\n if update_velocities:\n old_accelerations = self.snap.get_accelerations(self.potentials,\n self.snap.positions)\n old_vc = torch.sum(-old_accelerations * self.snap.positions,\n dim=-1).sqrt()\n self.potentials[0].rho = _symmetrize_matrix(\n _symmetrize_matrix(\n _symmetrize_matrix(self.potentials[0].rho, 0), 1), 2)\n self.potentials[0].grid_accelerations()\n if dm_potential is not None:\n self.potentials[1] = dm_potential\n if update_velocities:\n new_accelerations = self.snap.get_accelerations(self.potentials,\n self.snap.positions)\n new_vc = torch.sum(-new_accelerations * self.snap.positions,\n dim=-1).sqrt()\n gd = torch.isfinite(new_vc / old_vc) & (new_vc / old_vc > 0)\n self.snap.velocities[gd, :] *= (new_vc / old_vc)[gd, None]\n align_bar(self.snap)\n\n def resample(self, velocity_perturbation=0.01):\n \"\"\"Resample the model to equal mass particles.\n\n Note that the snapshot changes and so the parameters of\n the model also change in a way that any optimiser that keeps parameter-by-parameter information e.g.\n gradients must also be update.\"\"\"\n with torch.no_grad():\n self.snap = self.snap.resample(self.potentials,\n velocity_perturbation=velocity_perturbation)\n align_bar(self.snap)\n\n def vc(self, components=False, r=torch.linspace(0, 9),\n phi=torch.linspace(0, math.pi)):\n \"\"\"Returns (r,vc) the circular velocity of the model in physical units and locations at which it was evaluated.\n\n If components=True then return list containing the vc of each component, otherwise just return the total.\n r optionally specifies the physical radii at which to compute vc\n phi specifies the azimuths over which to average.\"\"\"\n phi_grid, r_grid = torch.meshgrid(phi, r)\n phi_grid, r_grid = phi_grid.flatten(), r_grid.flatten()\n pos = torch.stack((r_grid * torch.cos(phi_grid),\n r_grid * torch.sin(phi_grid), 0 * phi_grid)).t()\n pos = pos.to(device=self.d_scale.device)\n pos /= self.d_scale\n vc = []\n for potential in self.potentials:\n device = next(potential.buffers()).device\n acc = potential.get_accelerations(pos.to(device=device)).to(\n device=pos.device)\n vc += [torch.sum(-acc * pos, dim=1).sqrt().reshape(\n phi.shape + r.shape).mean(dim=0) * self.v_scale]\n if components:\n return r, vc\n else:\n total_vc = vc[0]\n for thisvc in vc[1:]:\n total_vc = (total_vc ** 2 + thisvc ** 2).sqrt()\n return r, total_vc\n\n\nclass MilkyWayModel(DynamicalModel):\n def __init__(self, snap: SnapShot, potentials: List[nn.Module],\n targets: List[nn.Module],\n self_gravity_update: Union[float, torch.Tensor] = 0.2,\n bar_angle: Union[float, torch.Tensor] = 27.,\n r_0: Union[float, torch.Tensor] = 8.2,\n z_0: Union[float, torch.Tensor] = 0.014,\n v_scale: Union[float, torch.Tensor] = 240,\n d_scale: Union[float, torch.Tensor] = 1.4,\n v_sun: Union[List[float], Tuple[float, float, float],\n torch.Tensor] = (11.1, 12.24 + 238.0, 7.25)\n ):\n super(MilkyWayModel, self).__init__(snap, potentials, targets,\n self_gravity_update)\n self.bar_angle = nn.Parameter(torch.as_tensor(bar_angle),\n requires_grad=False)\n self.r_0 = nn.Parameter(torch.as_tensor(r_0), requires_grad=False)\n self.z_0 = nn.Parameter(torch.as_tensor(z_0), requires_grad=False)\n self.v_scale = nn.Parameter(torch.as_tensor(v_scale),\n requires_grad=False)\n self.d_scale = nn.Parameter(torch.as_tensor(d_scale),\n requires_grad=False)\n self.v_sun = nn.Parameter(torch.as_tensor(v_sun), requires_grad=False)\n\n @property\n def m_scale(self) -> torch.tensor:\n G = 4.302E-3 # Gravitational constant in astronomical units\n return self.d_scale * 1e3 * self.v_scale ** 2 / G\n\n @property\n def t_scale(self) -> torch.tensor:\n \"\"\"1 iu in time in Gyr\"\"\"\n return self.d_scale / self.v_scale * 0.977813106 # note that 1km/s is almost 1kpc/Gyr\n\n @property\n def xyz(self) -> torch.tensor:\n \"\"\"Return position of particles in relative to the Sun in cartesian coordinates with units kpc\n \"\"\"\n ddtor = math.pi / 180.\n ang = self.bar_angle * ddtor\n pos = self.snap.positions\n xyz = torch.zeros_like(pos)\n inplane_gc_distance = (self.r_0 ** 2 - self.z_0 ** 2).sqrt()\n xyz[:, 0] = (pos[:, 0] * torch.cos(-ang) - pos[:, 1] * torch.sin(\n -ang)) * self.d_scale + inplane_gc_distance\n xyz[:, 1] = (pos[:, 0] * torch.sin(-ang) + pos[:, 1] * torch.cos(\n -ang)) * self.d_scale\n xyz[:, 2] = pos[:, 2] * self.d_scale - self.z_0\n return xyz\n\n @property\n def l_b_mu(self) -> torch.tensor:\n \"\"\"Return array of particles in galactic (l,b,mu) coordinates. (l,b) in degrees. mu is distance modulus\"\"\"\n xyz = self.xyz\n l_b_mu = torch.zeros_like(xyz)\n d = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2 + xyz[:, 2] ** 2).sqrt()\n l_b_mu[:, 0] = torch.atan2(xyz[:, 1], xyz[:, 0]) * 180 / math.pi\n b_offset = torch.asin(\n self.z_0 / self.r_0) # the GC has z = -z_0, rotate b coordinate so this is at l,b=(0,0)\n l_b_mu[:, 1] = (torch.asin(xyz[:, 2] / d) + b_offset) * 180 / math.pi\n l_b_mu[:, 2] = 5 * (100 * d).log10()\n return l_b_mu\n\n @property\n def masses(self) -> torch.tensor:\n return self.snap.masses * self.m_scale\n\n @property\n def omega(self) -> torch.tensor:\n return self.snap.omega * self.v_scale / self.d_scale\n\n @omega.setter\n def omega(self, omega: float):\n self.snap.omega = omega / self.v_scale * self.d_scale\n\n @property\n def uvw(self) -> torch.tensor:\n \"\"\"Return UVW velocities.\n \"\"\"\n ddtor = math.pi / 180.\n ang = self.bar_angle * ddtor\n vxyz = torch.zeros_like(self.snap.positions)\n # sun moves at Vsun[0] towards galactic center i.e. other stars are moving away towards larger x\n vel = self.snap.velocities * self.v_scale\n vxyz[:, 0] = (vel[:, 0] * torch.cos(-ang) - vel[:, 1] * torch.sin(-ang)) + self.v_sun[0]\n # sun moves at Vsun[1] in direction of rotation, other stars are going slower than (0,-Vc,0)\n vxyz[:, 1] = (vel[:, 0] * torch.sin(-ang) + vel[:, 1] * torch.cos(-ang)) - self.v_sun[1]\n # sun is moving towards ngp i.e. other stars on average move at negative vz\n vxyz[:, 2] = vel[:, 2] - self.v_sun[2]\n return vxyz\n\n @property\n def vr(self) -> torch.tensor:\n \"\"\"Return array of particles radial velocities in [km/s]\"\"\"\n xyz = self.xyz\n vxyz = self.uvw\n r = xyz.norm(dim=-1)\n vr = (xyz * vxyz).sum(dim=-1) / r\n return vr\n\n @property\n def mul_mub(self) -> torch.tensor:\n \"\"\"Return proper motions of particles in [mas/yr] in (l, b).\n Proper motion in l is (rate of change of l)*cos(b)\"\"\"\n xyz = self.xyz\n vxyz = self.uvw\n r = xyz.norm(dim=-1)\n rxy = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2).sqrt()\n # magic number comes from: 1 mas/yr = 4.74057 km/s at 1 kpc\n mul = (-vxyz[:, 0] * xyz[:, 1] / rxy + vxyz[:, 1] * xyz[:, 0] / rxy) / r / 4.74057\n mub = (-vxyz[:, 0] * xyz[:, 2] * xyz[:, 0] / rxy - vxyz[:, 1] * xyz[:, 2] * xyz[:, 1] / rxy + vxyz[:, 2] * rxy) / (\n r ** 2) / 4.74057\n return torch.stack((mul, mub), dim=-1)\n" ]
[ [ "torch.cos", "torch.linspace", "torch.sin", "torch.nn.ModuleList", "torch.zeros_like", "torch.sum", "torch.asin", "torch.isfinite", "torch.no_grad", "torch.stack", "torch.meshgrid", "torch.atan2", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HennyJie/BrainGB
[ "96cf6711e2f2e6fa48b699ce3c0d6e318955c4de" ]
[ "src/dataset/transforms.py" ]
[ "import torch\nfrom node2vec import Node2Vec as Node2Vec_\nfrom .brain_data import BrainData\nfrom torch_geometric.data import Data\nfrom networkx.convert_matrix import from_numpy_matrix\nfrom .utils import binning, LDP\nimport networkx as nx\nfrom .base_transform import BaseTransform\nfrom numpy import linalg as LA\nimport numpy as np\n\n\nclass FromSVTransform(BaseTransform):\n def __init__(self, sv_transform):\n super(FromSVTransform, self).__init__()\n self.sv_transform = sv_transform\n\n def __call__(self, data):\n keys = list(filter(lambda x: x.startswith('edge_index'), data.keys))\n for key in keys:\n if key.startswith('edge_index'):\n postfix = key[10:]\n edge_index = data[f'edge_index{postfix}']\n edge_attr = data[f'edge_attr{postfix}']\n svdata = Data(edge_index=edge_index, edge_attr=edge_attr, num_nodes=data.num_nodes)\n svdata_transformed = self.sv_transform(svdata)\n data[f'x{postfix}'] = svdata_transformed.x\n data[f'edge_index{postfix}'] = svdata_transformed.edge_index\n data[f'edge_attr{postfix}'] = svdata_transformed.edge_attr\n return data\n\n def __str__(self):\n return self.sv_transform.__class__.__name__\n\n\nclass Identity(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns a diagonal matrix with ones on the diagonal.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n data.x = torch.diag(torch.ones(data.num_nodes))\n return data\n\n\nclass Degree(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns a diagonal matrix with the degree of each node on the diagonal.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n data.x = torch.Tensor(adj.sum(dim=1, keepdim=True)).float()\n return data\n\n def __str__(self):\n return 'Degree'\n\n\nclass LDPTransform(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns node feature with LDP transform.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n data.x = torch.Tensor(\n LDP(nx.from_numpy_array(adj.numpy()))\n ).float()\n return data\n\n def __str__(self):\n return 'LDP'\n\n\nclass DegreeBin(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns node feature with degree bin transform.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n return torch.Tensor(binning(adj.sum(dim=1))).float()\n\n def __str__(self):\n return 'Degree_Bin'\n\n\nclass Adj(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns adjacency matrix.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n data.x = adj\n return data\n\n def __str__(self):\n return 'Adj'\n\n\nclass Eigenvector(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns node feature with eigenvector.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n w, v = LA.eig(adj.numpy())\n # indices = np.argsort(w)[::-1]\n v = v.transpose()\n data.x = torch.Tensor(v).float()\n return data\n\n\nclass EigenNorm(BaseTransform):\n def __call__(self, data: BrainData):\n \"\"\"\n Returns node feature with eigen norm.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n sum_of_rows = adj.sum(dim=1)\n adj /= sum_of_rows\n adj = torch.nan_to_num(adj)\n w, v = LA.eig(adj.numpy())\n # indices = np.argsort(w)[::-1]\n v = v.transpose()\n data.x = torch.Tensor(v).float()\n return data\n\n\nclass Node2Vec(BaseTransform):\n def __init__(self, feature_dim=32, walk_length=5, num_walks=200, num_workers=4,\n window=10, min_count=1, batch_words=4):\n super(Node2Vec, self).__init__()\n self.feature_dim = feature_dim\n self.walk_length = walk_length\n self.num_walks = num_walks\n self.num_workers = num_workers\n self.window = window\n self.min_count = min_count\n self.batch_words = batch_words\n\n def __call__(self, data):\n \"\"\"\n Returns node feature with node2vec transform.\n :param data: BrainData\n :return: torch.Tensor\n \"\"\"\n adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])\n adj = adj.to_dense()\n if (adj < 0).int().sum() > 0:\n # split the adjacency matrix into two (negative and positive) parts\n pos_adj = adj.clone()\n pos_adj[adj < 0] = 0\n neg_adj = adj.clone()\n neg_adj[adj > 0] = 0\n neg_adj = -neg_adj\n adjs = [pos_adj, neg_adj]\n else:\n adjs = [adj]\n\n xs = []\n for adj in adjs:\n x = torch.zeros((data.num_nodes, self.feature_dim))\n graph = from_numpy_matrix(adj.numpy())\n node2vec = Node2Vec_(graph, dimensions=self.feature_dim, walk_length=self.walk_length,\n num_walks=self.num_walks, workers=self.num_workers)\n model = node2vec.fit(window=self.window, min_count=self.min_count,\n batch_words=self.batch_words)\n for i in range(data.num_nodes):\n x[i] = torch.Tensor(model.wv[f'{i}'].copy())\n xs.append(x)\n data.x = torch.cat(xs, dim=-1)\n return data\n\n def __str__(self):\n return 'Node2Vec'\n" ]
[ [ "torch.ones", "torch.Tensor", "torch.zeros", "torch.cat", "torch.nan_to_num", "torch.sparse_coo_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
oahziur/probability
[ "ca14fa8924749593fd21e2b6389551f964527eec", "11645be43d2845da65a4fbafde4cfa95780280c0", "8edc2892658b5fac7f2e162e1abdc37d1f9858da", "ca14fa8924749593fd21e2b6389551f964527eec", "11645be43d2845da65a4fbafde4cfa95780280c0" ]
[ "tensorflow_probability/python/bijectors/tanh.py", "tensorflow_probability/python/mcmc/transformed_kernel_test.py", "tensorflow_probability/python/distributions/distribution_test.py", "tensorflow_probability/python/distributions/pareto_test.py", "tensorflow_probability/python/distributions/linear_gaussian_ssm.py" ]
[ "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tanh bijector.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow_probability.python.bijectors import bijector\n\n\n__all__ = [\n \"Tanh\",\n]\n\n\nclass Tanh(bijector.Bijector):\n \"\"\"Bijector that computes `Y = tanh(X)`, therefore `Y in (-1, 1)`.\n\n This can be achieved by an affine transform of the Sigmoid bijector, i.e.,\n it is equivalent to\n ```\n tfb.Chain([tfb.Affine(shift=-1, scale=2.),\n tfb.Sigmoid(),\n tfb.Affine(scale=2.)])\n ```\n\n However, using the `Tanh` bijector directly is slightly faster and more\n numerically stable.\n \"\"\"\n\n def __init__(self, validate_args=False, name=\"tanh\"):\n super(Tanh, self).__init__(\n forward_min_event_ndims=0,\n validate_args=validate_args,\n name=name)\n\n def _forward(self, x):\n return tf.nn.tanh(x)\n\n def _inverse(self, y):\n return tf.atanh(y)\n\n def _inverse_log_det_jacobian(self, y):\n return -tf.log1p(-tf.square(y))\n\n def _forward_log_det_jacobian(self, x):\n # This formula is mathematically equivalent to\n # `tf.log1p(-tf.square(tf.tanh(x)))`, however this code is more numerically\n # stable.\n\n # Derivation:\n # log(1 - tanh(x)^2)\n # = log(sech(x)^2)\n # = 2 * log(sech(x))\n # = 2 * log(2e^-x / (e^-2x + 1))\n # = 2 * (log(2) - x - log(e^-2x + 1))\n # = 2 * (log(2) - x - softplus(-2x))\n return 2. * (np.log(2.) - x - tf.nn.softplus(-2. * x))\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for `TransformedTransitionKernel` `TransitionKernel`.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n# Dependency imports\nimport numpy as np\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\n\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\n\nFakeInnerKernelResults = collections.namedtuple(\n 'FakeInnerKernelResults', [])\n\n\nclass FakeInnerKernel(tfp.mcmc.TransitionKernel):\n \"\"\"Fake Transition Kernel.\"\"\"\n\n def __init__(self, target_log_prob_fn):\n self._parameters = dict(target_log_prob_fn=target_log_prob_fn)\n\n @property\n def parameters(self):\n return self._parameters\n\n @property\n def is_calibrated(self):\n return True\n\n def one_step(self, current_state, previous_kernel_results):\n pass\n\n def bootstrap_results(self, init_state):\n return FakeInnerKernelResults()\n\n\nclass TransformedTransitionKernelTest(tf.test.TestCase):\n\n def setUp(self):\n self.dtype = np.float32\n\n def test_support_works_correctly_with_HMC(self):\n num_results = 2000\n with self.cached_session(graph=tf.Graph()) as sess:\n target = tfd.Beta(\n concentration1=self.dtype(1.),\n concentration0=self.dtype(10.))\n transformed_hmc = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(\n target_log_prob_fn=target.log_prob,\n step_size=1.64,\n num_leapfrog_steps=2,\n seed=55),\n bijector=tfb.Sigmoid())\n # Recall, tfp.mcmc.sample_chain calls\n # transformed_hmc.bootstrap_results too.\n states, kernel_results = tfp.mcmc.sample_chain(\n num_results=num_results,\n # The initial state is used by inner_kernel.bootstrap_results.\n # Note the input is *after* bijector.forward.\n current_state=self.dtype(0.25),\n kernel=transformed_hmc,\n num_burnin_steps=200,\n num_steps_between_results=1,\n parallel_iterations=1)\n self.assertEqual(num_results, tf.dimension_value(states.shape[0]))\n sample_mean = tf.reduce_mean(states, axis=0)\n sample_var = tf.reduce_mean(\n tf.squared_difference(states, sample_mean),\n axis=0)\n [\n sample_mean_,\n sample_var_,\n is_accepted_,\n true_mean_,\n true_var_,\n ] = sess.run([\n sample_mean,\n sample_var,\n kernel_results.inner_results.is_accepted,\n target.mean(),\n target.variance(),\n ])\n self.assertAllClose(true_mean_, sample_mean_,\n atol=0.06, rtol=0.)\n self.assertAllClose(true_var_, sample_var_,\n atol=0.01, rtol=0.1)\n self.assertNear(0.6, is_accepted_.mean(), err=0.05)\n\n def test_support_works_correctly_with_MALA(self):\n num_results = 2000\n with self.cached_session(graph=tf.Graph()) as sess:\n target = tfd.Beta(\n concentration1=self.dtype(1.),\n concentration0=self.dtype(10.))\n transformed_mala = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.MetropolisAdjustedLangevinAlgorithm(\n target_log_prob_fn=target.log_prob,\n step_size=1.,\n seed=55),\n bijector=tfb.Sigmoid())\n # Recall, tfp.mcmc.sample_chain calls\n # transformed_hmc.bootstrap_results too.\n states, _ = tfp.mcmc.sample_chain(\n num_results=num_results,\n # The initial state is used by inner_kernel.bootstrap_results.\n # Note the input is *after* bijector.forward.\n current_state=self.dtype(0.25),\n kernel=transformed_mala,\n num_burnin_steps=200,\n num_steps_between_results=1,\n parallel_iterations=1)\n self.assertEqual(num_results, tf.dimension_value(states.shape[0]))\n sample_mean = tf.reduce_mean(states, axis=0)\n sample_var = tf.reduce_mean(\n tf.squared_difference(states, sample_mean),\n axis=0)\n [\n sample_mean_,\n sample_var_,\n true_mean_,\n true_var_,\n ] = sess.run([\n sample_mean,\n sample_var,\n target.mean(),\n target.variance(),\n ])\n self.assertAllClose(true_mean_, sample_mean_,\n atol=0.06, rtol=0.)\n self.assertAllClose(true_var_, sample_var_,\n atol=0.01, rtol=0.1)\n\n def test_support_works_correctly_with_RWM(self):\n num_results = 2000\n with self.cached_session(graph=tf.Graph()) as sess:\n target = tfd.Beta(\n concentration1=self.dtype(1.),\n concentration0=self.dtype(10.))\n transformed_rwm = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.RandomWalkMetropolis(\n target_log_prob_fn=target.log_prob,\n new_state_fn=tfp.mcmc.random_walk_normal_fn(scale=1.5),\n seed=55),\n bijector=tfb.Sigmoid())\n # Recall, tfp.mcmc.sample_chain calls\n # transformed_hmc.bootstrap_results too.\n states, _ = tfp.mcmc.sample_chain(\n num_results=num_results,\n # The initial state is used by inner_kernel.bootstrap_results.\n # Note the input is *after* bijector.forward.\n current_state=self.dtype(0.25),\n kernel=transformed_rwm,\n num_burnin_steps=200,\n num_steps_between_results=1,\n parallel_iterations=1)\n self.assertEqual(num_results, tf.dimension_value(states.shape[0]))\n sample_mean = tf.reduce_mean(states, axis=0)\n sample_var = tf.reduce_mean(\n tf.squared_difference(states, sample_mean),\n axis=0)\n [\n sample_mean_,\n sample_var_,\n true_mean_,\n true_var_,\n ] = sess.run([\n sample_mean,\n sample_var,\n target.mean(),\n target.variance(),\n ])\n self.assertAllClose(true_mean_, sample_mean_,\n atol=0.06, rtol=0.)\n self.assertAllClose(true_var_, sample_var_,\n atol=0.01, rtol=0.1)\n\n def test_end_to_end_works_correctly(self):\n true_mean = self.dtype([0, 0])\n true_cov = self.dtype([[1, 0.5],\n [0.5, 1]])\n num_results = 2000\n counter = collections.Counter()\n with self.cached_session(graph=tf.Graph()) as sess:\n def target_log_prob(x, y):\n counter['target_calls'] += 1\n # Corresponds to unnormalized MVN.\n # z = matmul(inv(chol(true_cov)), [x, y] - true_mean)\n z = tf.stack([x, y], axis=-1) - true_mean\n z = tf.squeeze(\n tf.linalg.triangular_solve(\n np.linalg.cholesky(true_cov),\n z[..., tf.newaxis]),\n axis=-1)\n return -0.5 * tf.reduce_sum(z**2., axis=-1)\n\n transformed_hmc = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(\n target_log_prob_fn=target_log_prob,\n # Affine scaling means we have to change the step_size\n # in order to get 60% acceptance, as was done in mcmc/hmc_test.py.\n step_size=[1.23 / 0.75, 1.23 / 0.5],\n num_leapfrog_steps=2,\n seed=54),\n bijector=[\n tfb.AffineScalar(scale=0.75),\n tfb.AffineScalar(scale=0.5),\n ])\n # Recall, tfp.mcmc.sample_chain calls\n # transformed_hmc.bootstrap_results too.\n states, kernel_results = tfp.mcmc.sample_chain(\n num_results=num_results,\n # The initial state is used by inner_kernel.bootstrap_results.\n # Note the input is *after* `bijector.forward`.\n current_state=[self.dtype(-2), self.dtype(2)],\n kernel=transformed_hmc,\n num_burnin_steps=200,\n num_steps_between_results=1,\n parallel_iterations=1)\n self.assertAllEqual(dict(target_calls=2), counter)\n states = tf.stack(states, axis=-1)\n self.assertEqual(num_results, tf.dimension_value(states.shape[0]))\n sample_mean = tf.reduce_mean(states, axis=0)\n x = states - sample_mean\n sample_cov = tf.matmul(x, x, transpose_a=True) / self.dtype(num_results)\n [sample_mean_, sample_cov_, is_accepted_] = sess.run([\n sample_mean, sample_cov, kernel_results.inner_results.is_accepted])\n self.assertNear(0.6, is_accepted_.mean(), err=0.05)\n self.assertAllClose(true_mean, sample_mean_,\n atol=0.06, rtol=0.)\n self.assertAllClose(true_cov, sample_cov_,\n atol=0., rtol=0.1)\n\n def test_bootstrap_requires_xor_args(self):\n def fake_target_log_prob(x):\n return -x**2 / 2.\n\n transformed_fake = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=FakeInnerKernel(target_log_prob_fn=fake_target_log_prob),\n bijector=tfb.Exp())\n with self.assertRaisesWithPredicateMatch(\n ValueError, r'Must specify exactly one'):\n transformed_fake.bootstrap_results()\n with self.assertRaisesWithPredicateMatch(\n ValueError, r'Must specify exactly one'):\n transformed_fake.bootstrap_results(\n init_state=2., transformed_init_state=np.log(2.))\n\n def test_bootstrap_correctly_untransforms(self):\n def fake_target_log_prob(x):\n return -x**2 / 2.\n\n transformed_fake = tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=FakeInnerKernel(target_log_prob_fn=fake_target_log_prob),\n bijector=tfb.Exp())\n with self.cached_session(graph=tf.Graph()) as sess:\n [\n automatic_pkr,\n manual_pkr,\n ] = sess.run([\n transformed_fake.bootstrap_results(2.),\n transformed_fake.bootstrap_results(transformed_init_state=[4., 5.]),\n ])\n self.assertNear(np.log(2.), automatic_pkr.transformed_state, err=1e-6)\n self.assertAllClose(\n [4., 5.], manual_pkr.transformed_state, atol=0., rtol=1e-6)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\ntfd = tfp.distributions\ntfe = tf.contrib.eager\n\n\[email protected]_all_tests_in_graph_and_eager_modes\nclass DistributionTest(tf.test.TestCase):\n\n def testParamShapesAndFromParams(self):\n classes = [\n tfd.Normal,\n tfd.Bernoulli,\n tfd.Beta,\n tfd.Chi2,\n tfd.Exponential,\n tfd.Gamma,\n tfd.InverseGamma,\n tfd.Laplace,\n tfd.StudentT,\n tfd.Uniform,\n ]\n\n sample_shapes = [(), (10,), (10, 20, 30)]\n for cls in classes:\n for sample_shape in sample_shapes:\n param_shapes = cls.param_shapes(sample_shape)\n params = dict([(name, tf.random_normal(shape))\n for name, shape in param_shapes.items()])\n dist = cls(**params)\n self.assertAllEqual(sample_shape, self.evaluate(\n tf.shape(dist.sample())))\n dist_copy = dist.copy()\n self.assertAllEqual(sample_shape,\n self.evaluate(tf.shape(dist_copy.sample())))\n self.assertEqual(dist.parameters, dist_copy.parameters)\n\n def testCopyExtraArgs(self):\n # Note: we cannot easily test all distributions since each requires\n # different initialization arguments. We therefore spot test a few.\n normal = tfd.Normal(loc=1., scale=2., validate_args=True)\n self.assertEqual(normal.parameters, normal.copy().parameters)\n wishart = tfd.Wishart(df=2, scale=[[1., 2], [2, 5]], validate_args=True)\n self.assertEqual(wishart.parameters, wishart.copy().parameters)\n\n def testCopyOverride(self):\n normal = tfd.Normal(loc=1., scale=2., validate_args=True)\n unused_normal_copy = normal.copy(validate_args=False)\n base_params = normal.parameters.copy()\n copy_params = normal.copy(validate_args=False).parameters.copy()\n self.assertNotEqual(\n base_params.pop(\"validate_args\"), copy_params.pop(\"validate_args\"))\n self.assertEqual(base_params, copy_params)\n\n def testIsScalar(self):\n mu = 1.\n sigma = 2.\n\n normal = tfd.Normal(mu, sigma, validate_args=True)\n self.assertTrue(tf.contrib.util.constant_value(normal.is_scalar_event()))\n self.assertTrue(tf.contrib.util.constant_value(normal.is_scalar_batch()))\n\n normal = tfd.Normal([mu], [sigma], validate_args=True)\n self.assertTrue(tf.contrib.util.constant_value(normal.is_scalar_event()))\n self.assertFalse(tf.contrib.util.constant_value(normal.is_scalar_batch()))\n\n mvn = tfd.MultivariateNormalDiag([mu], [sigma], validate_args=True)\n self.assertFalse(tf.contrib.util.constant_value(mvn.is_scalar_event()))\n self.assertTrue(tf.contrib.util.constant_value(mvn.is_scalar_batch()))\n\n mvn = tfd.MultivariateNormalDiag([[mu]], [[sigma]], validate_args=True)\n self.assertFalse(tf.contrib.util.constant_value(mvn.is_scalar_event()))\n self.assertFalse(tf.contrib.util.constant_value(mvn.is_scalar_batch()))\n\n # We now test every codepath within the underlying is_scalar_helper\n # function.\n\n # Test case 1, 2.\n x = tf.placeholder_with_default(input=1, shape=[])\n # None would fire an exception were it actually executed.\n self.assertTrue(normal._is_scalar_helper(x.shape, lambda: None))\n self.assertTrue(\n normal._is_scalar_helper(tf.TensorShape(None), lambda: tf.shape(x)))\n\n x = tf.placeholder_with_default(input=[1], shape=[1])\n # None would fire an exception were it actually executed.\n self.assertFalse(normal._is_scalar_helper(x.shape, lambda: None))\n self.assertFalse(\n normal._is_scalar_helper(tf.TensorShape(None), lambda: tf.shape(x)))\n\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n if tf.executing_eagerly():\n return\n\n # Test case 3.\n x = tf.placeholder_with_default(input=1, shape=None)\n is_scalar = normal._is_scalar_helper(x.shape, lambda: tf.shape(x))\n self.assertTrue(self.evaluate(is_scalar))\n\n x = tf.placeholder_with_default(input=[1], shape=None)\n is_scalar = normal._is_scalar_helper(x.shape, lambda: tf.shape(x))\n self.assertFalse(self.evaluate(is_scalar))\n\n def _GetFakeDistribution(self):\n class FakeDistribution(tfd.Distribution):\n \"\"\"Fake Distribution for testing _set_sample_static_shape.\"\"\"\n\n def __init__(self, batch_shape=None, event_shape=None):\n self._static_batch_shape = tf.TensorShape(batch_shape)\n self._static_event_shape = tf.TensorShape(event_shape)\n super(FakeDistribution, self).__init__(\n dtype=tf.float32,\n reparameterization_type=tfd.NOT_REPARAMETERIZED,\n validate_args=True,\n allow_nan_stats=True,\n name=\"DummyDistribution\")\n\n def _batch_shape(self):\n return self._static_batch_shape\n\n def _event_shape(self):\n return self._static_event_shape\n\n return FakeDistribution\n\n def testSampleShapeHints(self):\n # In eager mode, all shapes are known, so these tests do not need to\n # execute.\n if tf.executing_eagerly():\n return\n\n fake_distribution = self._GetFakeDistribution()\n\n # Make a new session since we're playing with static shapes. [And below.]\n x = tf.placeholder_with_default(\n input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None)\n dist = fake_distribution(batch_shape=[2, 3], event_shape=[5])\n sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32)\n y = dist._set_sample_static_shape(x, sample_shape)\n # We use as_list since TensorShape comparison does not work correctly for\n # unknown values, ie, Dimension(None).\n self.assertAllEqual([6, 7, 2, 3, 5], y.shape.as_list())\n\n x = tf.placeholder_with_default(\n input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None)\n dist = fake_distribution(batch_shape=[None, 3], event_shape=[5])\n sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32)\n y = dist._set_sample_static_shape(x, sample_shape)\n self.assertAllEqual([6, 7, None, 3, 5], y.shape.as_list())\n\n x = tf.placeholder_with_default(\n input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None)\n dist = fake_distribution(batch_shape=[None, 3], event_shape=[None])\n sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32)\n y = dist._set_sample_static_shape(x, sample_shape)\n self.assertAllEqual([6, 7, None, 3, None], y.shape.as_list())\n\n x = tf.placeholder_with_default(\n input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None)\n dist = fake_distribution(batch_shape=None, event_shape=None)\n sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32)\n y = dist._set_sample_static_shape(x, sample_shape)\n self.assertTrue(y.shape.ndims is None)\n\n x = tf.placeholder_with_default(\n input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None)\n dist = fake_distribution(batch_shape=[None, 3], event_shape=None)\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n sample_shape = tf.convert_to_tensor([6, 7], dtype=tf.int32)\n y = dist._set_sample_static_shape(x, sample_shape)\n self.assertTrue(y.shape.ndims is None)\n\n def testNameScopeWorksCorrectly(self):\n x = tfd.Normal(loc=0., scale=1., name=\"x\")\n x_duplicate = tfd.Normal(loc=0., scale=1., name=\"x\")\n with tf.name_scope(\"y\") as name:\n y = tfd.Bernoulli(logits=0., name=name)\n x_sample = x.sample(name=\"custom_sample\")\n x_sample_duplicate = x.sample(name=\"custom_sample\")\n x_log_prob = x.log_prob(0., name=\"custom_log_prob\")\n x_duplicate_sample = x_duplicate.sample(name=\"custom_sample\")\n\n self.assertEqual(x.name, \"x/\")\n self.assertEqual(y.name, \"y/\")\n\n # There's no notion of graph, hence the same name will be reused.\n # Tensors also do not have names in eager mode, so exit early.\n if tf.executing_eagerly():\n return\n self.assertTrue(x_sample.name.startswith(\"x/custom_sample\"))\n self.assertTrue(x_log_prob.name.startswith(\"x/custom_log_prob\"))\n\n self.assertEqual(x_duplicate.name, \"x_1/\")\n self.assertTrue(x_duplicate_sample.name.startswith(\n \"x_1/custom_sample\"))\n self.assertTrue(x_sample_duplicate.name.startswith(\"x/custom_sample_1\"))\n\n def testStrWorksCorrectlyScalar(self):\n # Usually we'd write np.float(X) here, but a recent Eager bug would\n # erroneously coerce the value to float32 anyway. We therefore use constants\n # here, until the bug is resolved in TensorFlow 1.12.\n normal = tfd.Normal(loc=tf.constant(0, tf.float16),\n scale=tf.constant(1, tf.float16))\n self.assertEqual(\n str(normal),\n \"tfp.distributions.Normal(\"\n \"\\\"Normal/\\\", \"\n \"batch_shape=(), \"\n \"event_shape=(), \"\n \"dtype=float16)\")\n\n chi2 = tfd.Chi2(df=np.float32([1., 2.]), name=\"silly\")\n self.assertEqual(\n str(chi2),\n \"tfp.distributions.Chi2(\"\n \"\\\"silly/\\\", \" # What a silly name that is!\n \"batch_shape=(2,), \"\n \"event_shape=(), \"\n \"dtype=float32)\")\n\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n if tf.executing_eagerly():\n return\n\n exp = tfd.Exponential(rate=tf.placeholder_with_default(\n input=1., shape=None))\n self.assertEqual(\n str(exp),\n \"tfp.distributions.Exponential(\\\"Exponential/\\\", \"\n # No batch shape.\n \"event_shape=(), \"\n \"dtype=float32)\")\n\n def testStrWorksCorrectlyMultivariate(self):\n mvn_static = tfd.MultivariateNormalDiag(\n loc=np.zeros([2, 2]), name=\"MVN\")\n self.assertEqual(\n str(mvn_static),\n \"tfp.distributions.MultivariateNormalDiag(\"\n \"\\\"MVN/\\\", \"\n \"batch_shape=(2,), \"\n \"event_shape=(2,), \"\n \"dtype=float64)\")\n\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n if tf.executing_eagerly():\n return\n\n mvn_dynamic = tfd.MultivariateNormalDiag(\n loc=tf.placeholder_with_default(\n input=np.ones((3, 3), dtype=np.float32), shape=[None, 3]),\n name=\"MVN2\")\n self.assertEqual(\n str(mvn_dynamic),\n \"tfp.distributions.MultivariateNormalDiag(\"\n \"\\\"MVN2/\\\", \"\n \"batch_shape=(?,), \" # Partially known.\n \"event_shape=(3,), \"\n \"dtype=float32)\")\n\n def testReprWorksCorrectlyScalar(self):\n # Usually we'd write np.float(X) here, but a recent Eager bug would\n # erroneously coerce the value to float32 anyway. We therefore use constants\n # here, until the bug is resolved in TensorFlow 1.12.\n normal = tfd.Normal(loc=tf.constant(0, tf.float16),\n scale=tf.constant(1, tf.float16))\n self.assertEqual(\n repr(normal),\n \"<tfp.distributions.Normal\"\n \" 'Normal/'\"\n \" batch_shape=()\"\n \" event_shape=()\"\n \" dtype=float16>\")\n\n chi2 = tfd.Chi2(df=np.float32([1., 2.]), name=\"silly\")\n self.assertEqual(\n repr(chi2),\n \"<tfp.distributions.Chi2\"\n \" 'silly/'\" # What a silly name that is!\n \" batch_shape=(2,)\"\n \" event_shape=()\"\n \" dtype=float32>\")\n\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n if tf.executing_eagerly():\n return\n\n exp = tfd.Exponential(rate=tf.placeholder_with_default(\n input=1., shape=None))\n self.assertEqual(\n repr(exp),\n \"<tfp.distributions.Exponential\"\n \" 'Exponential/'\"\n \" batch_shape=<unknown>\"\n \" event_shape=()\"\n \" dtype=float32>\")\n\n def testReprWorksCorrectlyMultivariate(self):\n mvn_static = tfd.MultivariateNormalDiag(\n loc=np.zeros([2, 2]), name=\"MVN\")\n self.assertEqual(\n repr(mvn_static),\n \"<tfp.distributions.MultivariateNormalDiag\"\n \" 'MVN/'\"\n \" batch_shape=(2,)\"\n \" event_shape=(2,)\"\n \" dtype=float64>\")\n\n # There's no notion of partially known shapes in eager mode, so exit\n # early.\n if tf.executing_eagerly():\n return\n\n mvn_dynamic = tfd.MultivariateNormalDiag(\n loc=tf.placeholder_with_default(\n input=np.ones((3, 3), dtype=np.float32), shape=[None, 3]),\n name=\"MVN2\")\n self.assertEqual(\n repr(mvn_dynamic),\n \"<tfp.distributions.MultivariateNormalDiag\"\n \" 'MVN2/'\"\n \" batch_shape=(?,)\" # Partially known.\n \" event_shape=(3,)\"\n \" dtype=float32>\")\n\n def testUnimplemtnedProbAndLogProbExceptions(self):\n class TerribleDistribution(tfd.Distribution):\n\n def __init__(self):\n super(TerribleDistribution, self).__init__(\n dtype=tf.float32,\n reparameterization_type=tfd.NOT_REPARAMETERIZED,\n validate_args=False,\n allow_nan_stats=False)\n\n terrible_distribution = TerribleDistribution()\n with self.assertRaisesRegexp(\n NotImplementedError, \"prob is not implemented\"):\n terrible_distribution.prob(1.)\n with self.assertRaisesRegexp(\n NotImplementedError, \"log_prob is not implemented\"):\n terrible_distribution.log_prob(1.)\n with self.assertRaisesRegexp(\n NotImplementedError, \"cdf is not implemented\"):\n terrible_distribution.cdf(1.)\n with self.assertRaisesRegexp(\n NotImplementedError, \"log_cdf is not implemented\"):\n terrible_distribution.log_cdf(1.)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport numpy as np\nfrom scipy import stats\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability.python.internal import test_case\n\ntfd = tfp.distributions\ntfe = tf.contrib.eager\n\n\[email protected]_all_tests_in_graph_and_eager_modes\nclass ParetoTest(test_case.TestCase):\n\n def _scipy_pareto(self, concentration, scale):\n # In scipy pareto is defined with scale = 1, so we need to scale.\n return stats.pareto(concentration, scale=scale)\n\n def testParetoShape(self):\n scale = tf.constant([2.] * 5)\n concentration = tf.constant([2.] * 5)\n pareto = tfd.Pareto(concentration, scale)\n\n self.assertEqual(self.evaluate(pareto.batch_shape_tensor()), (5,))\n self.assertEqual(pareto.batch_shape, tf.TensorShape([5]))\n self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), [])\n self.assertEqual(pareto.event_shape, tf.TensorShape([]))\n\n def testParetoShapeBroadcast(self):\n scale = tf.constant([[3., 2.]])\n concentration = tf.constant([[4.], [5.], [6.]])\n pareto = tfd.Pareto(concentration, scale)\n\n self.assertAllEqual(self.evaluate(pareto.batch_shape_tensor()), (3, 2))\n self.assertAllEqual(pareto.batch_shape, tf.TensorShape([3, 2]))\n self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), [])\n self.assertEqual(pareto.event_shape, tf.TensorShape([]))\n\n def testInvalidScale(self):\n invalid_scales = [-.01, 0., -2.]\n concentration = 3.\n for scale in invalid_scales:\n with self.assertRaisesOpError(\"Condition x > 0\"):\n pareto = tfd.Pareto(concentration, scale, validate_args=True)\n self.evaluate(pareto.scale)\n\n def testInvalidConcentration(self):\n scale = 1.\n invalid_concentrations = [-.01, 0., -2.]\n for concentration in invalid_concentrations:\n with self.assertRaisesOpError(\"Condition x > 0\"):\n pareto = tfd.Pareto(concentration, scale, validate_args=True)\n self.evaluate(pareto.concentration)\n\n def testParetoLogPdf(self):\n batch_size = 6\n scale = tf.constant([3.] * batch_size)\n scale_v = 3.\n concentration = tf.constant([2.])\n concentration_v = 2.\n x = [3., 3.1, 4., 5., 6., 7.]\n pareto = tfd.Pareto(concentration, scale)\n log_prob = pareto.log_prob(x)\n self.assertEqual(log_prob.shape, (6,))\n self.assertAllClose(\n self.evaluate(log_prob),\n self._scipy_pareto(concentration_v, scale_v).logpdf(x))\n\n pdf = pareto.prob(x)\n self.assertEqual(pdf.shape, (6,))\n self.assertAllClose(\n self.evaluate(pdf),\n self._scipy_pareto(concentration_v, scale_v).pdf(x))\n\n def testParetoLogPdfValidateArgs(self):\n batch_size = 3\n scale = tf.constant([2., 3., 4.])\n concentration = tf.constant([2.] * batch_size)\n pareto = tfd.Pareto(concentration, scale, validate_args=True)\n\n with self.assertRaisesOpError(\"not in the support\"):\n x = tf.placeholder_with_default(input=[2., 3., 3.], shape=[3])\n log_prob = pareto.log_prob(x)\n self.evaluate(log_prob)\n\n with self.assertRaisesOpError(\"not in the support\"):\n x = tf.placeholder_with_default(input=[2., 2., 5.], shape=[3])\n log_prob = pareto.log_prob(x)\n self.evaluate(log_prob)\n\n with self.assertRaisesOpError(\"not in the support\"):\n x = tf.placeholder_with_default(input=[1., 3., 5.], shape=[3])\n log_prob = pareto.log_prob(x)\n self.evaluate(log_prob)\n\n def testParetoLogPdfMultidimensional(self):\n batch_size = 6\n scale = tf.constant([[2., 4., 5.]] * batch_size)\n scale_v = [2., 4., 5.]\n concentration = tf.constant([[1.]] * batch_size)\n concentration_v = 1.\n\n x = np.array([[6., 7., 9.2, 5., 6., 7.]], dtype=np.float32).T\n\n pareto = tfd.Pareto(concentration, scale)\n log_prob = pareto.log_prob(x)\n self.assertEqual(log_prob.shape, (6, 3))\n self.assertAllClose(\n self.evaluate(log_prob),\n self._scipy_pareto(concentration_v, scale_v).logpdf(x))\n\n prob = pareto.prob(x)\n self.assertEqual(prob.shape, (6, 3))\n self.assertAllClose(\n self.evaluate(prob),\n self._scipy_pareto(concentration_v, scale_v).pdf(x))\n\n def testParetoLogCdf(self):\n batch_size = 6\n scale = tf.constant([3.] * batch_size)\n scale_v = 3.\n concentration = tf.constant([2.])\n concentration_v = 2.\n x = [3., 3.1, 4., 5., 6., 7.]\n pareto = tfd.Pareto(concentration, scale)\n log_cdf = pareto.log_cdf(x)\n self.assertEqual(log_cdf.shape, (6,))\n self.assertAllClose(\n self.evaluate(log_cdf),\n self._scipy_pareto(concentration_v, scale_v).logcdf(x))\n\n cdf = pareto.cdf(x)\n self.assertEqual(cdf.shape, (6,))\n self.assertAllClose(\n self.evaluate(cdf),\n self._scipy_pareto(concentration_v, scale_v).cdf(x))\n\n def testParetoLogCdfMultidimensional(self):\n batch_size = 6\n scale = tf.constant([[2., 4., 5.]] * batch_size)\n scale_v = [2., 4., 5.]\n concentration = tf.constant([[1.]] * batch_size)\n concentration_v = 1.\n\n x = np.array([[6., 7., 9.2, 5., 6., 7.]], dtype=np.float32).T\n\n pareto = tfd.Pareto(concentration, scale)\n log_cdf = pareto.log_cdf(x)\n self.assertEqual(log_cdf.shape, (6, 3))\n self.assertAllClose(\n self.evaluate(log_cdf),\n self._scipy_pareto(concentration_v, scale_v).logcdf(x))\n\n cdf = pareto.cdf(x)\n self.assertEqual(cdf.shape, (6, 3))\n self.assertAllClose(\n self.evaluate(cdf),\n self._scipy_pareto(concentration_v, scale_v).cdf(x))\n\n def testParetoPDFGradientZeroOutsideSupport(self):\n scale = tf.constant(1.)\n concentration = tf.constant(3.)\n # Check the gradient on the undefined portion.\n x = scale - 1\n\n pareto = tfd.Pareto(concentration, scale)\n compute_pdf = lambda x: pareto.prob(x) # pylint:disable=unnecessary-lambda\n self.assertAlmostEqual(self.compute_gradients(\n compute_pdf, args=[x])[0], 0.)\n\n def testParetoCDFGradientZeroOutsideSupport(self):\n scale = tf.constant(1.)\n concentration = tf.constant(3.)\n # Check the gradient on the undefined portion.\n x = scale - 1\n\n pareto = tfd.Pareto(concentration, scale)\n compute_cdf = lambda x: pareto.cdf(x) # pylint:disable=unnecessary-lambda\n self.assertAlmostEqual(\n self.compute_gradients(\n compute_cdf, args=[x])[0], 0.)\n\n def testParetoMean(self):\n scale = [1.4, 2., 2.5]\n concentration = [2., 3., 2.5]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.mean().shape, (3,))\n self.assertAllClose(\n self.evaluate(pareto.mean()),\n self._scipy_pareto(concentration, scale).mean())\n\n def testParetoMeanInf(self):\n scale = [1.4, 2., 2.5]\n concentration = [0.4, 0.9, 0.99]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.mean().shape, (3,))\n\n self.assertTrue(\n np.all(np.isinf(self.evaluate(pareto.mean()))))\n\n def testParetoVariance(self):\n scale = [1.4, 2., 2.5]\n concentration = [2., 3., 2.5]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.variance().shape, (3,))\n self.assertAllClose(\n self.evaluate(pareto.variance()),\n self._scipy_pareto(concentration, scale).var())\n\n def testParetoVarianceInf(self):\n scale = [1.4, 2., 2.5]\n concentration = [0.4, 0.9, 0.99]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.variance().shape, (3,))\n self.assertTrue(\n np.all(np.isinf(self.evaluate(pareto.variance()))))\n\n def testParetoStd(self):\n scale = [1.4, 2., 2.5]\n concentration = [2., 3., 2.5]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.stddev().shape, (3,))\n self.assertAllClose(\n self.evaluate(pareto.stddev()),\n self._scipy_pareto(concentration, scale).std())\n\n def testParetoMode(self):\n scale = [0.4, 1.4, 2., 2.5]\n concentration = [1., 2., 3., 2.5]\n pareto = tfd.Pareto(concentration, scale)\n self.assertEqual(pareto.mode().shape, (4,))\n self.assertAllClose(self.evaluate(pareto.mode()), scale)\n\n def testParetoSampleMean(self):\n scale = 4.\n concentration = 3.\n n = int(100e3)\n pareto = tfd.Pareto(concentration, scale)\n samples = pareto.sample(n, seed=123456)\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n,))\n self.assertEqual(sample_values.shape, (n,))\n self.assertAllClose(\n sample_values.mean(),\n self._scipy_pareto(concentration, scale).mean(),\n rtol=.01,\n atol=0)\n\n def testParetoSampleVariance(self):\n scale = 1.\n concentration = 3.\n n = int(400e3)\n pareto = tfd.Pareto(concentration, scale)\n samples = pareto.sample(n, seed=123456)\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n,))\n self.assertEqual(sample_values.shape, (n,))\n self.assertAllClose(\n sample_values.var(),\n self._scipy_pareto(concentration, scale).var(),\n rtol=.03,\n atol=0)\n\n def testParetoSampleMultidimensionalMean(self):\n scale = np.array([np.arange(1, 21, dtype=np.float32)])\n concentration = 3.\n pareto = tfd.Pareto(concentration, scale)\n n = int(100e3)\n samples = pareto.sample(n, seed=123456)\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 1, 20))\n self.assertEqual(sample_values.shape, (n, 1, 20))\n self.assertAllClose(\n sample_values.mean(axis=0),\n self._scipy_pareto(concentration, scale).mean(),\n rtol=.01,\n atol=0)\n\n def testParetoSampleMultidimensionalVariance(self):\n scale = np.array([np.arange(1, 11, dtype=np.float32)])\n concentration = 4.\n pareto = tfd.Pareto(concentration, scale)\n n = int(800e3)\n samples = pareto.sample(n, seed=123456)\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 1, 10))\n self.assertEqual(sample_values.shape, (n, 1, 10))\n\n self.assertAllClose(\n sample_values.var(axis=0),\n self._scipy_pareto(concentration, scale).var(),\n rtol=.05,\n atol=0)\n\n def testParetoParetoKLFinite(self):\n a_scale = np.arange(1.0, 5.0)\n a_concentration = 1.0\n b_scale = 1.0\n b_concentration = np.arange(2.0, 10.0, 2)\n\n a = tfd.Pareto(concentration=a_concentration, scale=a_scale)\n b = tfd.Pareto(concentration=b_concentration, scale=b_scale)\n\n true_kl = (b_concentration * (np.log(a_scale) - np.log(b_scale)) +\n np.log(a_concentration) - np.log(b_concentration) +\n b_concentration / a_concentration - 1.0)\n kl = tfd.kl_divergence(a, b)\n\n x = a.sample(int(1e5), seed=0)\n kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), 0)\n\n kl_, kl_sample_ = self.evaluate([kl, kl_sample])\n self.assertAllEqual(true_kl, kl_)\n self.assertAllClose(true_kl, kl_sample_, atol=0., rtol=1e-2)\n\n zero_kl = tfd.kl_divergence(a, a)\n true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl])\n self.assertAllEqual(true_zero_kl_, zero_kl_)\n\n def testParetoParetoKLInfinite(self):\n a = tfd.Pareto(concentration=1.0, scale=1.0)\n b = tfd.Pareto(concentration=1.0, scale=2.0)\n\n kl = tfd.kl_divergence(a, b)\n kl_ = self.evaluate(kl)\n self.assertAllEqual(np.inf, kl_)\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Linear Gaussian State Space Model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\n# Dependency imports\nimport tensorflow as tf\n\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions import independent\nfrom tensorflow_probability.python.distributions import mvn_tril\nfrom tensorflow_probability.python.distributions import normal\nfrom tensorflow_probability.python.distributions import seed_stream\n\nfrom tensorflow_probability.python.internal import distribution_util as util\nfrom tensorflow_probability.python.internal import reparameterization\nfrom tensorflow.python.ops.linalg import linear_operator_util\n\ntfl = tf.linalg\n\n# The built-in tf.matmul doesn't broadcast batch dimensions, so we\n# need to use `matmul_with_broadcast` throughout to ensure we support\n# batching.\n_matmul = linear_operator_util.matmul_with_broadcast\n\n\ndef _broadcast_to_shape(x, shape):\n return x + tf.zeros(shape=shape, dtype=x.dtype)\n\n\ndef _check_equal_shape(name,\n static_shape,\n dynamic_shape,\n static_target_shape,\n dynamic_target_shape=None):\n \"\"\"Check that source and target shape match, statically if possible.\"\"\"\n\n static_target_shape = tf.TensorShape(static_target_shape)\n if static_shape.is_fully_defined() and static_target_shape.is_fully_defined():\n if static_shape != static_target_shape:\n raise ValueError(\"{}: required shape {} but found {}\".\n format(name, static_target_shape, static_shape))\n return None\n else:\n if dynamic_target_shape is None:\n if static_target_shape.is_fully_defined():\n dynamic_target_shape = static_target_shape.as_list()\n else:\n raise ValueError(\"{}: cannot infer target shape: no dynamic shape \"\n \"specified and static shape {} is not fully defined\".\n format(name, static_target_shape))\n return tf.assert_equal(dynamic_shape, dynamic_target_shape,\n message=(\"{}: required shape {}\".\n format(name, static_target_shape)))\n\n\ndef _augment_sample_shape(partial_batch_dist,\n full_sample_and_batch_shape,\n validate_args=False):\n \"\"\"Augment a sample shape to broadcast batch dimensions.\n\n Computes an augmented sample shape, so that any batch dimensions not\n part of the distribution `partial_batch_dist` are treated as identical\n distributions.\n\n # partial_batch_dist.batch_shape = [ 7]\n # full_sample_and_batch_shape = [3, 4, 7]\n # => return an augmented sample shape of [3, 4] so that\n # partial_batch_dist.sample(augmented_sample_shape) has combined\n # sample and batch shape of [3, 4, 7].\n\n Args:\n partial_batch_dist: `tfd.Distribution` instance with batch shape a\n prefix of `full_sample_and_batch_shape`.\n full_sample_and_batch_shape: a Tensor or Tensor-like shape.\n validate_args: if True, check for shape errors at runtime.\n Returns:\n augmented_sample_shape: sample shape such that\n `partial_batch_dist.sample(augmented_sample_shape)` has combined\n sample and batch shape of `full_sample_and_batch_shape`.\n\n Raises:\n ValueError: if `partial_batch_dist.batch_shape` has more dimensions than\n `full_sample_and_batch_shape`.\n NotImplementedError: if broadcasting would be required to make\n `partial_batch_dist.batch_shape` into a prefix of\n `full_sample_and_batch_shape` .\n \"\"\"\n full_ndims = util.prefer_static_shape(full_sample_and_batch_shape)[0]\n partial_batch_ndims = (partial_batch_dist.batch_shape.ndims\n if partial_batch_dist.batch_shape.ndims is not None\n else util.prefer_static_shape(\n partial_batch_dist.batch_shape_tensor())[0])\n\n num_broadcast_dims = full_ndims - partial_batch_ndims\n\n expected_partial_batch_shape = (\n full_sample_and_batch_shape[num_broadcast_dims:])\n expected_partial_batch_shape_static = util.static_value(\n full_sample_and_batch_shape[num_broadcast_dims:])\n\n # Raise errors statically if possible.\n num_broadcast_dims_static = util.static_value(num_broadcast_dims)\n if num_broadcast_dims_static is not None:\n if num_broadcast_dims_static < 0:\n raise ValueError(\"Cannot broadcast distribution {} batch shape to \"\n \"target batch shape with fewer dimensions\"\n .format(partial_batch_dist))\n if (expected_partial_batch_shape_static is not None and\n partial_batch_dist.batch_shape.is_fully_defined()):\n if (partial_batch_dist.batch_shape and\n any(expected_partial_batch_shape_static !=\n partial_batch_dist.batch_shape.as_list())):\n raise NotImplementedError(\"Broadcasting is not supported; \"\n \"unexpected batch shape \"\n \"(expected {}, saw {}).\".format(\n expected_partial_batch_shape_static,\n partial_batch_dist.batch_shape\n ))\n runtime_assertions = []\n if validate_args:\n runtime_assertions.append(tf.assert_greater_equal(\n tf.convert_to_tensor(\n num_broadcast_dims,\n dtype=tf.int32),\n tf.zeros((), dtype=tf.int32), message=(\n \"Cannot broadcast distribution {} batch shape to \"\n \"target batch shape with fewer dimensions.\".\n format(partial_batch_dist))))\n runtime_assertions.append(tf.assert_equal(\n expected_partial_batch_shape,\n partial_batch_dist.batch_shape_tensor(),\n message=(\"Broadcasting is not supported; \"\n \"unexpected batch shape.\"),\n name=\"assert_batch_shape_same\"))\n\n with tf.control_dependencies(runtime_assertions):\n return full_sample_and_batch_shape[:num_broadcast_dims]\n\n\nclass LinearGaussianStateSpaceModel(distribution.Distribution):\n \"\"\"Observation distribution from a linear Gaussian state space model.\n\n The state space model, sometimes called a Kalman filter, posits a\n latent state vector `z_t` of dimension `latent_size` that evolves\n over time following linear Gaussian transitions,\n\n ```z_{t+1} = F * z_t + N(b; Q)```\n\n for transition matrix `F`, bias `b` and covariance matrix\n `Q`. At each timestep, we observe a noisy projection of the\n latent state `x_t = H * z_t + N(c; R)`. The transition and\n observation models may be fixed or may vary between timesteps.\n\n This Distribution represents the marginal distribution on\n observations, `p(x)`. The marginal `log_prob` is computed by\n Kalman filtering [1], and `sample` by an efficient forward\n recursion. Both operations require time linear in `T`, the total\n number of timesteps.\n\n #### Shapes\n\n The event shape is `[num_timesteps, observation_size]`, where\n `observation_size` is the dimension of each observation `x_t`.\n The observation and transition models must return consistent\n shapes.\n\n This implementation supports vectorized computation over a batch of\n models. All of the parameters (prior distribution, transition and\n observation operators and noise models) must have a consistent\n batch shape.\n\n #### Time-varying processes\n\n Any of the model-defining parameters (prior distribution, transition\n and observation operators and noise models) may be specified as a\n callable taking an integer timestep `t` and returning a\n time-dependent value. The dimensionality (`latent_size` and\n `observation_size`) must be the same at all timesteps.\n\n Importantly, the timestep is passed as a `Tensor`, not a Python\n integer, so any conditional behavior must occur *inside* the\n TensorFlow graph. For example, suppose we want to use a different\n transition model on even days than odd days. It does *not* work to\n write\n\n ```python\n def transition_matrix(t):\n if t % 2 == 0:\n return even_day_matrix\n else:\n return odd_day_matrix\n ```\n\n since the value of `t` is not fixed at graph-construction\n time. Instead we need to write\n\n ```python\n def transition_matrix(t):\n return tf.cond(tf.equal(tf.mod(t, 2), 0),\n lambda : even_day_matrix,\n lambda : odd_day_matrix)\n ```\n\n so that TensorFlow can switch between operators appropriately at\n runtime.\n\n #### Examples\n\n Consider a simple tracking model. The two-dimensional latent state\n represents the true position of a vehicle, and at each timestep we\n see a noisy observation of this position (e.g., a GPS reading). The\n vehicle is assumed to move by a random walk with standard deviation\n `step_std` at each step, and observation noise level `std`. We build\n the distribution over noisy observations by\n\n ```python\n ndims = 2\n step_std = 1.0\n noise_std = 5.0\n model = LinearGaussianStateSpaceModel(\n num_timesteps=100,\n transition_matrix=tfl.LinearOperatorIdentity(ndims),\n transition_noise=tfd.MultivariateNormalDiag(\n scale_diag=step_std**2 * tf.ones([ndims])),\n observation_matrix=tfl.LinearOperatorIdentity(ndims),\n observation_noise=tfd.MultivariateNormalDiag(\n scale_diag=noise_std**2 * tf.ones([ndims])),\n initial_state_prior=tfd.MultivariateNormalDiag(\n scale_diag=tf.ones([ndims])))\n )\n ```\n\n using the identity matrix for the transition and observation\n operators. We can then use this model to generate samples,\n compute marginal likelihood of observed sequences, and\n perform posterior inference.\n\n ```python\n x = model.sample(5) # Sample from the prior on sequences of observations.\n lp = model.log_prob(x) # Marginal likelihood of a (batch of) observations.\n\n # Compute the filtered posterior on latent states given observations,\n # and extract the mean and covariance for the current (final) timestep.\n _, filtered_means, filtered_covs, _, _ = model.forward_filter(x)\n final_step = tfd.MultivariateNormalFullCovariance(\n loc=filtered_means[..., -1, :],\n scale=filtered_covs[..., -1, :])\n ```\n\n * TODO(davmre): implement and describe full posterior inference / smoothing.\n\n * TODO(davmre): show example of fitting parameters.\n \"\"\"\n\n def __init__(self,\n num_timesteps,\n transition_matrix,\n transition_noise,\n observation_matrix,\n observation_noise,\n initial_state_prior,\n initial_step=0,\n validate_args=False,\n allow_nan_stats=True,\n name=\"LinearGaussianStateSpaceModel\"):\n \"\"\"Initialize a `LinearGaussianStateSpaceModel.\n\n Args:\n num_timesteps: Python `int` total number of timesteps.\n transition_matrix: A transition operator, represented by a Tensor or\n LinearOperator of shape `[latent_size, latent_size]`, or by a\n callable taking as argument a scalar integer Tensor `t` and\n returning a Tensor or LinearOperator representing the transition\n operator from latent state at time `t` to time `t + 1`.\n transition_noise: An instance of\n `tfd.MultivariateNormalLinearOperator` with event shape\n `[latent_size]`, representing the mean and covariance of the\n transition noise model, or a callable taking as argument a\n scalar integer Tensor `t` and returning such a distribution\n representing the noise in the transition from time `t` to time `t + 1`.\n observation_matrix: An observation operator, represented by a Tensor\n or LinearOperator of shape `[observation_size, latent_size]`,\n or by a callable taking as argument a scalar integer Tensor\n `t` and returning a timestep-specific Tensor or\n LinearOperator.\n observation_noise: An instance of\n `tfd.MultivariateNormalLinearOperator` with event shape\n `[observation_size]`, representing the mean and covariance of\n the observation noise model, or a callable taking as argument\n a scalar integer Tensor `t` and returning a timestep-specific\n noise model.\n initial_state_prior: An instance of `MultivariateNormalLinearOperator`\n representing the prior distribution on latent states; must\n have event shape `[latent_size]`.\n initial_step: optional `int` specifying the time of the first\n modeled timestep. This is added as an offset when passing\n timesteps `t` to (optional) callables specifying\n timestep-specific transition and observation models.\n validate_args: Python `bool`, default `False`. Whether to validate input\n with asserts. If `validate_args` is `False`, and the inputs are\n invalid, correct behavior is not guaranteed.\n allow_nan_stats: Python `bool`, default `True`. If `False`, raise an\n exception if a statistic (e.g. mean/mode/etc...) is undefined for any\n batch member If `True`, batch members with valid parameters leading to\n undefined statistics will return NaN for this statistic.\n name: The name to give Ops created by the initializer.\n \"\"\"\n\n parameters = locals()\n\n with tf.name_scope(name, values=[num_timesteps,\n transition_matrix,\n transition_noise,\n observation_matrix,\n observation_noise,\n initial_state_prior,\n initial_step]) as name:\n\n self.num_timesteps = num_timesteps\n self.initial_state_prior = initial_state_prior\n self.initial_step = initial_step\n self.final_step = self.initial_step + self.num_timesteps\n\n # TODO(b/78475680): Friendly dtype inference.\n dtype = initial_state_prior.dtype\n\n # Internally, the transition and observation matrices are\n # canonicalized as callables returning a LinearOperator. This\n # creates no overhead when the model is actually fixed, since in\n # that case we simply build the trivial callable that returns\n # the same matrix at each timestep.\n def _maybe_make_linop(x, is_square=None, name=None):\n \"\"\"Converts Tensors into LinearOperators.\"\"\"\n if not isinstance(x, tfl.LinearOperator):\n x = tfl.LinearOperatorFullMatrix(\n tf.convert_to_tensor(x, dtype=dtype),\n is_square=is_square,\n name=name)\n return x\n def _maybe_make_callable_from_linop(f, name, make_square_linop=None):\n \"\"\"Converts fixed objects into trivial callables.\"\"\"\n if not callable(f):\n linop = _maybe_make_linop(f, is_square=make_square_linop, name=name)\n f = lambda t: linop\n return f\n self.get_transition_matrix_for_timestep = (\n _maybe_make_callable_from_linop(\n transition_matrix,\n name=\"transition_matrix\",\n make_square_linop=True))\n self.get_observation_matrix_for_timestep = (\n _maybe_make_callable_from_linop(\n observation_matrix, name=\"observation_matrix\"))\n\n # Similarly, we canonicalize the transition and observation\n # noise models as callables returning a\n # tfd.MultivariateNormalLinearOperator distribution object.\n def _maybe_make_callable(f):\n if not callable(f):\n return lambda t: f\n return f\n self.get_transition_noise_for_timestep = _maybe_make_callable(\n transition_noise)\n self.get_observation_noise_for_timestep = _maybe_make_callable(\n observation_noise)\n\n # We call the get_observation_matrix_for_timestep once so that\n # we can infer the observation size. This potentially adds ops\n # to the graph, though will not in typical cases (e.g., where\n # the callable was generated by wrapping a fixed value using\n # _maybe_make_callable above).\n self.latent_size = util.prefer_static_value(\n initial_state_prior.event_shape_tensor())[-1]\n self.observation_size = util.prefer_static_value(\n self.get_observation_matrix_for_timestep(\n self.initial_step).shape_tensor())[-2]\n\n self.runtime_assertions = []\n if validate_args:\n transition_matrix = (\n self.get_transition_matrix_for_timestep(self.initial_step))\n transition_noise = (\n self.get_transition_noise_for_timestep(self.initial_step))\n observation_matrix = (\n self.get_observation_matrix_for_timestep(self.initial_step))\n observation_noise = (\n self.get_observation_noise_for_timestep(self.initial_step))\n\n tf.assert_same_float_dtype([initial_state_prior,\n transition_matrix,\n transition_noise,\n observation_matrix,\n observation_noise])\n\n latent_size_ = util.static_value(self.latent_size)\n observation_size_ = util.static_value(self.observation_size)\n runtime_assertions = [\n _check_equal_shape(\n name=\"transition_matrix\",\n static_shape=transition_matrix.shape[-2:],\n dynamic_shape=transition_matrix.shape_tensor()[-2:],\n static_target_shape=[latent_size_, latent_size_],\n dynamic_target_shape=[self.latent_size, self.latent_size]),\n _check_equal_shape(\n name=\"observation_matrix\",\n static_shape=observation_matrix.shape[-2:],\n dynamic_shape=observation_matrix.shape_tensor()[-2:],\n static_target_shape=[observation_size_, latent_size_],\n dynamic_target_shape=[self.observation_size, self.latent_size]),\n _check_equal_shape(\n name=\"initial_state_prior\",\n static_shape=initial_state_prior.event_shape,\n dynamic_shape=initial_state_prior.event_shape_tensor(),\n static_target_shape=[latent_size_],\n dynamic_target_shape=[self.latent_size]),\n _check_equal_shape(\n name=\"transition_noise\",\n static_shape=transition_noise.event_shape,\n dynamic_shape=transition_noise.event_shape_tensor(),\n static_target_shape=[latent_size_],\n dynamic_target_shape=[self.latent_size]),\n _check_equal_shape(\n name=\"observation_noise\",\n static_shape=observation_noise.event_shape,\n dynamic_shape=observation_noise.event_shape_tensor(),\n static_target_shape=[observation_size_],\n dynamic_target_shape=[self.observation_size])]\n self.runtime_assertions = [op for op in runtime_assertions\n if op is not None]\n _, _ = self._batch_shape(), self._batch_shape_tensor()\n\n super(LinearGaussianStateSpaceModel, self).__init__(\n dtype=dtype,\n reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n parameters=parameters,\n graph_parents=[],\n name=name)\n\n def _batch_shape_tensor(self):\n # We assume the batch shapes of parameters don't change over time,\n # so use the initial step as a prototype.\n return tf.broadcast_dynamic_shape(\n self.initial_state_prior.batch_shape_tensor(),\n tf.broadcast_dynamic_shape(\n self.get_transition_matrix_for_timestep(\n self.initial_step).batch_shape_tensor(),\n tf.broadcast_dynamic_shape(\n self.get_transition_noise_for_timestep(\n self.initial_step).batch_shape_tensor(),\n tf.broadcast_dynamic_shape(\n self.get_observation_matrix_for_timestep(\n self.initial_step).batch_shape_tensor(),\n self.get_observation_noise_for_timestep(\n self.initial_step).batch_shape_tensor()))))\n\n def _batch_shape(self):\n # We assume the batch shapes of parameters don't change over time,\n # so use the initial step as a prototype.\n return tf.broadcast_static_shape(\n self.initial_state_prior.batch_shape,\n tf.broadcast_static_shape(\n self.get_transition_matrix_for_timestep(\n self.initial_step).batch_shape,\n tf.broadcast_static_shape(\n self.get_transition_noise_for_timestep(\n self.initial_step).batch_shape,\n tf.broadcast_static_shape(\n self.get_observation_matrix_for_timestep(\n self.initial_step).batch_shape,\n self.get_observation_noise_for_timestep(\n self.initial_step).batch_shape))))\n\n def _event_shape(self):\n return tf.TensorShape([\n tf.contrib.util.constant_value(\n tf.convert_to_tensor(self.num_timesteps)),\n tf.contrib.util.constant_value(\n tf.convert_to_tensor(self.observation_size))])\n\n def _event_shape_tensor(self):\n return tf.stack([self.num_timesteps, self.observation_size])\n\n def _sample_n(self, n, seed=None):\n _, observation_samples = self._joint_sample_n(n, seed=seed)\n return observation_samples\n\n def _joint_sample_n(self, n, seed=None):\n \"\"\"Draw a joint sample from the prior over latents and observations.\"\"\"\n\n with tf.name_scope(\"sample_n_joint\"):\n stream = seed_stream.SeedStream(\n seed, salt=\"LinearGaussianStateSpaceModel_sample_n_joint\")\n\n sample_and_batch_shape = util.prefer_static_value(\n tf.concat([[n], self.batch_shape_tensor()],\n axis=0))\n\n # Sample the initial timestep from the prior. Since we want\n # this sample to have full batch shape (not just the batch shape\n # of the self.initial_state_prior object which might in general be\n # smaller), we augment the sample shape to include whatever\n # extra batch dimensions are required.\n with tf.control_dependencies(self.runtime_assertions):\n initial_latent = self.initial_state_prior.sample(\n sample_shape=_augment_sample_shape(\n self.initial_state_prior,\n sample_and_batch_shape,\n self.validate_args),\n seed=stream())\n\n # Add a dummy dimension so that matmul() does matrix-vector\n # multiplication.\n initial_latent = initial_latent[..., tf.newaxis]\n\n initial_observation_matrix = (\n self.get_observation_matrix_for_timestep(self.initial_step))\n initial_observation_noise = (\n self.get_observation_noise_for_timestep(self.initial_step))\n\n initial_observation_pred = initial_observation_matrix.matmul(\n initial_latent)\n initial_observation = (initial_observation_pred +\n initial_observation_noise.sample(\n sample_shape=_augment_sample_shape(\n initial_observation_noise,\n sample_and_batch_shape,\n self.validate_args),\n seed=stream())[..., tf.newaxis])\n\n sample_step = build_kalman_sample_step(\n self.get_transition_matrix_for_timestep,\n self.get_transition_noise_for_timestep,\n self.get_observation_matrix_for_timestep,\n self.get_observation_noise_for_timestep,\n full_sample_and_batch_shape=sample_and_batch_shape,\n stream=stream,\n validate_args=self.validate_args)\n\n # Scan over all timesteps to sample latents and observations.\n (latents, observations) = tf.scan(\n sample_step,\n elems=tf.range(self.initial_step+1, self.final_step),\n initializer=(initial_latent, initial_observation))\n\n # Combine the initial sampled timestep with the remaining timesteps.\n latents = tf.concat([initial_latent[tf.newaxis, ...],\n latents], axis=0)\n observations = tf.concat([initial_observation[tf.newaxis, ...],\n observations], axis=0)\n\n # Put dimensions back in order. The samples we've computed are\n # ordered by timestep, with shape `[num_timesteps, num_samples,\n # batch_shape, size, 1]` where `size` represents `latent_size`\n # or `observation_size` respectively. But timesteps are really\n # part of each probabilistic event, so we need to return a Tensor\n # of shape `[num_samples, batch_shape, num_timesteps, size]`.\n latents = tf.squeeze(latents, -1)\n latents = util.move_dimension(latents, 0, -2)\n observations = tf.squeeze(observations, -1)\n observations = util.move_dimension(observations, 0, -2)\n\n return latents, observations\n\n def _log_prob(self, x):\n log_likelihoods, _, _, _, _, _, _ = self.forward_filter(x)\n\n # Sum over timesteps to compute the log marginal likelihood.\n return tf.reduce_sum(log_likelihoods, axis=-1)\n\n def forward_filter(self, x):\n \"\"\"Run a Kalman filter over a provided sequence of outputs.\n\n Note that the returned values `filtered_means`, `predicted_means`, and\n `observation_means` depend on the observed time series `x`, while the\n corresponding covariances are independent of the observed series; i.e., they\n depend only on the model itself. This means that the mean values have shape\n `concat([sample_shape(x), batch_shape, [num_timesteps,\n {latent/observation}_size]])`, while the covariances have shape\n `concat[(batch_shape, [num_timesteps, {latent/observation}_size,\n {latent/observation}_size]])`, which does not depend on the sample shape.\n\n Args:\n x: a float-type `Tensor` with rightmost dimensions\n `[num_timesteps, observation_size]` matching\n `self.event_shape`. Additional dimensions must match or be\n broadcastable to `self.batch_shape`; any further dimensions\n are interpreted as a sample shape.\n\n Returns:\n log_likelihoods: Per-timestep log marginal likelihoods `log\n p(x_t | x_{:t-1})` evaluated at the input `x`, as a `Tensor`\n of shape `sample_shape(x) + batch_shape + [num_timesteps].`\n filtered_means: Means of the per-timestep filtered marginal\n distributions p(z_t | x_{:t}), as a Tensor of shape\n `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`.\n filtered_covs: Covariances of the per-timestep filtered marginal\n distributions p(z_t | x_{:t}), as a Tensor of shape\n `batch_shape + [num_timesteps, latent_size, latent_size]`.\n predicted_means: Means of the per-timestep predictive\n distributions over latent states, p(z_{t+1} | x_{:t}), as a\n Tensor of shape `sample_shape(x) + batch_shape +\n [num_timesteps, latent_size]`.\n predicted_covs: Covariances of the per-timestep predictive\n distributions over latent states, p(z_{t+1} | x_{:t}), as a\n Tensor of shape `batch_shape + [num_timesteps, latent_size,\n latent_size]`.\n observation_means: Means of the per-timestep predictive\n distributions over observations, p(x_{t} | x_{:t-1}), as a\n Tensor of shape `sample_shape(x) + batch_shape +\n [num_timesteps, observation_size]`.\n observation_covs: Covariances of the per-timestep predictive\n distributions over observations, p(x_{t} | x_{:t-1}), as a\n Tensor of shape `batch_shape + [num_timesteps,\n observation_size, observation_size]`.\n \"\"\"\n\n with tf.name_scope(\"forward_filter\", values=[x]):\n x = tf.convert_to_tensor(x, name=\"x\")\n\n # Check event shape statically if possible\n check_shape_op = _check_equal_shape(\n \"x\", x.shape[-2:], tf.shape(x)[-2:],\n self.event_shape, self.event_shape_tensor())\n if self.validate_args:\n runtime_assertions = (self.runtime_assertions\n if check_shape_op is None\n else self.runtime_assertions + [check_shape_op])\n with tf.control_dependencies(runtime_assertions):\n x = tf.identity(x)\n\n # Get the full output sample_shape + batch shape. Usually\n # this will just be x[:-2], i.e. the input shape excluding\n # event shape. But users can specify inputs that broadcast\n # batch dimensions, so we need to broadcast this against\n # self.batch_shape.\n if self.batch_shape.is_fully_defined() and x.shape.is_fully_defined():\n sample_and_batch_shape = tf.broadcast_static_shape(\n x.shape[:-2], self.batch_shape)\n else:\n sample_and_batch_shape = tf.broadcast_dynamic_shape(\n tf.shape(x)[:-2], self.batch_shape_tensor())\n\n # To scan over timesteps we need to move `num_timsteps` from the\n # event shape to the initial dimension of the tensor.\n x = util.move_dimension(x, -2, 0)\n\n # Observations are assumed to be vectors, but we add a dummy\n # extra dimension to allow us to use `matmul` throughout.\n x = x[..., tf.newaxis]\n\n # Initialize filtering distribution from the prior. The mean in\n # a Kalman filter depends on data, so should match the full\n # sample and batch shape. The covariance is data-independent, so\n # only has batch shape.\n prior_mean = _broadcast_to_shape(\n self.initial_state_prior.mean()[..., tf.newaxis],\n tf.concat([sample_and_batch_shape,\n [self.latent_size, 1]], axis=0))\n prior_cov = _broadcast_to_shape(\n self.initial_state_prior.covariance(),\n tf.concat([self.batch_shape_tensor(),\n [self.latent_size, self.latent_size]], axis=0))\n\n initial_observation_matrix = (\n self.get_observation_matrix_for_timestep(self.initial_step))\n initial_observation_noise = (\n self.get_observation_noise_for_timestep(self.initial_step))\n\n initial_observation_mean = _propagate_mean(prior_mean,\n initial_observation_matrix,\n initial_observation_noise)\n initial_observation_cov = _propagate_cov(prior_cov,\n initial_observation_matrix,\n initial_observation_noise)\n\n initial_state = KalmanFilterState(\n predicted_mean=prior_mean,\n predicted_cov=prior_cov,\n filtered_mean=prior_mean, # establishes shape, value ignored\n filtered_cov=prior_cov, # establishes shape, value ignored\n observation_mean=initial_observation_mean,\n observation_cov=initial_observation_cov,\n log_marginal_likelihood=tf.zeros(\n shape=sample_and_batch_shape, dtype=self.dtype),\n timestep=tf.convert_to_tensor(\n self.initial_step, dtype=tf.int32, name=\"initial_step\"))\n\n update_step_fn = build_kalman_filter_step(\n self.get_transition_matrix_for_timestep,\n self.get_transition_noise_for_timestep,\n self.get_observation_matrix_for_timestep,\n self.get_observation_noise_for_timestep)\n\n filter_states = tf.scan(update_step_fn,\n elems=x,\n initializer=initial_state)\n\n log_likelihoods = util.move_dimension(\n filter_states.log_marginal_likelihood, 0, -1)\n\n # Move the time dimension back into the event shape.\n filtered_means = util.move_dimension(\n filter_states.filtered_mean[..., 0], 0, -2)\n filtered_covs = util.move_dimension(\n filter_states.filtered_cov, 0, -3)\n predicted_means = util.move_dimension(\n filter_states.predicted_mean[..., 0], 0, -2)\n predicted_covs = util.move_dimension(\n filter_states.predicted_cov, 0, -3)\n observation_means = util.move_dimension(\n filter_states.observation_mean[..., 0], 0, -2)\n observation_covs = util.move_dimension(\n filter_states.observation_cov, 0, -3)\n # We could directly construct the batch Distributions\n # filtered_marginals = tfd.MultivariateNormalFullCovariance(\n # filtered_means, filtered_covs)\n # predicted_marginals = tfd.MultivariateNormalFullCovariance(\n # predicted_means, predicted_covs)\n # but we choose not to: returning the raw means and covariances\n # saves computation in Eager mode (avoiding an immediate\n # Cholesky factorization that the user may not want) and aids\n # debugging of numerical issues.\n\n return (log_likelihoods,\n filtered_means, filtered_covs,\n predicted_means, predicted_covs,\n observation_means, observation_covs)\n\n def _mean(self):\n _, observation_mean = self._joint_mean()\n return observation_mean\n\n def _joint_mean(self):\n \"\"\"Compute prior means for all variables via dynamic programming.\n\n Returns:\n latent_means: Prior means of latent states `z_t`, as a `Tensor`\n of shape `batch_shape + [num_timesteps, latent_size]`\n observation_means: Prior covariance matrices of observations\n `x_t`, as a `Tensor` of shape `batch_shape + [num_timesteps,\n observation_size]`\n \"\"\"\n\n with tf.name_scope(\"mean_joint\"):\n\n # The initial timestep is a special case, since we sample the\n # latent state from the prior rather than the transition model.\n\n with tf.control_dependencies(self.runtime_assertions):\n # Broadcast to ensure we represent the full batch shape.\n initial_latent_mean = _broadcast_to_shape(\n self.initial_state_prior.mean()[..., tf.newaxis],\n tf.concat([self.batch_shape_tensor(),\n [self.latent_size, 1]], axis=0))\n\n initial_observation_mean = _propagate_mean(\n initial_latent_mean,\n self.get_observation_matrix_for_timestep(self.initial_step),\n self.get_observation_noise_for_timestep(self.initial_step))\n\n mean_step = build_kalman_mean_step(\n self.get_transition_matrix_for_timestep,\n self.get_transition_noise_for_timestep,\n self.get_observation_matrix_for_timestep,\n self.get_observation_noise_for_timestep)\n\n # Scan over all timesteps following the initial step.\n (latent_means, observation_means) = tf.scan(\n mean_step,\n elems=tf.range(self.initial_step+1, self.final_step),\n initializer=(initial_latent_mean, initial_observation_mean))\n\n # Squish the initial step back on top of the other (scanned) timesteps\n latent_means = tf.concat([initial_latent_mean[tf.newaxis, ...],\n latent_means], axis=0)\n observation_means = tf.concat([initial_observation_mean[tf.newaxis, ...],\n observation_means], axis=0)\n\n # Put dimensions back in order. The samples we've computed have\n # shape `[num_timesteps, batch_shape, size, 1]`, where `size`\n # is the dimension of the latent or observation spaces\n # respectively, but we want to return values with shape\n # `[batch_shape, num_timesteps, size]`.\n latent_means = tf.squeeze(latent_means, -1)\n latent_means = util.move_dimension(latent_means, 0, -2)\n observation_means = tf.squeeze(observation_means, -1)\n observation_means = util.move_dimension(observation_means, 0, -2)\n\n return latent_means, observation_means\n\n def _joint_covariances(self):\n \"\"\"Compute prior covariances for all variables via dynamic programming.\n\n Returns:\n latent_covs: Prior covariance matrices of latent states `z_t`, as\n a `Tensor` of shape `batch_shape + [num_timesteps,\n latent_size, latent_size]`\n observation_covs: Prior covariance matrices of observations\n `x_t`, as a `Tensor` of shape `batch_shape + [num_timesteps,\n observation_size, observation_size]`\n \"\"\"\n\n with tf.name_scope(\"covariance_joint\"):\n\n with tf.control_dependencies(self.runtime_assertions):\n initial_latent_cov = _broadcast_to_shape(\n self.initial_state_prior.covariance(),\n tf.concat([self.batch_shape_tensor(),\n [self.latent_size, self.latent_size]], axis=0))\n\n initial_observation_cov = _propagate_cov(\n initial_latent_cov,\n self.get_observation_matrix_for_timestep(self.initial_step),\n self.get_observation_noise_for_timestep(self.initial_step))\n\n cov_step = build_kalman_cov_step(\n self.get_transition_matrix_for_timestep,\n self.get_transition_noise_for_timestep,\n self.get_observation_matrix_for_timestep,\n self.get_observation_noise_for_timestep)\n\n # Scan over all timesteps following the initial step.\n (latent_covs, observation_covs) = tf.scan(\n cov_step,\n elems=tf.range(self.initial_step+1, self.final_step),\n initializer=(initial_latent_cov, initial_observation_cov))\n\n # Squish the initial step back on top of the other (scanned) timesteps\n latent_covs = tf.concat([initial_latent_cov[tf.newaxis, ...],\n latent_covs], axis=0)\n observation_covs = tf.concat([initial_observation_cov[tf.newaxis, ...],\n observation_covs], axis=0)\n\n # Put dimensions back in order. The samples we've computed have\n # shape `[num_timesteps, batch_shape, size, size]`, where `size`\n # is the dimension of the state or observation spaces\n # respectively, but we want to return values with shape\n # `[batch_shape, num_timesteps, size, size]`.\n latent_covs = util.move_dimension(latent_covs, 0, -3)\n observation_covs = util.move_dimension(observation_covs, 0, -3)\n return latent_covs, observation_covs\n\n def _variance(self):\n _, observation_covs = self._joint_covariances()\n return tf.matrix_diag_part(observation_covs)\n\n\nKalmanFilterState = collections.namedtuple(\"KalmanFilterState\", [\n \"filtered_mean\", \"filtered_cov\",\n \"predicted_mean\", \"predicted_cov\",\n \"observation_mean\", \"observation_cov\",\n \"log_marginal_likelihood\", \"timestep\"])\n\n\ndef build_kalman_filter_step(get_transition_matrix_for_timestep,\n get_transition_noise_for_timestep,\n get_observation_matrix_for_timestep,\n get_observation_noise_for_timestep):\n \"\"\"Build a callable that performs one step of Kalman filtering.\n\n Args:\n get_transition_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[latent_size, latent_size]`.\n get_transition_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[latent_size]`.\n get_observation_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[observation_size, observation_size]`.\n get_observation_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[observation_size]`.\n\n Returns:\n kalman_filter_step: a callable that updates a KalmanFilterState\n from timestep `t-1` to `t`.\n \"\"\"\n\n def kalman_filter_step(state, x_t):\n \"\"\"Run a single step of Kalman filtering.\n\n Args:\n state: A `KalmanFilterState` object representing the previous\n filter state at time `t-1`.\n x_t: A `Tensor` with event shape `[observation_size, 1]`,\n representing the vector observed at time `t`.\n\n Returns:\n new_state: A `KalmanFilterState` object representing the new\n filter state at time `t`.\n \"\"\"\n\n # Given predicted mean u_{t|t-1} and covariance P_{t|t-1} from the\n # previous step, incorporate the observation x_t, producing the\n # filtered mean u_t and covariance P_t.\n (filtered_mean,\n filtered_cov,\n observation_dist) = linear_gaussian_update(\n state.predicted_mean, state.predicted_cov,\n get_observation_matrix_for_timestep(state.timestep),\n get_observation_noise_for_timestep(state.timestep),\n x_t)\n\n # Compute the marginal likelihood p(x_{t} | x_{:t-1}) for this\n # observation.\n log_marginal_likelihood = observation_dist.log_prob(x_t[..., 0])\n\n # Run the filtered posterior through the transition\n # model to predict the next time step:\n # u_{t|t-1} = F_t u_{t-1} + b_t\n # P_{t|t-1} = F_t P_{t-1} F_t' + Q_t\n predicted_mean, predicted_cov = kalman_transition(\n filtered_mean,\n filtered_cov,\n get_transition_matrix_for_timestep(state.timestep),\n get_transition_noise_for_timestep(state.timestep))\n\n return KalmanFilterState(\n filtered_mean, filtered_cov,\n predicted_mean, predicted_cov,\n observation_dist.mean()[..., tf.newaxis],\n observation_dist.covariance(),\n log_marginal_likelihood,\n state.timestep+1)\n\n return kalman_filter_step\n\n\ndef linear_gaussian_update(\n prior_mean, prior_cov, observation_matrix, observation_noise, x_observed):\n \"\"\"Conjugate update for a linear Gaussian model.\n\n Given a normal prior on a latent variable `z`,\n `p(z) = N(prior_mean, prior_cov) = N(u, P)`,\n for which we observe a linear Gaussian transformation `x`,\n `p(x|z) = N(H * z + c, R)`,\n the posterior is also normal:\n `p(z|x) = N(u*, P*)`.\n\n We can write this update as\n x_expected = H * u + c # pushforward prior mean\n S = R + H * P * H' # pushforward prior cov\n K = P * H' * S^{-1} # optimal Kalman gain\n u* = u + K * (x_observed - x_expected) # posterior mean\n P* = (I - K * H) * P (I - K * H)' + K * R * K' # posterior cov\n (see, e.g., https://en.wikipedia.org/wiki/Kalman_filter#Update)\n\n Args:\n prior_mean: `Tensor` with event shape `[latent_size, 1]` and\n potential batch shape `B = [b1, ..., b_n]`.\n prior_cov: `Tensor` with event shape `[latent_size, latent_size]`\n and batch shape `B` (matching `prior_mean`).\n observation_matrix: `LinearOperator` with shape\n `[observation_size, latent_size]` and batch shape broadcastable\n to `B`.\n observation_noise: potentially-batched\n `MultivariateNormalLinearOperator` instance with event shape\n `[observation_size]` and batch shape broadcastable to `B`.\n x_observed: potentially batched `Tensor` with event shape\n `[observation_size, 1]` and batch shape `B`.\n\n Returns:\n posterior_mean: `Tensor` with event shape `[latent_size, 1]` and\n batch shape `B`.\n posterior_cov: `Tensor` with event shape `[latent_size,\n latent_size]` and batch shape `B`.\n predictive_dist: the prior predictive distribution `p(x|z)`,\n as a `Distribution` instance with event\n shape `[observation_size]` and batch shape `B`. This will\n typically be `tfd.MultivariateNormalTriL`, but when\n `observation_size=1` we return a `tfd.Independent(tfd.Normal)`\n instance as an optimization.\n \"\"\"\n\n # If observations are scalar, we can avoid some matrix ops.\n observation_size_is_static_and_scalar = (\n tf.dimension_value(observation_matrix.shape[-2]) == 1)\n\n # Push the predicted mean for the latent state through the\n # observation model\n x_expected = _propagate_mean(prior_mean,\n observation_matrix,\n observation_noise)\n\n # Push the predictive covariance of the latent state through the\n # observation model:\n # S = R + H * P * H'.\n # We use a temporary variable for H * P,\n # reused below to compute Kalman gain.\n tmp_obs_cov = observation_matrix.matmul(prior_cov)\n predicted_obs_cov = (\n observation_matrix.matmul(tmp_obs_cov, adjoint_arg=True)\n + observation_noise.covariance())\n\n # Compute optimal Kalman gain:\n # K = P * H' * S^{-1}\n # Since both S and P are cov matrices, thus symmetric,\n # we can take the transpose and reuse our previous\n # computation:\n # = (S^{-1} * H * P)'\n # = (S^{-1} * tmp_obs_cov) '\n # = (S \\ tmp_obs_cov)'\n if observation_size_is_static_and_scalar:\n gain_transpose = tmp_obs_cov/predicted_obs_cov\n else:\n predicted_obs_cov_chol = tf.cholesky(predicted_obs_cov)\n gain_transpose = tf.cholesky_solve(predicted_obs_cov_chol, tmp_obs_cov)\n\n # Compute the posterior mean, incorporating the observation.\n # u* = u + K (x_observed - x_expected)\n posterior_mean = (prior_mean +\n _matmul(gain_transpose, x_observed - x_expected,\n adjoint_a=True))\n\n # For the posterior covariance, we could use the simple update\n # P* = P - K * H * P\n # but this is prone to numerical issues because it subtracts a\n # value from a PSD matrix. We choose instead to use the more\n # expensive Jordan form update\n # P* = (I - K H) * P * (I - K H)' + K R K'\n # which always produces a PSD result. This uses\n # tmp_term = (I - K * H)'\n # as an intermediate quantity.\n tmp_term = -observation_matrix.matmul(gain_transpose, adjoint=True) # -K * H\n tmp_term = tf.matrix_set_diag(tmp_term, tf.matrix_diag_part(tmp_term) + 1)\n posterior_cov = (\n _matmul(tmp_term, _matmul(prior_cov, tmp_term), adjoint_a=True)\n + _matmul(gain_transpose,\n _matmul(observation_noise.covariance(), gain_transpose),\n adjoint_a=True))\n\n if observation_size_is_static_and_scalar:\n # A plain Normal would have event shape `[]`; wrapping with Independent\n # ensures `event_shape=[1]` as required.\n predictive_dist = independent.Independent(\n normal.Normal(loc=x_expected[..., 0],\n scale=tf.sqrt(predicted_obs_cov[..., 0])),\n reinterpreted_batch_ndims=1)\n\n # Minor hack to define the covariance, so that `predictive_dist` can pass as\n # an MVNTriL-like object.\n predictive_dist.covariance = lambda: predicted_obs_cov\n else:\n predictive_dist = mvn_tril.MultivariateNormalTriL(\n loc=x_expected[..., 0],\n scale_tril=predicted_obs_cov_chol)\n\n return posterior_mean, posterior_cov, predictive_dist\n\n\ndef kalman_transition(filtered_mean, filtered_cov,\n transition_matrix, transition_noise):\n \"\"\"Propagate a filtered distribution through a transition model.\"\"\"\n\n predicted_mean = _propagate_mean(filtered_mean,\n transition_matrix,\n transition_noise)\n predicted_cov = _propagate_cov(filtered_cov,\n transition_matrix,\n transition_noise)\n return predicted_mean, predicted_cov\n\n\ndef build_kalman_mean_step(get_transition_matrix_for_timestep,\n get_transition_noise_for_timestep,\n get_observation_matrix_for_timestep,\n get_observation_noise_for_timestep):\n \"\"\"Build a callable that performs one step of Kalman mean recursion.\n\n Args:\n get_transition_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[latent_size, latent_size]`.\n get_transition_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[latent_size]`.\n get_observation_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[observation_size, observation_size]`.\n get_observation_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[observation_size]`.\n\n Returns:\n kalman_mean_step: a callable that computes latent state and\n observation means at time `t`, given latent mean at time `t-1`.\n \"\"\"\n\n def mean_step(previous_means, t):\n \"\"\"Single step of prior mean recursion.\"\"\"\n previous_latent_mean, _ = previous_means\n\n latent_mean = _propagate_mean(previous_latent_mean,\n get_transition_matrix_for_timestep(t - 1),\n get_transition_noise_for_timestep(t - 1))\n observation_mean = _propagate_mean(latent_mean,\n get_observation_matrix_for_timestep(t),\n get_observation_noise_for_timestep(t))\n return (latent_mean, observation_mean)\n\n return mean_step\n\n\ndef build_kalman_cov_step(get_transition_matrix_for_timestep,\n get_transition_noise_for_timestep,\n get_observation_matrix_for_timestep,\n get_observation_noise_for_timestep):\n \"\"\"Build a callable for one step of Kalman covariance recursion.\n\n Args:\n get_transition_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[latent_size, latent_size]`.\n get_transition_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[latent_size]`.\n get_observation_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[observation_size, observation_size]`.\n get_observation_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[observation_size]`.\n\n Returns:\n cov_step: a callable that computes latent state and observation\n covariance at time `t`, given latent covariance at time `t-1`.\n \"\"\"\n\n def cov_step(previous_covs, t):\n \"\"\"Single step of prior covariance recursion.\"\"\"\n previous_latent_cov, _ = previous_covs\n\n latent_cov = _propagate_cov(\n previous_latent_cov,\n get_transition_matrix_for_timestep(t - 1),\n get_transition_noise_for_timestep(t - 1))\n observation_cov = _propagate_cov(\n latent_cov,\n get_observation_matrix_for_timestep(t),\n get_observation_noise_for_timestep(t))\n\n return (latent_cov, observation_cov)\n\n return cov_step\n\n\ndef build_kalman_sample_step(get_transition_matrix_for_timestep,\n get_transition_noise_for_timestep,\n get_observation_matrix_for_timestep,\n get_observation_noise_for_timestep,\n full_sample_and_batch_shape,\n stream,\n validate_args=False):\n \"\"\"Build a callable for one step of Kalman sampling recursion.\n\n Args:\n get_transition_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[latent_size, latent_size]`.\n get_transition_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[latent_size]`.\n get_observation_matrix_for_timestep: callable taking a timestep\n as an integer `Tensor` argument, and returning a `LinearOperator`\n of shape `[observation_size, observation_size]`.\n get_observation_noise_for_timestep: callable taking a timestep as\n an integer `Tensor` argument, and returning a\n `MultivariateNormalLinearOperator` of event shape\n `[observation_size]`.\n full_sample_and_batch_shape: Desired sample and batch shape of the\n returned samples, concatenated in a single `Tensor`.\n stream: `tfd.SeedStream` instance used to generate a\n sequence of random seeds.\n validate_args: if True, perform error checking at runtime.\n\n Returns:\n sample_step: a callable that samples the latent state and\n observation at time `t`, given latent state at time `t-1`.\n \"\"\"\n\n def sample_step(sampled_prev, t):\n \"\"\"Sample values for a single timestep.\"\"\"\n latent_prev, _ = sampled_prev\n\n transition_matrix = get_transition_matrix_for_timestep(t - 1)\n transition_noise = get_transition_noise_for_timestep(t - 1)\n\n latent_pred = transition_matrix.matmul(latent_prev)\n latent_sampled = latent_pred + transition_noise.sample(\n sample_shape=_augment_sample_shape(\n transition_noise,\n full_sample_and_batch_shape,\n validate_args),\n seed=stream())[..., tf.newaxis]\n\n observation_matrix = get_observation_matrix_for_timestep(t)\n observation_noise = get_observation_noise_for_timestep(t)\n\n observation_pred = observation_matrix.matmul(latent_sampled)\n observation_sampled = observation_pred + observation_noise.sample(\n sample_shape=_augment_sample_shape(\n observation_noise,\n full_sample_and_batch_shape,\n validate_args),\n seed=stream())[..., tf.newaxis]\n\n return (latent_sampled, observation_sampled)\n\n return sample_step\n\n\ndef _propagate_mean(mean, linop, dist):\n \"\"\"Propagate a mean through linear Gaussian transformation.\"\"\"\n return linop.matmul(mean) + dist.mean()[..., tf.newaxis]\n\n\ndef _propagate_cov(cov, linop, dist):\n \"\"\"Propagate covariance through linear Gaussian transformation.\"\"\"\n # For linop A and input cov P, returns `A P A' + dist.cov()`\n return linop.matmul(linop.matmul(cov), adjoint_arg=True) + dist.covariance()\n" ]
[ [ "numpy.log", "tensorflow.atanh", "tensorflow.nn.tanh", "tensorflow.square", "tensorflow.nn.softplus" ], [ "tensorflow.matmul", "numpy.log", "tensorflow.Graph", "tensorflow.reduce_mean", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.test.main", "tensorflow.dimension_value", "numpy.linalg.cholesky", "tensorflow.squared_difference" ], [ "tensorflow.convert_to_tensor", "tensorflow.TensorShape", "tensorflow.executing_eagerly", "tensorflow.constant", "tensorflow.shape", "tensorflow.placeholder_with_default", "tensorflow.test.main", "numpy.ones", "tensorflow.name_scope", "numpy.float32", "numpy.zeros", "tensorflow.random_normal" ], [ "tensorflow.TensorShape", "numpy.log", "tensorflow.constant", "numpy.arange", "tensorflow.placeholder_with_default", "tensorflow.test.main", "tensorflow.zeros_like", "numpy.array", "scipy.stats.pareto" ], [ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.scan", "tensorflow.control_dependencies", "tensorflow.zeros", "tensorflow.matrix_diag_part", "tensorflow.reduce_sum", "tensorflow.stack", "tensorflow.cholesky", "tensorflow.cholesky_solve", "tensorflow.squeeze", "tensorflow.broadcast_static_shape", "tensorflow.name_scope", "tensorflow.TensorShape", "tensorflow.shape", "tensorflow.identity", "tensorflow.dimension_value", "tensorflow.range", "tensorflow.sqrt", "tensorflow.assert_same_float_dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "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": [ "1.13" ] }, { "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": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "1.2" ] } ]
iamlmn/monte_carlo_analysis
[ "45f7af2b439f80bce429a94257a1167c9d5f4a2c" ]
[ "scenario analysis/portfolio_evaluation.py" ]
[ "import yfinance\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\ndef _simulate_returns(historical_returns,forecast_days):\n return historical_returns.sample(n = forecast_days, \n replace = True).reset_index(drop = True)\n\n\ndef simulate_modified_returns(\n historical_returns,\n forecast_days,\n correct_mean_by):\n h = historical_returns.copy()\n new_series = h + correct_mean_by\n return new_series.sample(n=forecast_days, \n replace = True).reset_index(drop=True)\n\n\ndef simulate_portfolio(historical_returns,composition,forecast_days):\n result = 0\n for t in tqdm(composition):\n name,weight = t[0],t[1]\n s = _simulate_returns(historical_returns['return_%s' % (name)], forecast_days)\n result = result + s * weight\n \n return(result)\n\n\ndef simulate_modified_portfolio(\n historical_returns,\n composition,\n forecast_days):\n \n result = 0\n \n for t in composition:\n name,weight,correction = t[0],t[1],t[2]\n s = simulate_modified_returns(\n historical_returns['return_%s' % (name)], \n forecast_days,correction\n )\n \n result = result + s * weight\n return(result)\n\n\n\ndef simulation(historical_returns,composition,forecast_days,n_iterations):\n simulated_portfolios = None\n\n for i in range(n_iterations):\n sim = simulate_modified_portfolio(historical_returns,composition,forecast_days)\n\n sim_port = pd.DataFrame({'returns_%d' % (i) : sim})\n\n if simulated_portfolios is None:\n simulated_portfolios = sim_port\n else:\n simulated_portfolios = simulated_portfolios.join(sim_port)\n \n return simulated_portfolios\n\nif __name__ == '__main__':\n portfolio_composition = [('MSFT',0.5),('AAPL',0.2),('GOOG',0.3)]\n returns = pd.DataFrame({})\n\n # create returns portfolio dataframe\n\n \n for t in portfolio_composition:\n name = t[0]\n ticker = yfinance.Ticker(name)\n data = ticker.history(interval=\"1d\",start=\"2010-01-01\",end=\"2019-12-31\")\n data['return_%s' % (name)] = data['Close'].pct_change(1)\n returns = returns.join(data[['return_%s' % (name)]],how=\"outer\").dropna()\n\n # Monte Carlo simulation of a portfolio\n\n \n # simulate_portfolio(returns,portfolio_composition,10)\n # This may be enough for portfolio simulation, but we want something more, that is the what-if analysis.\n\n # print(\"The historical average returns are : \\n\", returns.mean(axis=0))\n \n '''\n If we perform portfolio simulation as shown before, \n we are simply saying that the future returns are a random sample \n of the past returns. We already know this isn’t completely true. \n Moreover, maybe we are performing scenario analysis because \n we want to know what happens if certain conditions will occur. \n For example, what happens if the average daily return of each stock \n is lower than its historical value?If we perform portfolio \n simulation as shown before, we are simply saying that the future returns \n are a random sample of the past returns. We already know this \n isn’t completely true. Moreover, maybe we are performing scenario analysis \n because we want to know what happens if certain conditions will occur. \n For example, what happens if the average daily return of each \n stock is lower than its historical value?\n '''\n\n print('Let’s try to simulate what happens if the average \\\n returns drop by -0.0001 for MSFT, -0.001 for AAPL and -0.0005 for GOOG. \\\n We must subtract these quantities from each stock and then simulate the \\\n future portfolios with the new, modified data.')\n\n\n\n # We’ll add these corrections directly to the portfolio_composition list (they are the third component of each tuple):\n\n new_portfolio_composition = [\n ('MSFT', 0.5,-0.0001), \n ('AAPL', 0.2,-0.001), \n ('GOOG', 0.3,-0.0005)\n]\n\n # Simulations and results\n\n forecast_days = 20\n n_iterations = 200\n\n simulated_portfolios = simulation(returns,\n new_portfolio_composition,forecast_days,n_iterations)\n\n\n\n # Taken the daily returns of a portfolio, we can build the return after N days with the compound interest formula:\n\n percentile_5th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,5),axis=1)\n percentile_95th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,95),axis=1)\n average_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x),axis=1)\n print(percentile_5th.tail(1))\n print(percentile_95th.tail(1))\n print(average_port.tail(1))\n\n # Confidence interval for future portfolios\n x = range(forecast_days)\n\n plt.rcParams['figure.figsize'] = [10, 10]\n\n plt.plot(x,average_port,label=\"Average portfolio\")\n plt.xlabel(\"Day\")\n plt.ylabel(\"Portfolio return\")\n\n\n plt.fill_between(x, percentile_5th, percentile_95th,alpha=0.2)\n plt.grid()\n plt.legend()\n\n plt.show()\n\n\n # Probability of beating the portfolio target\n\n target_return = 0.02\n target_prob_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x > target_return),axis=1)\n\n print(\"Probabilityof beating the portfolio target {} \".format(target_return),target_prob_port.tail(1))\n\n\n # The size of the error bars is calculated with the standard error formula:\n err_bars = np.sqrt(\n target_prob_port * (1-target_prob_port) / n_iterations\n )\n x = range(forecast_days)\n plt.rcParams['figure.figsize'] = [10, 10]\n plt.bar(x,target_prob_port,yerr = err_bars)\n plt.xlabel(\"Day\")\n plt.ylabel(\"Probability of return >= %.2f\" % (target_return))\n plt.grid()\n plt.show()\n\n\n\n # Sharpe ratio histogram\n '''\n performance metric of a portfolio\n '''\n\n sharpe_indices = simulated_portfolios.apply(lambda x : np.mean(x)/np.std(x))\n plt.hist(sharpe_indices,bins=\"rice\")\n plt.xlabel(\"Sharpe ratio\")\n plt.show()\n print(\"Sharpe ratio mean value\",np.mean(sharpe_indices))" ]
[ [ "matplotlib.pyplot.legend", "numpy.sqrt", "pandas.DataFrame", "numpy.percentile", "matplotlib.pyplot.plot", "numpy.std", "numpy.mean", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.grid", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel" ] ]
[ { "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": [] } ]
rtg0795/tfx
[ "63c31b719896eef645df3850d0e6b946e44cd059", "63c31b719896eef645df3850d0e6b946e44cd059", "63c31b719896eef645df3850d0e6b946e44cd059", "63c31b719896eef645df3850d0e6b946e44cd059", "63c31b719896eef645df3850d0e6b946e44cd059" ]
[ "tfx/orchestration/portable/python_executor_operator_test.py", "tfx/orchestration/kubeflow/kubeflow_dag_runner_test.py", "tfx/utils/name_utils_test.py", "tfx/dsl/components/base/base_component_test.py", "tfx/orchestration/experimental/interactive/interactive_context_test.py" ]
[ "# Copyright 2020 Google LLC. 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 tfx.orchestration.portable.python_executor_operator.\"\"\"\n\nimport os\nfrom typing import Any, Dict, List\n\nimport tensorflow as tf\nfrom tfx import types\nfrom tfx.dsl.components.base import base_executor\nfrom tfx.dsl.io import fileio\nfrom tfx.orchestration.portable import data_types\nfrom tfx.orchestration.portable import outputs_utils\nfrom tfx.orchestration.portable import python_executor_operator\nfrom tfx.proto.orchestration import executable_spec_pb2\nfrom tfx.proto.orchestration import execution_result_pb2\nfrom tfx.proto.orchestration import pipeline_pb2\nfrom tfx.types import standard_artifacts\nfrom tfx.utils import test_case_utils\n\nfrom google.protobuf import text_format\n\n\nclass InprocessExecutor(base_executor.BaseExecutor):\n \"\"\"A Fake in-process executor what returns execution result.\"\"\"\n\n def Do(\n self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> execution_result_pb2.ExecutorOutput:\n executor_output = execution_result_pb2.ExecutorOutput()\n outputs_utils.populate_output_artifact(executor_output, output_dict)\n outputs_utils.populate_exec_properties(executor_output, exec_properties)\n return executor_output\n\n\nclass NotInprocessExecutor(base_executor.BaseExecutor):\n \"\"\"A Fake not-in-process executor what writes execution result to executor_output_uri.\"\"\"\n\n def Do(self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> None:\n executor_output = execution_result_pb2.ExecutorOutput()\n outputs_utils.populate_output_artifact(executor_output, output_dict)\n outputs_utils.populate_exec_properties(executor_output, exec_properties)\n with fileio.open(self._context.executor_output_uri, 'wb') as f:\n f.write(executor_output.SerializeToString())\n\n\nclass InplaceUpdateExecutor(base_executor.BaseExecutor):\n \"\"\"A Fake executor that uses the executor Context to compute its output.\"\"\"\n\n def Do(self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> None:\n model = output_dict['output_key'][0]\n model.name = '{0}.{1}.my_model'.format(\n self._context.pipeline_info.id,\n self._context.pipeline_node.node_info.id)\n\n\nclass PythonExecutorOperatorTest(test_case_utils.TfxTest):\n\n def _get_execution_info(self, input_dict, output_dict, exec_properties):\n pipeline_node = pipeline_pb2.PipelineNode(node_info={'id': 'MyPythonNode'})\n pipeline_info = pipeline_pb2.PipelineInfo(id='MyPipeline')\n stateful_working_dir = os.path.join(self.tmp_dir, 'stateful_working_dir')\n executor_output_uri = os.path.join(self.tmp_dir, 'executor_output')\n return data_types.ExecutionInfo(\n execution_id=1,\n input_dict=input_dict,\n output_dict=output_dict,\n exec_properties=exec_properties,\n stateful_working_dir=stateful_working_dir,\n execution_output_uri=executor_output_uri,\n pipeline_node=pipeline_node,\n pipeline_info=pipeline_info,\n pipeline_run_id=99)\n\n def testRunExecutor_with_InprocessExecutor(self):\n executor_sepc = text_format.Parse(\n \"\"\"\n class_path: \"tfx.orchestration.portable.python_executor_operator_test.InprocessExecutor\"\n \"\"\", executable_spec_pb2.PythonClassExecutableSpec())\n operator = python_executor_operator.PythonExecutorOperator(executor_sepc)\n input_dict = {'input_key': [standard_artifacts.Examples()]}\n output_dict = {'output_key': [standard_artifacts.Model()]}\n exec_properties = {'key': 'value'}\n executor_output = operator.run_executor(\n self._get_execution_info(input_dict, output_dict, exec_properties))\n self.assertProtoPartiallyEquals(\n \"\"\"\n execution_properties {\n key: \"key\"\n value {\n string_value: \"value\"\n }\n }\n output_artifacts {\n key: \"output_key\"\n value {\n artifacts {\n }\n }\n }\"\"\", executor_output)\n\n def testRunExecutor_with_NotInprocessExecutor(self):\n executor_sepc = text_format.Parse(\n \"\"\"\n class_path: \"tfx.orchestration.portable.python_executor_operator_test.NotInprocessExecutor\"\n \"\"\", executable_spec_pb2.PythonClassExecutableSpec())\n operator = python_executor_operator.PythonExecutorOperator(executor_sepc)\n input_dict = {'input_key': [standard_artifacts.Examples()]}\n output_dict = {'output_key': [standard_artifacts.Model()]}\n exec_properties = {'key': 'value'}\n executor_output = operator.run_executor(\n self._get_execution_info(input_dict, output_dict, exec_properties))\n self.assertProtoPartiallyEquals(\n \"\"\"\n execution_properties {\n key: \"key\"\n value {\n string_value: \"value\"\n }\n }\n output_artifacts {\n key: \"output_key\"\n value {\n artifacts {\n }\n }\n }\"\"\", executor_output)\n\n def testRunExecutor_with_InplaceUpdateExecutor(self):\n executor_sepc = text_format.Parse(\n \"\"\"\n class_path: \"tfx.orchestration.portable.python_executor_operator_test.InplaceUpdateExecutor\"\n \"\"\", executable_spec_pb2.PythonClassExecutableSpec())\n operator = python_executor_operator.PythonExecutorOperator(executor_sepc)\n input_dict = {'input_key': [standard_artifacts.Examples()]}\n output_dict = {'output_key': [standard_artifacts.Model()]}\n exec_properties = {\n 'string': 'value',\n 'int': 1,\n 'float': 0.0,\n # This should not happen on production and will be\n # dropped.\n 'proto': execution_result_pb2.ExecutorOutput()\n }\n executor_output = operator.run_executor(\n self._get_execution_info(input_dict, output_dict, exec_properties))\n self.assertProtoPartiallyEquals(\n \"\"\"\n execution_properties {\n key: \"float\"\n value {\n double_value: 0.0\n }\n }\n execution_properties {\n key: \"int\"\n value {\n int_value: 1\n }\n }\n execution_properties {\n key: \"string\"\n value {\n string_value: \"value\"\n }\n }\n output_artifacts {\n key: \"output_key\"\n value {\n artifacts {\n custom_properties {\n key: \"name\"\n value {\n string_value: \"MyPipeline.MyPythonNode.my_model\"\n }\n }\n name: \"MyPipeline.MyPythonNode.my_model\"\n }\n }\n }\"\"\", executor_output)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for tfx.orchestration.kubeflow.kubeflow_dag_runner.\"\"\"\n\nimport json\nimport os\nimport tarfile\nfrom typing import List\n\nfrom kfp import onprem\nimport tensorflow as tf\nfrom tfx.components.statistics_gen import component as statistics_gen_component\nfrom tfx.dsl.component.experimental import executor_specs\nfrom tfx.dsl.component.experimental.annotations import Parameter\nfrom tfx.dsl.component.experimental.decorators import component\nfrom tfx.dsl.components.base import base_component\nfrom tfx.dsl.io import fileio\nfrom tfx.extensions.google_cloud_big_query.example_gen import component as big_query_example_gen_component\nfrom tfx.orchestration import data_types\nfrom tfx.orchestration import pipeline as tfx_pipeline\nfrom tfx.orchestration.kubeflow import kubeflow_dag_runner\nfrom tfx.orchestration.kubeflow.decorators import FinalStatusStr\nfrom tfx.proto import example_gen_pb2\nfrom tfx.types import component_spec\nfrom tfx.utils import telemetry_utils\nfrom tfx.utils import test_case_utils\nimport yaml\n\nfrom ml_metadata.proto import metadata_store_pb2\n\n\n@component\ndef _say_hi(status: Parameter[str]):\n print(status)\n\n\n# 2-step pipeline under test.\ndef _two_step_pipeline() -> tfx_pipeline.Pipeline:\n default_input_config = json.dumps({\n 'splits': [{\n 'name': 'single_split',\n 'pattern': 'SELECT * FROM default-table'\n }]\n })\n input_config = data_types.RuntimeParameter(\n name='input_config', ptype=str, default=default_input_config)\n example_gen = big_query_example_gen_component.BigQueryExampleGen(\n input_config=input_config, output_config=example_gen_pb2.Output())\n statistics_gen = statistics_gen_component.StatisticsGen(\n examples=example_gen.outputs['examples'])\n return tfx_pipeline.Pipeline(\n pipeline_name='two_step_pipeline',\n pipeline_root='pipeline_root',\n metadata_connection_config=metadata_store_pb2.ConnectionConfig(),\n components=[example_gen, statistics_gen],\n )\n\n\nclass _DummySpec(component_spec.ComponentSpec):\n INPUTS = {}\n OUTPUTS = {}\n PARAMETERS = {}\n\n\nclass _DummyComponent(base_component.BaseComponent):\n SPEC_CLASS = _DummySpec\n EXECUTOR_SPEC = executor_specs.TemplatedExecutorContainerSpec(\n image='dummy:latest', command=['ls'])\n\n def __init__(self):\n super().__init__(_DummySpec())\n\n\ndef _container_component_pipeline() -> tfx_pipeline.Pipeline:\n return tfx_pipeline.Pipeline(\n pipeline_name='container_component_pipeline',\n pipeline_root='pipeline_root',\n metadata_connection_config=metadata_store_pb2.ConnectionConfig(),\n components=[_DummyComponent()],\n )\n\n\nclass KubeflowDagRunnerTest(test_case_utils.TfxTest):\n\n def setUp(self):\n super().setUp()\n self._source_data_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), 'testdata')\n self.enter_context(test_case_utils.change_working_dir(self.tmp_dir))\n\n def _compare_tfx_ir_against_testdata(self, args: List[str], golden_file: str):\n index_of_tfx_ir_flag = args.index('--tfx_ir')\n self.assertAllGreater(len(args), index_of_tfx_ir_flag)\n real_tfx_ir = json.loads(args[index_of_tfx_ir_flag + 1])\n real_tfx_ir_str = json.dumps(real_tfx_ir, sort_keys=True)\n with open(os.path.join(self._source_data_dir,\n golden_file)) as tfx_ir_json_file:\n formatted_tfx_ir = json.dumps(json.load(tfx_ir_json_file), sort_keys=True)\n self.assertEqual(real_tfx_ir_str, formatted_tfx_ir)\n\n def testTwoStepPipeline(self):\n \"\"\"Sanity-checks the construction and dependencies for a 2-step pipeline.\"\"\"\n kubeflow_dag_runner.KubeflowDagRunner().run(_two_step_pipeline())\n file_path = os.path.join(self.tmp_dir, 'two_step_pipeline.tar.gz')\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n\n containers = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertEqual(2, len(containers))\n\n big_query_container = [\n c for c in containers if c['name'] == 'bigqueryexamplegen'\n ]\n self.assertEqual(1, len(big_query_container))\n self.assertEqual([\n 'python',\n '-m',\n 'tfx.orchestration.kubeflow.container_entrypoint',\n ], big_query_container[0]['container']['command'])\n self.assertIn('--tfx_ir', big_query_container[0]['container']['args'])\n self.assertIn('--node_id', big_query_container[0]['container']['args'])\n self._compare_tfx_ir_against_testdata(\n big_query_container[0]['container']['args'],\n 'two_step_pipeline_post_dehydrate_ir.json')\n\n statistics_gen_container = [\n c for c in containers if c['name'] == 'statisticsgen'\n ]\n self.assertEqual(1, len(statistics_gen_container))\n\n # Ensure the pod labels are correctly appended.\n metadata = [\n c['metadata'] for c in pipeline['spec']['templates'] if 'dag' not in c\n ]\n for m in metadata:\n self.assertEqual('tfx', m['labels'][telemetry_utils.LABEL_KFP_SDK_ENV])\n\n # Ensure dependencies between components are captured.\n dag = [c for c in pipeline['spec']['templates'] if 'dag' in c]\n self.assertEqual(1, len(dag))\n\n self.assertEqual(\n {\n 'tasks': [{\n 'name': 'bigqueryexamplegen',\n 'template': 'bigqueryexamplegen',\n 'arguments': {\n 'parameters': [{\n 'name': 'input_config',\n 'value': '{{inputs.parameters.input_config}}'\n }, {\n 'name': 'pipeline-root',\n 'value': '{{inputs.parameters.pipeline-root}}'\n }]\n }\n }, {\n 'name': 'statisticsgen',\n 'template': 'statisticsgen',\n 'arguments': {\n 'parameters': [{\n 'name': 'pipeline-root',\n 'value': '{{inputs.parameters.pipeline-root}}'\n }]\n },\n 'dependencies': ['bigqueryexamplegen'],\n }]\n }, dag[0]['dag'])\n\n def testDefaultPipelineOperatorFuncs(self):\n kubeflow_dag_runner.KubeflowDagRunner().run(_two_step_pipeline())\n file_path = 'two_step_pipeline.tar.gz'\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n\n containers = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertEqual(2, len(containers))\n\n def testMountGcpServiceAccount(self):\n kubeflow_dag_runner.KubeflowDagRunner(\n config=kubeflow_dag_runner.KubeflowDagRunnerConfig(\n pipeline_operator_funcs=kubeflow_dag_runner\n .get_default_pipeline_operator_funcs(use_gcp_sa=True))).run(\n _two_step_pipeline())\n file_path = 'two_step_pipeline.tar.gz'\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n\n containers = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertEqual(2, len(containers))\n\n # Check that each container has default GCP credentials.\n\n container_0 = containers[0]\n env = [\n env for env in container_0['container']['env']\n if env['name'] == 'GOOGLE_APPLICATION_CREDENTIALS'\n ]\n self.assertEqual(1, len(env))\n self.assertEqual('/secret/gcp-credentials/user-gcp-sa.json',\n env[0]['value'])\n\n container_1 = containers[0]\n env = [\n env for env in container_1['container']['env']\n if env['name'] == 'GOOGLE_APPLICATION_CREDENTIALS'\n ]\n self.assertEqual(1, len(env))\n self.assertEqual('/secret/gcp-credentials/user-gcp-sa.json',\n env[0]['value'])\n\n def testVolumeMountingPipelineOperatorFuncs(self):\n mount_volume_op = onprem.mount_pvc('my-persistent-volume-claim',\n 'my-volume-name',\n '/mnt/volume-mount-path')\n config = kubeflow_dag_runner.KubeflowDagRunnerConfig(\n pipeline_operator_funcs=[mount_volume_op])\n\n kubeflow_dag_runner.KubeflowDagRunner(config=config).run(\n _two_step_pipeline())\n file_path = 'two_step_pipeline.tar.gz'\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n\n container_templates = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertEqual(2, len(container_templates))\n\n volumes = [{\n 'name': 'my-volume-name',\n 'persistentVolumeClaim': {\n 'claimName': 'my-persistent-volume-claim'\n }\n }]\n\n # Check that the PVC is specified for kfp<=0.1.31.1.\n if 'volumes' in pipeline['spec']:\n self.assertEqual(volumes, pipeline['spec']['volumes'])\n\n for template in container_templates:\n # Check that each container has the volume mounted.\n self.assertEqual([{\n 'name': 'my-volume-name',\n 'mountPath': '/mnt/volume-mount-path'\n }], template['container']['volumeMounts'])\n\n # Check that each template has the PVC specified for kfp>=0.1.31.2.\n if 'volumes' in template:\n self.assertEqual(volumes, template['volumes'])\n\n def testContainerComponent(self):\n kubeflow_dag_runner.KubeflowDagRunner().run(_container_component_pipeline())\n file_path = os.path.join(self.tmp_dir,\n 'container_component_pipeline.tar.gz')\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n containers = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertLen(containers, 1)\n component_args = containers[0]['container']['args']\n self.assertIn('--node_id', component_args)\n\n def testExitHandler(self):\n dag_runner = kubeflow_dag_runner.KubeflowDagRunner()\n dag_runner.set_exit_handler(_say_hi(status=FinalStatusStr()))\n pipeline = _container_component_pipeline()\n pipeline.enable_cache = True\n dag_runner.run(pipeline)\n file_path = os.path.join(self.tmp_dir,\n 'container_component_pipeline.tar.gz')\n self.assertTrue(fileio.exists(file_path))\n\n with tarfile.TarFile.open(file_path).extractfile(\n 'pipeline.yaml') as pipeline_file:\n self.assertIsNotNone(pipeline_file)\n pipeline = yaml.safe_load(pipeline_file)\n self.assertIn('onExit', pipeline['spec'])\n containers = [\n c for c in pipeline['spec']['templates'] if 'container' in c\n ]\n self.assertLen(containers, 2)\n exit_component_args = ' '.join(containers[1]['container']['args'])\n self.assertIn('{{workflow.status}}', exit_component_args)\n self.assertNotIn('enableCache', exit_component_args)\n first_component_args = ' '.join(containers[0]['container']['args'])\n self.assertNotIn('{{workflow.status}}', first_component_args)\n self.assertIn('enableCache', first_component_args)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2022 Google LLC. 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 tfx.utils.name_utils.\"\"\"\n\nimport types\n\nimport tensorflow as tf\n\nfrom tfx.utils import name_utils\n\n\nclass Foo:\n class Bar:\n pass\n\n\ndef fun():\n pass\n\nVALUE = 42\n\n\nclass ClassUtilsTest(tf.test.TestCase):\n\n def testGetFullName_GoodExamples(self):\n self.assertEqual(name_utils.get_full_name(str), 'builtins.str')\n self.assertEqual(name_utils.get_full_name(Foo), f'{__name__}.Foo')\n self.assertEqual(name_utils.get_full_name(Foo.Bar), f'{__name__}.Foo.Bar')\n self.assertEqual(name_utils.get_full_name(fun), f'{__name__}.fun')\n\n def testGetFullName_BadExamples(self):\n with self.assertRaisesRegex(ValueError, 'does not have a name'):\n name_utils.get_full_name(VALUE)\n\n with self.assertRaisesRegex(ValueError, 'does not have a qualified name'):\n class DynamicClass:\n pass\n name_utils.get_full_name(DynamicClass)\n\n with self.assertRaisesRegex(ValueError, 'is not importable'):\n dynamic_class = types.new_class('DynamicClass')\n name_utils.get_full_name(dynamic_class)\n\n def testGetClass_GoodExamples(self):\n self.assertIs(name_utils.resolve_full_name('builtins.str'), str)\n self.assertIs(name_utils.resolve_full_name(f'{__name__}.Foo'), Foo)\n self.assertIs(name_utils.resolve_full_name(f'{__name__}.Foo.Bar'), Foo.Bar)\n self.assertIs(name_utils.resolve_full_name(f'{__name__}.fun'), fun)\n\n def testGetClass_BadExamples(self):\n with self.assertRaisesRegex(ValueError, 'not a valid name.'):\n name_utils.resolve_full_name(42)\n\n with self.assertRaisesRegex(ValueError, 'not a valid name.'):\n name_utils.resolve_full_name('foo^ax.1234')\n\n with self.assertRaisesRegex(ValueError, 'Cannot find'):\n name_utils.resolve_full_name('non_existing_module_name.meh.FakeClass')\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2019 Google LLC. 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 tfx.dsl.components.base.base_component.\"\"\"\n\nimport tensorflow as tf\n\nfrom tfx import types\nfrom tfx.dsl.components.base import base_component\nfrom tfx.dsl.components.base import base_executor\nfrom tfx.dsl.components.base import executor_spec\nfrom tfx.proto import example_gen_pb2\nfrom tfx.types import component_spec\nfrom tfx.types.system_executions import SystemExecution\nfrom tfx.utils import json_utils\n\n\nclass _InputArtifact(types.Artifact):\n TYPE_NAME = \"InputArtifact\"\n\n\nclass _OutputArtifact(types.Artifact):\n TYPE_NAME = \"OutputArtifact\"\n\n\nclass _BasicComponentSpec(types.ComponentSpec):\n\n PARAMETERS = {\n \"folds\":\n component_spec.ExecutionParameter(type=int),\n \"proto\":\n component_spec.ExecutionParameter(\n type=example_gen_pb2.Input, optional=True),\n }\n INPUTS = {\n \"input\": component_spec.ChannelParameter(type=_InputArtifact),\n }\n OUTPUTS = {\n \"output\": component_spec.ChannelParameter(type=_OutputArtifact),\n }\n\n\nclass _BasicComponent(base_component.BaseComponent):\n\n SPEC_CLASS = _BasicComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(base_executor.BaseExecutor)\n\n def __init__(self,\n spec: types.ComponentSpec = None,\n folds: int = None,\n input: types.Channel = None): # pylint: disable=redefined-builtin\n if not spec:\n output = types.Channel(type=_OutputArtifact)\n spec = _BasicComponentSpec(folds=folds, input=input, output=output)\n super().__init__(spec=spec)\n\n\nclass ComponentTest(tf.test.TestCase):\n\n def testComponentBasic(self):\n input_channel = types.Channel(type=_InputArtifact)\n component = _BasicComponent(folds=10, input=input_channel)\n self.assertEqual(component.id, \"_BasicComponent\")\n component.id = \"MyBasicComponent\"\n self.assertEqual(component.id, \"MyBasicComponent\")\n component = component.with_id(\"MyFavouriteId\")\n self.assertEqual(component.id, \"MyFavouriteId\")\n self.assertIs(input_channel, component.inputs[\"input\"])\n self.assertIsInstance(component.outputs[\"output\"], types.Channel)\n self.assertEqual(component.outputs[\"output\"].type, _OutputArtifact)\n self.assertEqual(component.outputs[\"output\"].type_name, \"OutputArtifact\")\n\n def testBaseNodeNewOverride(self):\n # Test behavior of `BaseNode.__new__` override.\n input_channel = types.Channel(type=_InputArtifact)\n component = _BasicComponent(folds=10, input=input_channel)\n self.assertIs(component._CONSTRUCT_CLS, _BasicComponent)\n self.assertEqual(component._CONSTRUCT_ARGS, ())\n self.assertEqual(component._CONSTRUCT_KWARGS,\n {\"folds\": 10, \"input\": input_channel})\n\n def testComponentSpecType(self):\n\n with self.assertRaisesRegex(\n ValueError,\n 'expects \"spec\" argument to be an instance of types.ComponentSpec'):\n _ = _BasicComponent(spec=object()) # pytype: disable=wrong-arg-types\n\n def testComponentSpecClass(self):\n\n class MissingSpecComponent(base_component.BaseComponent):\n\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n with self.assertRaisesRegex(TypeError, \"Can't instantiate abstract class\"):\n MissingSpecComponent(spec=object()) # pytype: disable=wrong-arg-types\n\n with self.assertRaisesRegex(\n TypeError, \"expects SPEC_CLASS property to be a subclass of \"\n \"types.ComponentSpec\"):\n MissingSpecComponent._validate_component_class()\n\n class InvalidSpecComponent(base_component.BaseComponent):\n\n SPEC_CLASSES = object()\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n with self.assertRaisesRegex(\n TypeError, \"expects SPEC_CLASS property to be a subclass of \"\n \"types.ComponentSpec\"):\n InvalidSpecComponent._validate_component_class()\n\n def testComponentSpecTypeAnnotation(self):\n\n class MissingAnnotationComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n\n class MissingAnnotationComponent(base_component.BaseComponent):\n\n SPEC_CLASS = MissingAnnotationComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n missing_annotation_component = MissingAnnotationComponent(\n spec=MissingAnnotationComponentSpec())\n self.assertIsNone(missing_annotation_component.type_annotation)\n\n class InvalidAnnotationComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n TYPE_ANNOTATION = types.ComponentSpec\n\n class InvalidAnnotationComponent(base_component.BaseComponent):\n\n SPEC_CLASS = InvalidAnnotationComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n with self.assertRaisesRegex(TypeError, \"not a subclass of SystemExecution\"):\n _ = InvalidAnnotationComponent(\n spec=InvalidAnnotationComponentSpec()).type_annotation\n\n class MyTrain(SystemExecution):\n MLMD_SYSTEM_BASE_TYPE = \"Train\"\n\n class MyTrainerComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n TYPE_ANNOTATION = MyTrain\n\n class MyTrainerComponent(base_component.BaseComponent):\n\n SPEC_CLASS = MyTrainerComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n self.assertEqual(\n MyTrainerComponent(spec=MyTrainerComponentSpec()).type_annotation\n .MLMD_SYSTEM_BASE_TYPE, \"Train\")\n\n def testComponentExecutorClass(self):\n\n class MissingExecutorComponent(base_component.BaseComponent):\n\n SPEC_CLASS = _BasicComponentSpec\n\n with self.assertRaisesRegex(TypeError, \"Can't instantiate abstract class\"):\n MissingExecutorComponent(spec=object()) # pytype: disable=wrong-arg-types\n\n with self.assertRaisesRegex(\n TypeError, \"expects EXECUTOR_SPEC property to be an instance of \"\n \"ExecutorSpec\"):\n MissingExecutorComponent._validate_component_class()\n\n class InvalidExecutorComponent(base_component.BaseComponent):\n\n SPEC_CLASS = _BasicComponentSpec\n EXECUTOR_SPEC = object()\n\n with self.assertRaisesRegex(\n TypeError, \"expects EXECUTOR_SPEC property to be an instance of \"\n \"ExecutorSpec\"):\n InvalidExecutorComponent._validate_component_class()\n\n def testComponentCustomExecutor(self):\n\n class EmptyComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n\n class MyComponent(base_component.BaseComponent):\n\n SPEC_CLASS = EmptyComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n\n class MyCustomExecutor(base_executor.BaseExecutor):\n pass\n\n custom_executor_component = MyComponent(\n spec=EmptyComponentSpec(),\n custom_executor_spec=executor_spec.ExecutorClassSpec(MyCustomExecutor))\n self.assertEqual(custom_executor_component.executor_spec.executor_class,\n MyCustomExecutor)\n\n with self.assertRaisesRegex(TypeError,\n \"should be an instance of ExecutorSpec\"):\n MyComponent(spec=EmptyComponentSpec(), custom_executor_spec=object)\n\n def testComponentDriverClass(self):\n\n class InvalidDriverComponent(base_component.BaseComponent):\n\n SPEC_CLASS = _BasicComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(\n base_executor.BaseExecutor)\n DRIVER_CLASS = object()\n\n with self.assertRaisesRegex(\n TypeError, \"expects DRIVER_CLASS property to be a subclass of \"\n \"base_driver.BaseDriver\"):\n InvalidDriverComponent._validate_component_class()\n\n def testJsonify(self):\n input_channel = types.Channel(type=_InputArtifact)\n component = _BasicComponent(folds=10, input=input_channel)\n json_dict = json_utils.dumps(component)\n recovered_component = json_utils.loads(json_dict)\n self.assertEqual(recovered_component.__class__, component.__class__)\n self.assertEqual(recovered_component.component_id, \"_BasicComponent\")\n self.assertEqual(input_channel.type,\n recovered_component.inputs[\"input\"].type)\n self.assertIsInstance(recovered_component.outputs[\"output\"], types.Channel)\n self.assertEqual(recovered_component.outputs[\"output\"].type,\n _OutputArtifact)\n self.assertEqual(recovered_component.outputs[\"output\"].type_name,\n \"OutputArtifact\")\n self.assertEqual(recovered_component.driver_class, component.driver_class)\n\n def testTaskDependency(self):\n channel_1 = types.Channel(type=_InputArtifact)\n component_1 = _BasicComponent(folds=10, input=channel_1)\n channel_2 = types.Channel(type=_InputArtifact)\n component_2 = _BasicComponent(folds=10, input=channel_2)\n self.assertEqual(False, component_2 in component_1.downstream_nodes)\n self.assertEqual(False, component_1 in component_2.upstream_nodes)\n component_1.add_downstream_node(component_2)\n self.assertEqual(True, component_2 in component_1.downstream_nodes)\n self.assertEqual(True, component_1 in component_2.upstream_nodes)\n\n def testComponentInit_OutputChannelType(self):\n component = _BasicComponent(\n spec=_BasicComponentSpec(\n input=types.Channel(type=_InputArtifact),\n folds=10,\n output=types.Channel(type=_OutputArtifact))).with_id(\"foo\")\n\n self.assertIsInstance(component.spec.outputs[\"output\"], types.OutputChannel)\n self.assertIsInstance(component.outputs[\"output\"], types.OutputChannel)\n output_channel = component.outputs[\"output\"]\n self.assertEqual(output_channel.producer_component_id, \"foo\")\n self.assertEqual(output_channel.output_key, \"output\")\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2019 Google LLC. 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 tfx.orchestration.experimental.interactive.interactive_context.\"\"\"\n\nimport builtins\nimport os\nimport shutil\nimport tempfile\nimport textwrap\nfrom typing import Any, Dict, List\nfrom unittest import mock\n\nimport jinja2\nimport nbformat\nimport tensorflow as tf\nfrom tfx import types\nfrom tfx.dsl.components.base import base_component\nfrom tfx.dsl.components.base import base_executor\nfrom tfx.dsl.components.base import executor_spec\nfrom tfx.orchestration.experimental.interactive import interactive_context\nfrom tfx.orchestration.experimental.interactive import standard_visualizations\nfrom tfx.orchestration.launcher.in_process_component_launcher import InProcessComponentLauncher\nfrom tfx.types import component_spec\nfrom tfx.types import standard_artifacts\nfrom tfx.utils import telemetry_utils\n\n\nclass InteractiveContextTest(tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n\n builtins.__dict__['__IPYTHON__'] = True\n self._tmpdir = None\n\n def tearDown(self):\n if self._tmpdir:\n shutil.rmtree(self._tmpdir, ignore_errors=True)\n super().tearDown()\n\n def _setupTestNotebook(self, notebook_name='test_notebook.ipynb'):\n notebook = nbformat.v4.new_notebook(\n cells=[\n nbformat.v4.new_markdown_cell(source='A markdown cell.'),\n nbformat.v4.new_code_cell(source='foo = 1'),\n nbformat.v4.new_markdown_cell(source='Another markdown cell.'),\n nbformat.v4.new_code_cell(source=textwrap.dedent('''\\\n %%skip_for_export\n !pip install something\n !ls\n x = 1\n y = 2\n print('this cell should not be exported')''')),\n nbformat.v4.new_code_cell(source=textwrap.dedent('''\\\n def bar():\n %some_line_magic print('this line should not be exported')\n a = \"hello\"\n b = \"world\"\n return a + b''')),\n nbformat.v4.new_code_cell(source=textwrap.dedent('''\\\n def baz():\n c = \"nyan\"\n d = \"cat\"\n return c + d''')),\n ]\n )\n self._tmpdir = tempfile.mkdtemp()\n self._exportdir = tempfile.mkdtemp()\n self._notebook_fp = os.path.join(self._tmpdir, notebook_name)\n nbformat.write(notebook, self._notebook_fp)\n\n def testBasicRun(self):\n\n class _FakeComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n\n class _FakeExecutor(base_executor.BaseExecutor):\n CALLED = False\n\n def Do(self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> None:\n _FakeExecutor.CALLED = True\n\n class _FakeComponent(base_component.BaseComponent):\n SPEC_CLASS = _FakeComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(_FakeExecutor)\n\n def __init__(self, spec: types.ComponentSpec):\n super().__init__(spec=spec)\n\n c = interactive_context.InteractiveContext()\n component = _FakeComponent(_FakeComponentSpec())\n c.run(component)\n self.assertTrue(_FakeExecutor.CALLED)\n\n def testRunMethodRequiresIPython(self):\n del builtins.__dict__['__IPYTHON__']\n\n c = interactive_context.InteractiveContext()\n self.assertIsNone(c.run(None))\n\n def testUnresolvedChannel(self):\n\n class _FakeComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {\n 'input':\n component_spec.ChannelParameter(type=standard_artifacts.Examples)\n }\n OUTPUTS = {}\n\n class _FakeExecutor(base_executor.BaseExecutor):\n CALLED = False\n\n def Do(self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> None:\n _FakeExecutor.CALLED = True\n\n class _FakeComponent(base_component.BaseComponent):\n SPEC_CLASS = _FakeComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(_FakeExecutor)\n\n def __init__(self, spec: types.ComponentSpec):\n super().__init__(spec=spec)\n\n c = interactive_context.InteractiveContext()\n foo = types.Channel(type=standard_artifacts.Examples).set_artifacts(\n [standard_artifacts.Examples()])\n component = _FakeComponent(_FakeComponentSpec(input=foo))\n with self.assertRaisesRegex(ValueError, 'Unresolved input channel'):\n c.run(component)\n\n @mock.patch.object(jinja2.Environment, 'get_template',\n return_value=jinja2.Template('{{ notebook_content }}'))\n def testExportToPipeline(self, mock_get_template):\n self._setupTestNotebook()\n\n c = interactive_context.InteractiveContext()\n export_filepath = os.path.join(self._exportdir, 'exported_pipeline.py')\n c.export_to_pipeline(notebook_filepath=self._notebook_fp,\n export_filepath=export_filepath,\n runner_type='beam')\n\n with open(export_filepath, 'r') as exported_pipeline:\n code = exported_pipeline.read()\n self.assertEqual(code, textwrap.dedent('''\\\n foo = 1\n\n def bar():\n a = \"hello\"\n b = \"world\"\n return a + b\n\n def baz():\n c = \"nyan\"\n d = \"cat\"\n return c + d'''))\n\n def testExportToPipelineRaisesErrorInvalidRunnerType(self):\n self._setupTestNotebook()\n\n c = interactive_context.InteractiveContext()\n export_filepath = os.path.join(self._exportdir, 'exported_pipeline.py')\n with self.assertRaisesRegex(ValueError, 'runner_type'):\n c.export_to_pipeline(notebook_filepath=self._notebook_fp,\n export_filepath=export_filepath,\n runner_type='foobar')\n\n @mock.patch('tfx.orchestration.experimental.interactive.'\n 'standard_visualizations.ExampleAnomaliesVisualization.display')\n def testShow(self, *unused_mocks):\n context = interactive_context.InteractiveContext()\n mock_object = mock.MagicMock()\n standard_visualizations.ExampleAnomaliesVisualization.display = mock_object\n mock_object.assert_not_called()\n artifact = standard_artifacts.ExampleAnomalies()\n context.show(\n types.Channel(type=standard_artifacts.ExampleAnomalies).set_artifacts(\n [artifact]))\n mock_object.assert_called_with(artifact)\n\n @mock.patch('tfx.orchestration.launcher.in_process_component_launcher.'\n 'InProcessComponentLauncher.create')\n def testTelemetry(self, mock_launcher_create):\n\n class _FakeLauncher:\n\n def __init__(self):\n self.recorded_labels = []\n\n def launch(self):\n self.recorded_labels = telemetry_utils.make_beam_labels_args()\n return mock.MagicMock()\n\n class _FakeComponentSpec(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {}\n\n class _FakeExecutor(base_executor.BaseExecutor):\n\n def Do(self, input_dict: Dict[str, List[types.Artifact]],\n output_dict: Dict[str, List[types.Artifact]],\n exec_properties: Dict[str, Any]) -> None:\n pass\n\n class _FakeComponent(base_component.BaseComponent):\n SPEC_CLASS = _FakeComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(_FakeExecutor)\n\n def __init__(self):\n super().__init__(spec=_FakeComponentSpec())\n\n # Set up fake on launcher.\n fake_launcher = _FakeLauncher()\n mock_launcher_create.side_effect = [fake_launcher]\n InProcessComponentLauncher.create = mock_launcher_create\n\n context = interactive_context.InteractiveContext()\n context.run(_FakeComponent())\n self.assertIn('--labels tfx_runner=interactivecontext',\n ' '.join(fake_launcher.recorded_labels))\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ] ]
[ { "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": [] } ]
DamienIrving/ocean-analysis
[ "23a6dbf616fb84e6e158e32534ffd394e0df2e3e", "23a6dbf616fb84e6e158e32534ffd394e0df2e3e", "23a6dbf616fb84e6e158e32534ffd394e0df2e3e", "23a6dbf616fb84e6e158e32534ffd394e0df2e3e" ]
[ "visualisation/drift_paper/plot_ohc_drift.py", "data_processing/correct_mask.py", "data_processing/calc_interhemispheric_metric.py", "data_processing/water_mass_binning.py" ]
[ "\"\"\"\nFilename: plot_ohc_drift.py\nAuthor: Damien Irving, [email protected]\nDescription: Create a bar chart showing drift in ocean heat content\n and its thermal and barystatic components \n\n\"\"\"\n\n# Import general Python modules\n\nimport sys\nimport os\nimport re\nimport pdb\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport cmdline_provenance as cmdprov\n\ncwd = os.getcwd()\nrepo_dir = '/'\nfor directory in cwd.split('/')[1:]:\n repo_dir = os.path.join(repo_dir, directory)\n if directory == 'ocean-analysis':\n break\n\nimport matplotlib as mpl\nmpl.rcParams['axes.labelsize'] = 'large'\nmpl.rcParams['axes.titlesize'] = 'x-large'\nmpl.rcParams['xtick.labelsize'] = 'medium'\nmpl.rcParams['ytick.labelsize'] = 'large'\nmpl.rcParams['legend.fontsize'] = 'large'\n\n\n# Define functions \n\ndef get_quartiles(df, column_name, df_project, units):\n \"\"\"Get the ensemble quartiles\"\"\"\n\n assert len(df) == len(df_project)\n\n quartiles = ['# ' + column_name + ' quartiles']\n for project in ['cmip6', 'cmip5']:\n df_subset = df[df_project == project]\n \n upper_quartile = df_subset[column_name].abs().quantile(0.75)\n median = df_subset[column_name].abs().quantile(0.5)\n lower_quartile = df_subset[column_name].abs().quantile(0.25)\n \n upper_quartile_text = \"%s upper quartile: %f %s\" %(project, upper_quartile, units)\n median_text = \"%s median: %f %s\" %(project, median, units)\n lower_quartile_text = \"%s lower quartile: %f %s\" %(project, lower_quartile, units)\n \n quartiles.append(upper_quartile_text)\n quartiles.append(median_text)\n quartiles.append(lower_quartile_text)\n\n return quartiles\n\n\ndef main(inargs):\n \"\"\"Run the program.\"\"\"\n\n df = pd.read_csv(inargs.infile)\n df.set_index(df['model'], drop=True, inplace=True)\n #df.set_index(df['model'] + ' (' + df['run'] + ')', drop=True, inplace=True)\n x = np.arange(df.shape[0])\n ncmip5 = df['project'].value_counts()['cmip5']\n\n df_ohc = df[['OHC (J yr-1)', 'thermal OHC (J yr-1)', 'barystatic OHC (J yr-1)']]\n\n sec_in_year = 365.25 * 24 * 60 * 60\n earth_surface_area = 5.1e14\n df_ohc = (df_ohc / sec_in_year) / earth_surface_area\n df_ohc = df_ohc.rename(columns={\"OHC (J yr-1)\": \"change in OHC ($dH/dt$)\",\n \"thermal OHC (J yr-1)\": \"change in OHC temperature component ($dH_T/dt$)\",\n \"barystatic OHC (J yr-1)\": \"change in OHC barystatic component ($dH_m/dt$)\"})\n\n df_ohc.plot.bar(figsize=(18,6), color=['#272727', 'tab:red', 'tab:blue'], width=0.9, zorder=2)\n plt.axhspan(0.4, 1.0, color='0.95', zorder=1)\n plt.axvline(x=ncmip5 - 0.5, color='0.5', linewidth=2.0)\n units = 'equivalent planetary energy imbalance (W m$^{-2}$)'\n plt.ylabel(units)\n plt.axvline(x=x[0]-0.5, color='0.5', linewidth=0.1)\n for val in x:\n plt.axvline(x=val+0.5, color='0.5', linewidth=0.1)\n \n quartiles = get_quartiles(df_ohc, \"change in OHC ($dH/dt$)\", df['project'], units)\n\n plt.savefig(inargs.outfile, bbox_inches='tight', dpi=400)\n log_file = re.sub('.png', '.met', inargs.outfile)\n log_text = cmdprov.new_log(git_repo=repo_dir, extra_notes=quartiles)\n cmdprov.write_log(log_file, log_text)\n\n\nif __name__ == '__main__':\n\n extra_info =\"\"\" \nauthor:\n Damien Irving, [email protected]\n\n\"\"\"\n\n description = 'Create a bar chart showing drift in ocean heat content'\n parser = argparse.ArgumentParser(description=description,\n epilog=extra_info, \n argument_default=argparse.SUPPRESS,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument(\"infile\", type=str, help=\"Input file name\")\n parser.add_argument(\"outfile\", type=str, help=\"Output file name\")\n\n args = parser.parse_args() \n main(args)\n", "\"\"\"\nFilename: correct_mask.py\nAuthor: Damien Irving, [email protected]\nDescription: Correct a bogus mask (e.g. some models put 1.0 or Nan as the mask value) \n\n\"\"\"\n\n# Import general Python modules\n\nimport sys, os, pdb\nimport argparse\nimport numpy\nimport iris\nimport cmdline_provenance as cmdprov\n\n# Import my modules\n\ncwd = os.getcwd()\nrepo_dir = '/'\nfor directory in cwd.split('/')[1:]:\n repo_dir = os.path.join(repo_dir, directory)\n if directory == 'ocean-analysis':\n break\n\nmodules_dir = os.path.join(repo_dir, 'modules')\nsys.path.append(modules_dir)\n\ntry:\n import general_io as gio\nexcept ImportError:\n raise ImportError('Must run this script from anywhere within the ocean-analysis git repo')\n\n\n# Define functions\n\ndef main(inargs):\n \"\"\"Run the program.\"\"\"\n\n cube = iris.load_cube(inargs.infile, inargs.var)\n\n cube.data = numpy.ma.masked_invalid(cube.data)\n if inargs.fill_value:\n cube.data = numpy.ma.masked_where(cube.data >= cube.data.fill_value, cube.data)\n if inargs.mask_value:\n cube.data = numpy.ma.masked_where(cube.data == inargs.mask_value, cube.data)\n\n cube.attributes['history'] = cmdprov.new_log(git_repo=repo_dir, infile_history={inargs.infile: cube.attributes['history']})\n iris.save(cube, inargs.outfile)\n\n\nif __name__ == '__main__':\n\n extra_info =\"\"\" \nauthor:\n Damien Irving, [email protected]\n \n\"\"\"\n\n description='Correct a bogus mask (e.g. some models put 1.0 or Nan as the mask value)'\n parser = argparse.ArgumentParser(description=description,\n epilog=extra_info, \n argument_default=argparse.SUPPRESS,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument(\"infile\", type=str, help=\"Input files\")\n parser.add_argument(\"var\", type=str, help=\"Variable standard_name\")\n parser.add_argument(\"outfile\", type=str, help=\"Output file name\")\n\n parser.add_argument(\"--fill_value\", action=\"store_true\", default=False,\n help=\"Mask points greater or equal to the fill value\")\n\n parser.add_argument(\"--mask_value\", type=float, default=None,\n help=\"Value to mask\")\n\n args = parser.parse_args() \n main(args)\n", "\"\"\"\nFilename: calc_interhemispheric_metric.py\nAuthor: Damien Irving, [email protected]\nDescription: Calculate the interhemispheric timeseries for a general input variable\n\n\"\"\"\n\n# Import general Python modules\n\nimport sys, os, pdb\nimport argparse\nimport numpy\nimport iris\nfrom iris.experimental.equalise_cubes import equalise_attributes\nimport dask\ndask.set_options(get=dask.get) \nimport cmdline_provenance as cmdprov\n\n# Import my modules\n\ncwd = os.getcwd()\nrepo_dir = '/'\nfor directory in cwd.split('/')[1:]:\n repo_dir = os.path.join(repo_dir, directory)\n if directory == 'ocean-analysis':\n break\n\nmodules_dir = os.path.join(repo_dir, 'modules')\nsys.path.append(modules_dir)\ntry:\n import general_io as gio\n import convenient_universal as uconv\n import spatial_weights\n import timeseries\n import grids\nexcept ImportError:\n raise ImportError('Must run this script from anywhere within the ocean-analysis git repo')\n\n\n# Define functions\n\ndef read_data(infile, variable, calc_annual=False, chunk=False):\n \"\"\"Load the input data.\"\"\"\n\n cube = iris.load_cube(infile, gio.check_iris_var(variable))\n cube = gio.check_time_units(cube)\n\n if calc_annual:\n cube = timeseries.convert_to_annual(cube, chunk=chunk)\n\n coord_names = [coord.name() for coord in cube.dim_coords]\n aux_coord_names = [coord.name() for coord in cube.aux_coords]\n assert 'time' in coord_names\n grid_type = 'curvilinear' if aux_coord_names == ['latitude', 'longitude'] else 'latlon'\n\n return cube, coord_names, aux_coord_names, grid_type\n\n\ndef calc_spatial_agg(cube, coord_names, aux_coord_names, grid_type,\n aggregation_method, weights_cube,\n lat_bounds=None, chunk=False):\n \"\"\"Load the infiles and calculate the spatial aggregate (sum or mean).\"\"\"\n\n cube = cube.copy() \n coord_names = coord_names.copy()\n\n # Extract region\n if lat_bounds:\n if grid_type == 'curvilinear':\n cube = grids.extract_latregion_curvilinear(cube, lat_bounds)\n else:\n cube = grids.extract_latregion_rectilinear(cube, lat_bounds)\n\n # Get weights \n if type(weights_cube) == iris.cube.Cube:\n if grid_type == 'latlon' and lat_bounds:\n weights_cube = grids.extract_latregion_rectilinear(weights_cube, lat_bounds)\n weights_array = uconv.broadcast_array(weights_cube.data, [1, weights_cube.ndim], cube.shape)\n elif type(weights_cube) == str:\n weights_array = spatial_weights.area_array(cube)\n else:\n weights_array = None\n\n # Calculate spatial aggregate\n coord_names.remove('time')\n if (aggregation_method == iris.analysis.SUM) and weights_cube:\n units = str(cube.units)\n cube.units = units.replace('m-2', '')\n cube.data = cube.data * weights_array\n weights = None\n else:\n weights = weights_array\n \n if chunk:\n spatial_agg = uconv.chunked_collapse_by_time(cube, coord_names, aggregation_method, weights=weights)\n else: \n spatial_agg = cube.collapsed(coord_names, aggregation_method, weights=weights)\n\n spatial_agg.remove_coord('latitude')\n spatial_agg.remove_coord('longitude')\n try:\n spatial_agg.remove_coord('depth')\n except iris.exceptions.CoordinateNotFoundError:\n pass\n if grid_type == 'curvilinear':\n spatial_agg.remove_coord(coord_names[-2])\n spatial_agg.remove_coord(coord_names[-1])\n\n return spatial_agg\n\n\ndef rename_cube(cube, quantity):\n \"\"\"Rename a cube according to the specifics of the analysis\"\"\"\n\n assert quantity in ['globe sum', 'nh sum', 'sh sum', 'minus sh sum', 'div globe sum',\n 'globe mean', 'nh mean', 'sh mean', 'minus sh mean', 'div globe mean',]\n \n if cube.standard_name:\n standard_name = '_'.join([cube.standard_name, quantity.replace(' ', '_')])\n else:\n standard_name = '_'.join([cube.long_name.replace(' ', '_'), quantity.replace(' ', '_')])\n long_name = ' '.join([cube.long_name, quantity]) \n var_name = '_'.join([cube.var_name, quantity.replace(' ', '_')])\n\n iris.std_names.STD_NAMES[standard_name] = {'canonical_units': cube.units}\n cube.standard_name = standard_name\n cube.long_name = long_name\n cube.var_name = var_name\n \n return cube\n\n\ndef calc_diff(nh_cube, sh_cube, agg_method):\n \"\"\"Calculate the difference metric\"\"\"\n \n metric = nh_cube.copy()\n metric.data = nh_cube.data - sh_cube.data\n metric = rename_cube(metric, 'minus sh ' + agg_method) \n \n return metric\n\n\ndef calc_frac(h_cube, globe_cube, agg_method):\n \"\"\"Calculate the global fraction metric\"\"\"\n\n metric = h_cube.copy()\n metric.data = (h_cube.data / globe_cube.data) * 100\n metric = rename_cube(metric, 'div globe ' + agg_method) \n\n metric.units = '%'\n\n return metric\n\n\ndef update_metadata(cube_list, new_log):\n \"\"\"Create the cube list for output.\"\"\"\n\n for cube in cube_list:\n cube.data = numpy.array(cube.data) #removes _FillValue attribute\n cube.attributes['history'] = new_log\n\n return cube_list\n\n\ndef cumsum(cube):\n \"\"\"Calculate the cumulative sum.\"\"\"\n \n cube.data = numpy.cumsum(cube.data)\n \n return cube\n\n\ndef combine_cubes(cube_list):\n \"\"\"Combine two like cubes\"\"\"\n\n equalise_attributes(cube_list)\n iris.util.unify_time_units(cube_list)\n cube = cube_list.concatenate_cube()\n cube = gio.check_time_units(cube)\n\n return cube\n\n\ndef main(inargs):\n \"\"\"Run the program.\"\"\"\n\n if inargs.weights_file:\n if inargs.weights_file[-3:] == '.nc':\n weights_cube = iris.load_cube(inargs.weights_file)\n else:\n weights_cube = 'calculate'\n else:\n weights_cube = None\n\n agg_methods = {'sum': iris.analysis.SUM, 'mean': iris.analysis.MEAN}\n for file_number, infile in enumerate(inargs.infiles):\n print(infile)\n cube, coord_names, aux_coord_names, grid_type = read_data(infile, inargs.variable, calc_annual=inargs.annual,\n chunk=inargs.chunk)\n\n nh_agg = calc_spatial_agg(cube, coord_names, aux_coord_names, grid_type,\n agg_methods[inargs.aggregation_method], weights_cube,\n lat_bounds=inargs.nh_lat_bounds, chunk=inargs.chunk)\n sh_agg = calc_spatial_agg(cube, coord_names, aux_coord_names, grid_type,\n agg_methods[inargs.aggregation_method], weights_cube,\n lat_bounds=inargs.sh_lat_bounds, chunk=inargs.chunk)\n globe_agg = calc_spatial_agg(cube, coord_names, aux_coord_names, grid_type,\n agg_methods[inargs.aggregation_method], weights_cube,\n chunk=inargs.chunk) \n\n nh_agg = rename_cube(nh_agg, 'nh ' + inargs.aggregation_method) \n sh_agg = rename_cube(sh_agg, 'sh ' + inargs.aggregation_method)\n globe_agg = rename_cube(globe_agg, 'globe ' + inargs.aggregation_method) \n\n cube_list = iris.cube.CubeList([nh_agg, sh_agg, globe_agg])\n\n if inargs.flux_to_mag:\n cube_list = iris.cube.CubeList(map(uconv.flux_to_magnitude, cube_list)) \n\n if file_number == 0:\n final_cube_list = cube_list\n else:\n for var_num in range(len(cube_list)):\n cube_pair = iris.cube.CubeList([final_cube_list[var_num], cube_list[var_num]])\n final_cube_list[var_num] = combine_cubes(cube_pair)\n\n if inargs.cumsum:\n final_cube_list = iris.cube.CubeList(map(cumsum, final_cube_list))\n\n new_log = cmdprov.new_log(infile_history={infile: cube.attributes['history']}, git_repo=repo_dir)\n final_cube_list = update_metadata(final_cube_list, new_log)\n iris.save(final_cube_list, inargs.outfile)\n\n\nif __name__ == '__main__':\n\n extra_info =\"\"\" \n\nauthor:\n Damien Irving, [email protected]\n\n\"\"\"\n\n description = 'Calculate the interhemispheric timeseries for a general input variable'\n parser = argparse.ArgumentParser(description=description,\n epilog=extra_info, \n argument_default=argparse.SUPPRESS,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n \n parser.add_argument(\"infiles\", type=str, nargs='*', help=\"Input files\") \n parser.add_argument(\"variable\", type=str, help=\"Input variable\") \n parser.add_argument(\"outfile\", type=str, help=\"Output file\") \n\n parser.add_argument(\"--weights_file\", type=str, default=None, \n help=\"\"\"Input weights file (write 'calculate' to determine from grid info) [default = no weighting]\"\"\")\n\n parser.add_argument(\"--aggregation_method\", type=str, default='sum', choices=('mean', 'sum'),\n help=\"calculate the hemispheric sum or mean\")\n \n parser.add_argument(\"--annual\", action=\"store_true\", default=False,\n help=\"Output annual mean [default=False]\")\n\n parser.add_argument(\"--nh_lat_bounds\", type=float, nargs=2, metavar=('LOWER', 'UPPER'), default=(0.0, 91.0),\n help=\"Northern Hemisphere latitude bounds [default = entire hemisphere]\")\n parser.add_argument(\"--sh_lat_bounds\", type=float, nargs=2, metavar=('LOWER', 'UPPER'), default=(-91.0, 0.0),\n help=\"Southern Hemisphere latitude bounds [default = entire hemisphere]\")\n\n parser.add_argument(\"--flux_to_mag\", action=\"store_true\", default=False,\n help=\"Convert units from a flux to a magnitude [default: False]\")\n\n parser.add_argument(\"--cumsum\", action=\"store_true\", default=False,\n help=\"Output the cumulative sum [default: False]\")\n\n parser.add_argument(\"--chunk\", action=\"store_true\", default=False,\n help=\"Split input files on time axis to avoid memory errors [default: False]\")\n\n args = parser.parse_args() \n main(args)\n", "\"\"\"Bin data for ocean water mass analysis.\"\"\"\n\nimport sys\nscript_dir = sys.path[0]\nimport os\nimport pdb\nimport argparse\nimport logging\n\nimport numpy as np\nimport iris\nimport iris.coord_categorisation\nimport iris.util\nimport cmdline_provenance as cmdprov\nfrom statsmodels.stats.weightstats import DescrStatsW\n\nrepo_dir = '/'.join(script_dir.split('/')[:-1])\nmodule_dir = repo_dir + '/modules'\nsys.path.append(module_dir)\ntry:\n import water_mass\n import general_io as gio\n import convenient_universal as uconv\n import spatial_weights\nexcept ImportError:\n raise ImportError('Script and modules in wrong directories')\n\n\nmom_vars = {\"temp_nonlocal_KPP\": \"cp*rho*dzt*nonlocal tendency from KPP\",\n \"temp_vdiffuse_diff_cbt\": \"vert diffusion of heat due to diff_cbt\",\n \"mixdownslope_temp\": \"cp*mixdownslope*rho*dzt*temp\",\n \"temp_sigma_diff\" : \"thk wghtd sigma-diffusion heating\",\n \"temp_vdiffuse_k33\": \"vert diffusion of heat due to K33 from neutral diffusion\",\n \"neutral_diffusion_temp\": \"rho*dzt*cp*explicit neutral diffusion tendency (heating)\",\n \"temp_tendency\": \"time tendency for tracer Conservative temperature\"}\n\n\ndef construct_cube(outdata_dict, w_cube, t_cube, s_cube, b_cube,\n t_values, t_edges, t_units, s_values, s_edges, s_units,\n log, years=None, mul_ts=False):\n \"\"\"Create the iris cube for output\"\"\"\n \n if years is None:\n time_coord = t_cube.coord('time')\n else:\n assert type(years) == np.ndarray\n time_coord = iris.coords.DimCoord(years,\n standard_name=t_cube.coord('year').standard_name,\n long_name=t_cube.coord('year').long_name,\n var_name=t_cube.coord('year').var_name,\n units=t_cube.coord('year').units)\n\n t_bounds = uconv.get_bounds_list(t_edges)\n t_coord_std_name = t_cube.standard_name\n t_coord_long_name = t_cube.long_name\n t_coord_var_name = t_cube.var_name\n t_coord_units = t_units\n t_coord = iris.coords.DimCoord(t_values,\n standard_name=t_coord_std_name,\n long_name=t_coord_long_name,\n var_name=t_coord_var_name,\n units=t_coord_units,\n bounds=t_bounds)\n\n s_bounds = uconv.get_bounds_list(s_edges)\n s_coord_std_name = s_cube.standard_name\n s_coord_long_name = s_cube.long_name\n s_coord_var_name = s_cube.var_name\n s_coord_units = s_units\n s_coord = iris.coords.DimCoord(s_values,\n standard_name=s_coord_std_name,\n long_name=s_coord_long_name,\n var_name=s_coord_var_name,\n units=s_coord_units,\n bounds=s_bounds)\n \n tbin_dim_coords_list = [(time_coord, 0), (t_coord, 1)]\n sbin_dim_coords_list = [(time_coord, 0), (s_coord, 1)]\n tsbin_dim_coords_list = [(time_coord, 0), (s_coord, 1), (t_coord, 2)]\n\n outcube_list = iris.cube.CubeList([])\n wvar_list = ['w', 'wt', 'ws'] if mul_ts else ['w']\n for wvar in wvar_list:\n std_base_name = w_cube.standard_name\n long_base_name = w_cube.long_name\n var_base_name = w_cube.var_name\n if wvar == 'wt':\n if std_base_name:\n std_base_name = t_cube.standard_name + '_times_' + std_base_name\n long_base_name = t_cube.long_name.strip() + ' times ' + long_base_name\n var_base_name = t_cube.var_name + '_' + var_base_name\n if wvar == 'ws':\n if std_base_name:\n std_base_name = s_cube.standard_name + '_times_' + std_base_name \n long_base_name = s_cube.long_name.strip() + ' times ' + long_base_name\n var_base_name = s_cube.var_name + '_' + var_base_name\n\n if std_base_name:\n tbin_std_name = std_base_name + '_binned_by_temperature'\n iris.std_names.STD_NAMES[tbin_std_name] = {'canonical_units': str(w_cube.units)}\n else:\n tbin_std_name = None\n tbin_cube = iris.cube.Cube(outdata_dict[wvar + '_tbin'],\n standard_name=tbin_std_name,\n long_name=long_base_name + ' binned by temperature',\n var_name=var_base_name + '_tbin',\n units=w_cube.units,\n attributes=t_cube.attributes,\n dim_coords_and_dims=tbin_dim_coords_list)\n tbin_cube.attributes['history'] = log\n outcube_list.append(tbin_cube)\n\n if std_base_name:\n sbin_std_name = std_base_name + '_binned_by_salinity'\n iris.std_names.STD_NAMES[sbin_std_name] = {'canonical_units': str(w_cube.units)}\n else:\n sbin_std_name = None\n sbin_cube = iris.cube.Cube(outdata_dict[wvar + '_sbin'],\n standard_name=sbin_std_name,\n long_name=long_base_name + ' binned by salinity',\n var_name=var_base_name + '_sbin',\n units=w_cube.units,\n attributes=t_cube.attributes,\n dim_coords_and_dims=sbin_dim_coords_list)\n sbin_cube.attributes['history'] = log\n outcube_list.append(sbin_cube)\n\n if std_base_name:\n tsbin_std_name = std_base_name + '_binned_by_temperature_and_salinity'\n iris.std_names.STD_NAMES[tsbin_std_name] = {'canonical_units': str(w_cube.units)}\n else:\n tsbin_std_name = None\n tsbin_cube = iris.cube.Cube(outdata_dict[wvar + '_tsbin'],\n standard_name=tsbin_std_name,\n long_name=long_base_name + ' binned by temperature and salinity',\n var_name=var_base_name + '_tsbin',\n units=w_cube.units,\n attributes=t_cube.attributes,\n dim_coords_and_dims=tsbin_dim_coords_list)\n tsbin_cube.attributes['history'] = log\n outcube_list.append(tsbin_cube)\n\n return outcube_list\n\n\ndef clipping_details(orig_data, clipped_data, bin_edges, var_name):\n \"\"\"Details of the clipping\"\"\"\n\n bin_min = bin_edges[0]\n bin_second_min = bin_edges[1]\n bin_max = bin_edges[-1]\n bin_second_max = bin_edges[-2]\n\n npoints_under = np.sum(orig_data < bin_min)\n npoints_min = np.sum(orig_data <= bin_second_min) - npoints_under\n npoints_clip_min = np.sum(clipped_data <= bin_second_min) - np.sum(clipped_data < bin_min)\n assert npoints_clip_min == npoints_under + npoints_min\n\n npoints_over = np.sum(orig_data > bin_max)\n npoints_max = np.sum(orig_data <= bin_max) - np.sum(orig_data <= bin_second_max)\n npoints_clip_max = np.sum(clipped_data <= bin_max) - np.sum(clipped_data <= bin_second_max)\n assert npoints_clip_max == npoints_over + npoints_max\n\n logging.info(f\"First {var_name} bin had {npoints_min} values, clipping added {npoints_under}\")\n logging.info(f\"Last {var_name} bin had {npoints_max} values, clipping added {npoints_over}\")\n \n\ndef bin_data(df, var_list, edge_list, b_cube, mul_ts=False):\n \"\"\"Bin the data.\n\n Args:\n df (pandas.DataFrame) -- Data\n var_list (list) -- Variables for binning axes\n edge_list (list) -- Bin edges for each bin axis variable\n mul_ts (bool) -- Bin weights times T and S too\n\n \"\"\"\n\n data_list = []\n for var, edges in zip(var_list, edge_list):\n assert var in ['temperature', 'salinity', 'basin']\n values = np.clip(df[var].values, edges[0], edges[-1])\n clipping_details(df[var].values, values, edges, var)\n data_list.append(values)\n data = np.array(data_list).T\n\n w_data = df['weight'].astype(np.float64).values\n w_dist, edges = np.histogramdd(data, weights=w_data, bins=edge_list)\n binned_total_weight = w_dist.sum()\n orig_total_weight = w_data.sum()\n logging.info(f\"Global total before binning: {orig_total_weight}\")\n logging.info(f\"Global total after binning: {binned_total_weight}\")\n np.testing.assert_allclose(orig_total_weight, binned_total_weight, rtol=0.05)\n w_dist = select_basin(w_dist, b_cube)\n if mul_ts:\n ws_dist, edges = np.histogramdd(data, weights=w_data * df['salinity'].values, bins=edge_list)\n wt_dist, edges = np.histogramdd(data, weights=w_data * df['temperature'].values, bins=edge_list)\n ws_dist = select_basin(ws_dist, b_cube)\n wt_dist = select_basin(wt_dist, b_cube)\n return w_dist, ws_dist, wt_dist\n else:\n return w_dist\n \n\ndef select_basin(data, b_cube, basin='globe'):\n \"\"\"Select a basin\"\"\"\n\n assert basin == 'globe'\n\n data = np.ma.masked_invalid(data)\n data, b_values, flag_values, flag_meanings = uconv.add_globe_basin(data, b_cube)\n \n assert data.ndim in [2, 3, 4]\n if data.ndim == 2:\n data = data[:, -1]\n elif data.ndim == 3:\n data = data[:, :, -1]\n else:\n data = data[:, :, :, -1]\n\n return data\n\n\ndef get_weights_data(file_list, var):\n \"\"\"Read the weights data file/s\"\"\"\n \n w_var = mom_vars[var] if var in mom_vars else var\n if ('vol' in w_var) or ('area' in w_var):\n assert len(file_list) == 1\n w_cube = gio.get_ocean_weights(file_list[0])\n history = w_cube.attributes['history'] \n else:\n w_cube, history = gio.combine_files(file_list, var, checks=True)\n\n return w_cube, history\n\n\ndef get_log(inargs, w_history, t_history, s_history, b_cube, a_cube, v_cube):\n \"\"\"Get the log entry for the output file history attribute.\"\"\"\n\n metadata_dict = {}\n if w_history: \n metadata_dict[inargs.weights_files[0]] = w_history[0]\n if t_history: \n metadata_dict[inargs.temperature_files[0]] = t_history[0]\n if s_history: \n metadata_dict[inargs.salinity_files[0]] = s_history[0]\n if 'history' in b_cube.attributes:\n metadata_dict[inargs.basin_file] = b_cube.attributes['history']\n if a_cube:\n if 'history' in a_cube.attributes:\n metadata_dict[inargs.area_file] = a_cube.attributes['history']\n if v_cube:\n if 'history' in v_cube.attributes:\n metadata_dict[inargs.volume_file] = v_cube.attributes['history']\n\n log = cmdprov.new_log(infile_history=metadata_dict, git_repo=repo_dir)\n\n return log\n\n\ndef get_bin_data(files, var, w_cube):\n \"\"\"Get binning variable data.\"\"\"\n\n cube, history = gio.combine_files(files, var, checks=True)\n w_coord_names = [coord.name() for coord in w_cube.dim_coords]\n coord_names = [coord.name() for coord in cube.dim_coords]\n assert w_cube.shape[-2:] == cube.shape[-2:]\n if not w_cube.shape == cube.shape:\n if (w_cube.ndim == 3) and (cube.ndim == 4) and (w_coord_names[0] == coord_names[0]):\n #e.g. w_cube is surface flux (time, i, j),\n #cube is full depth temperature (time, depth, i, j)\n cube = cube[:, 0, ::]\n cube.remove_coord(coord_names[1])\n assert w_cube.shape == cube.shape \n elif (w_cube.ndim == 2) and (cube.ndim == 4):\n #e.g. w_cube is area (i, j),\n #cube is full depth temperature (time, depth, i, j)\n cube = cube[:, 0, ::]\n cube.remove_coord(coord_names[1])\n assert w_cube.shape == cube.shape[1:]\n else:\n #e.g. w_cube is area (i, j),\n #cube is surface temperature (time, i, j)\n #e.g. w_cube is volume (depth, i, j),\n #cube is temperature (time, depth, i, j)\n assert w_cube.shape == cube.shape[1:]\n\n return cube, history\n\n\ndef weighted_percentiles(data, weights, percentiles):\n \"\"\"Return the weighted percentiles.\n\n Args:\n data (np.ndarray) : Bin variable (e.g. temperature, salinity)\n weights (np.ndarray): Weights (e.g. cell volume, area)\n percentiles (np.ndarray): Array of requested percentiles (e.g. 0-1 by 0.01)\n\n \"\"\"\n \n assert percentiles.max() <= 1.0\n assert percentiles.min() >= 0.0\n\n wq = DescrStatsW(data=data, weights=weights)\n bin_edges = wq.quantile(probs=percentiles, return_pandas=False)\n\n # manual method does not give a clean results...\n #ix = np.argsort(data)\n #data = data[ix] # sort data\n #weights = weights[ix] # sort weights\n #cdf = (np.cumsum(weights) - 0.5 * weights) / np.sum(weights) # 'like' a CDF function\n #perc = np.arange(0, 1.01, 0.01)\n #test2 = np.interp(perc, cdf, data)\n\n return bin_edges\n\n\ndef process_data_by_year(t_cube, s_cube, w_cube,\n a_cube, v_cube, b_cube,\n t_values, s_values, b_values,\n nt_values, ns_values,\n s_edges, t_edges, b_edges,\n w_dtype, log, inargs):\n \"\"\"Implement annual binning.\"\"\"\n\n iris.coord_categorisation.add_year(t_cube, 'time')\n iris.coord_categorisation.add_year(s_cube, 'time')\n t_years = set(t_cube.coord('year').points)\n s_years = set(s_cube.coord('year').points)\n assert t_years == s_years\n if not w_dtype == 'spatial':\n iris.coord_categorisation.add_year(w_cube, 'time')\n w_years = set(w_cube.coord('year').points)\n assert w_years == t_years\n years = np.array(list(t_years))\n years.sort()\n \n w_tbin_outdata = np.ma.zeros([len(years), nt_values])\n w_sbin_outdata = np.ma.zeros([len(years), ns_values])\n w_tsbin_outdata = np.ma.zeros([len(years), ns_values, nt_values])\n if w_dtype == 'spatial':\n ws_tbin_outdata = np.ma.zeros([len(years), nt_values])\n wt_tbin_outdata = np.ma.zeros([len(years), nt_values])\n ws_sbin_outdata = np.ma.zeros([len(years), ns_values])\n wt_sbin_outdata = np.ma.zeros([len(years), ns_values])\n ws_tsbin_outdata = np.ma.zeros([len(years), ns_values, nt_values])\n wt_tsbin_outdata = np.ma.zeros([len(years), ns_values, nt_values])\n\n for year_index, year in enumerate(years):\n print(year) \n year_constraint = iris.Constraint(year=year)\n s_year_cube = s_cube.extract(year_constraint)\n t_year_cube = t_cube.extract(year_constraint)\n if w_dtype == 'spatial':\n w_year_cube = w_cube\n else:\n w_year_cube = w_cube.extract(year_constraint)\n\n if a_cube:\n w_year_cube = spatial_weights.multiply_by_area(w_year_cube, area_cube=a_cube)\n elif v_cube:\n w_year_cube = spatial_weights.multiply_by_volume(w_year_cube, volume_cube=v_cube)\n\n df, s_units, t_units = water_mass.create_df(w_year_cube, t_year_cube, s_year_cube, b_cube,\n multiply_weights_by_days_in_year_frac=True)\n if w_dtype == 'spatial':\n tbin_list = bin_data(df, ['temperature', 'basin'], [t_edges, b_edges], b_cube, mul_ts=True)\n sbin_list = bin_data(df, ['salinity', 'basin'], [s_edges, b_edges], b_cube, mul_ts=True)\n tsbin_list = bin_data(df, ['salinity', 'temperature', 'basin'], [s_edges, t_edges, b_edges], b_cube, mul_ts=True)\n w_tbin_outdata[year_index, ::], ws_tbin_outdata[year_index, ::], wt_tbin_outdata[year_index, ::] = tbin_list\n w_sbin_outdata[year_index, ::], ws_sbin_outdata[year_index, ::], wt_sbin_outdata[year_index, ::] = sbin_list\n w_tsbin_outdata[year_index, ::], ws_tsbin_outdata[year_index, ::], wt_tsbin_outdata[year_index, ::] = tsbin_list\n else:\n w_tbin_outdata[year_index, ::] = bin_data(df, ['temperature', 'basin'], [t_edges, b_edges], b_cube)\n w_sbin_outdata[year_index, ::] = bin_data(df, ['salinity', 'basin'], [s_edges, b_edges], b_cube)\n w_tsbin_outdata[year_index, ::] = bin_data(df, ['salinity', 'temperature', 'basin'], [s_edges, t_edges, b_edges], b_cube)\n \n outdata_dict = {}\n outdata_dict['w_tbin'] = w_tbin_outdata\n outdata_dict['w_sbin'] = w_sbin_outdata\n outdata_dict['w_tsbin'] = w_tsbin_outdata\n if w_dtype == 'spatial':\n outdata_dict['ws_tbin'] = ws_tbin_outdata\n outdata_dict['wt_tbin'] = wt_tbin_outdata\n outdata_dict['ws_sbin'] = ws_sbin_outdata\n outdata_dict['wt_sbin'] = wt_sbin_outdata\n outdata_dict['ws_tsbin'] = ws_tsbin_outdata\n outdata_dict['wt_tsbin'] = wt_tsbin_outdata\n mul_ts = True\n else:\n mul_ts = False\n\n outcube_list = construct_cube(outdata_dict, w_year_cube, t_cube, s_cube, b_cube,\n t_values, t_edges, t_units, s_values, s_edges, s_units,\n log, years=years, mul_ts=mul_ts)\n\n return outcube_list\n\n\ndef process_data(t_cube, s_cube, w_cube,\n a_cube, v_cube, b_cube,\n t_values, s_values, b_values,\n nt_values, ns_values,\n s_edges, t_edges, b_edges,\n w_dtype, log, inargs):\n \"\"\"Implement binning.\"\"\"\n\n nmonths = t_cube.coord('time').shape[0]\n \n w_tbin_outdata = np.ma.zeros([nmonths, nt_values])\n w_sbin_outdata = np.ma.zeros([nmonths, ns_values])\n w_tsbin_outdata = np.ma.zeros([nmonths, ns_values, nt_values])\n if w_dtype == 'spatial':\n ws_tbin_outdata = np.ma.zeros([nmonths, nt_values])\n wt_tbin_outdata = np.ma.zeros([nmonths, nt_values])\n ws_sbin_outdata = np.ma.zeros([nmonths, ns_values])\n wt_sbin_outdata = np.ma.zeros([nmonths, ns_values])\n ws_tsbin_outdata = np.ma.zeros([nmonths, ns_values, nt_values])\n wt_tsbin_outdata = np.ma.zeros([nmonths, ns_values, nt_values])\n\n for month in range(nmonths):\n print(month) \n s_month_cube = s_cube[month, ::]\n t_month_cube = t_cube[month, ::]\n\n if w_dtype == 'spatial':\n w_month_cube = w_cube\n else:\n w_month_cube = w_cube[month, ::]\n\n if a_cube:\n w_month_cube = spatial_weights.multiply_by_area(w_month_cube, area_cube=a_cube)\n elif v_cube:\n w_month_cube = spatial_weights.multiply_by_volume(w_month_cube, volume_cube=v_cube)\n \n df, s_units, t_units = water_mass.create_df(w_month_cube, t_month_cube, s_month_cube, b_cube)\n if w_dtype == 'spatial':\n tbin_list = bin_data(df, ['temperature', 'basin'], [t_edges, b_edges], b_cube, mul_ts=True)\n sbin_list = bin_data(df, ['salinity', 'basin'], [s_edges, b_edges], b_cube, mul_ts=True)\n tsbin_list = bin_data(df, ['salinity', 'temperature', 'basin'], [s_edges, t_edges, b_edges], b_cube, mul_ts=True)\n w_tbin_outdata[month, ::], ws_tbin_outdata[month, ::], wt_tbin_outdata[month, ::] = tbin_list\n w_sbin_outdata[month, ::], ws_sbin_outdata[month, ::], wt_sbin_outdata[month, ::] = sbin_list\n w_tsbin_outdata[month, ::], ws_tsbin_outdata[month, ::], wt_tsbin_outdata[month, ::] = tsbin_list\n else:\n w_tbin_outdata[month, ::] = bin_data(df, ['temperature', 'basin'], [t_edges, b_edges], b_cube)\n w_sbin_outdata[month, ::] = bin_data(df, ['salinity', 'basin'], [s_edges, b_edges], b_cube)\n w_tsbin_outdata[month, ::] = bin_data(df, ['salinity', 'temperature', 'basin'], [s_edges, t_edges, b_edges], b_cube)\n\n outdata_dict = {}\n outdata_dict['w_tbin'] = w_tbin_outdata\n outdata_dict['w_sbin'] = w_sbin_outdata\n outdata_dict['w_tsbin'] = w_tsbin_outdata\n if w_dtype == 'spatial':\n outdata_dict['ws_tbin'] = ws_tbin_outdata\n outdata_dict['wt_tbin'] = wt_tbin_outdata\n outdata_dict['ws_sbin'] = ws_sbin_outdata\n outdata_dict['wt_sbin'] = wt_sbin_outdata\n outdata_dict['ws_tsbin'] = ws_tsbin_outdata\n outdata_dict['wt_tsbin'] = wt_tsbin_outdata\n mul_ts = True\n else:\n mul_ts = False\n\n outcube_list = construct_cube(outdata_dict, w_month_cube, t_cube, s_cube, b_cube,\n t_values, t_edges, t_units, s_values, s_edges, s_units,\n log, mul_ts=mul_ts)\n\n return outcube_list\n\n\ndef main(inargs):\n \"\"\"Run the program.\"\"\"\n\n logging.basicConfig(level=logging.DEBUG)\n if ('vol' in inargs.weights_var) or ('area' in inargs.weights_var):\n weights_dtype = 'spatial'\n elif 'flux' in inargs.weights_var:\n weights_dtype = 'flux'\n else:\n weights_dtype = 'full field'\n\n w_cube, w_history = get_weights_data(inargs.weights_files, inargs.weights_var)\n t_cube, t_history = get_bin_data(inargs.temperature_files, inargs.temperature_var, w_cube)\n s_cube, s_history = get_bin_data(inargs.salinity_files, inargs.salinity_var, w_cube)\n b_cube = iris.load_cube(inargs.basin_file, 'region')\n if inargs.area_file:\n assert not inargs.volume_file, \"Cannot multiply weights by area and volume\"\n a_cube = gio.get_ocean_weights(inargs.area_file)\n else:\n a_cube = None\n if inargs.volume_file:\n assert not inargs.area_file, \"Cannot multiply weights by area and volume\"\n v_cube = gio.get_ocean_weights(inargs.volume_file)\n else:\n v_cube = None\n\n log = get_log(inargs, w_history, t_history, s_history, b_cube, a_cube, v_cube)\n\n b_values, b_edges = uconv.get_basin_details(b_cube)\n t_min, t_max = inargs.temperature_bounds\n t_step = inargs.tbin_size\n t_edges = np.arange(t_min, t_max + t_step, t_step)\n t_values = (t_edges[1:] + t_edges[:-1]) / 2 \n s_values, s_edges = uconv.salinity_bins()\n nt_values = len(t_values)\n ns_values = len(s_values)\n\n if inargs.bin_freq == 'yr':\n outcube_list = process_data_by_year(t_cube, s_cube, w_cube,\n a_cube, v_cube, b_cube,\n t_values, s_values, b_values,\n nt_values, ns_values,\n s_edges, t_edges, b_edges,\n weights_dtype,\n log, inargs) \n elif inargs.bin_freq == 'mon':\n outcube_list = process_data(t_cube, s_cube, w_cube,\n a_cube, v_cube, b_cube,\n t_values, s_values, b_values,\n nt_values, ns_values,\n s_edges, t_edges, b_edges,\n weights_dtype,\n log, inargs)\n\n iris.util.equalise_attributes(outcube_list)\n iris.save(outcube_list, inargs.outfile)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=__doc__,\n argument_default=argparse.SUPPRESS,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument(\"weights_files\", type=str, nargs='*', help=\"volume, area or a flux\")\n parser.add_argument(\"weights_var\", type=str, help=\"weights variable\")\n parser.add_argument(\"basin_file\", type=str, help=\"basin file (from calc_basin.py)\")\n parser.add_argument(\"bin_freq\", type=str, choices=('mon', 'yr'), help=\"Binning frequency\")\n parser.add_argument(\"outfile\", type=str, help=\"output file\")\n \n parser.add_argument(\"--temperature_files\", type=str, nargs='*', help=\"temperature files for the binning\") \n parser.add_argument(\"--temperature_var\", type=str, help=\"temperature variable\")\n parser.add_argument(\"--salinity_files\", type=str, nargs='*', help=\"salinity files for the binning\") \n parser.add_argument(\"--salinity_var\", type=str, help=\"salinity variable\")\n\n parser.add_argument(\"--area_file\", type=str, default=None, help=\"For multiplying weights by area\")\n parser.add_argument(\"--volume_file\", type=str, default=None, help=\"For multiplying weights by volume\")\n\n parser.add_argument(\"--temperature_bounds\", type=float, nargs=2, default=(-6, 50),\n help='bounds for the temperature (Y) axis')\n bin_default = 1/3.\n parser.add_argument(\"--tbin_size\", type=float, default=bin_default, help='temperature bin size')\n\n args = parser.parse_args() \n main(args)\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.axvline", "numpy.arange", "matplotlib.pyplot.axhspan", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel" ], [ "numpy.ma.masked_where", "numpy.ma.masked_invalid" ], [ "numpy.array", "numpy.cumsum" ], [ "numpy.clip", "numpy.arange", "numpy.histogramdd", "numpy.ma.masked_invalid", "numpy.testing.assert_allclose", "numpy.array", "numpy.ma.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.10", "1.12", "1.19", "1.13", "1.16", "1.9", "1.18", "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": [] } ]
vipavlovic/pyprobml
[ "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141", "59a2edc682d0163955db5e2f27491ad772b60141" ]
[ "scripts/emnist_viz_tf.py", "scripts/spectral_clustering_demo.py", "scripts/logreg_iris_bayes_2d_pymc3.py", "vae/models/vq_vae.py", "scripts/mix_gauss_singularity.py", "scripts/newtonsMethodMinQuad.py", "misc/github_stats.py", "scripts/pagerank_demo_harvard.py", "scripts/rvm_regressor.py", "scripts/vanishing_gradients.py", "scripts/ard_vb_linreg_logreg.py" ]
[ "\n\n\nimport superimport\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyprobml_utils as pml\n\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nnp.random.seed(0)\n\nds, info = tfds.load('emnist', split='test', shuffle_files=False, with_info=True) # horribly slow\nprint(info)\n\n\nplt.figure(figsize=(10, 10))\ni = 0\nfor example in ds:\n image = example[\"image\"]\n label = example[\"label\"]\n plt.subplot(5, 5, i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(image)\n plt.title(label)\n i += 1\n if i >= 25: break\n\npml.savefig(\"emnist-data.pdf\")\nplt.show()", "import superimport\n\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.linalg import eigh\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import rbf_kernel\nimport pyprobml_utils as pml\n\nplt.style.use('classic')\n\ndef spectral_clustering_demo():\n np.random.seed(0)\n num_clusters = 2\n for data_type, data in (('circle', sample_circle(num_clusters)),\n ('spiral', sample_spiral())):\n kmeans = KMeans(n_clusters=num_clusters, random_state=0)\n kmeans.fit(data)\n assignments = kmeans.predict(data)\n plot_data(data, assignments, 'k-means clustering', data_type)\n\n sigma = 0.1\n gamma = 1 / (2 * sigma ** 2)\n W = rbf_kernel(data, gamma=gamma)\n d = np.sum(W, 1, keepdims=True)\n sqrt_d = np.sqrt(d)\n\n normalized_W = (W / sqrt_d) / sqrt_d.T\n paranoid_assert(W, normalized_W, False)\n\n # We select the largest eigen values of normalized_W, rather\n # than the smallest eigenvalues of I - normalized_W. The two\n # problems are equivalent. The eigen values can be converted\n # between the two problems via `1 - eigen_values`. The eigen\n # vectors are the same between both problems.\n eigen_values, eigen_vectors = eigh(normalized_W,\n # Get only the top num_clusters eigenvalues\n eigvals=(data.shape[0] - num_clusters, data.shape[0]-1))\n eigen_vectors = eigen_vectors / np.linalg.norm(eigen_vectors, axis=1, keepdims=True)\n\n kmeans.fit(eigen_vectors)\n assignments = kmeans.predict(eigen_vectors)\n plot_data(data, assignments, 'spectral clustering', data_type)\n\n plt.show()\n\ndef paranoid_assert(W, normalized_W, enable):\n if not enable:\n return\n D = np.diag(np.sum(W, 1))\n L = D - W\n D_inv_sqrt = np.diag(1 / np.diag(np.sqrt(D)))\n np.testing.assert_almost_equal(np.sum(L, 1), 0, err_msg=\"Rows of Laplacian must sum to 0.\")\n np.testing.assert_allclose(normalized_W, D_inv_sqrt * W * D_inv_sqrt, rtol=0, atol=1)\n\ndef sample_circle(num_clusters):\n points_per_cluster = 500\n bandwidth = 0.1\n\n data = np.zeros((num_clusters * points_per_cluster, 2))\n for k, n in itertools.product(range(num_clusters), range(points_per_cluster)):\n theta = 2 * np.pi * np.random.uniform()\n rho = k + 1 + np.random.randn() * bandwidth\n x, y = pol2cart(theta, rho)\n idx = k * points_per_cluster + n\n data[idx, 0] = x\n data[idx, 1] = y\n data = data.reshape((num_clusters * points_per_cluster, 2))\n return data\n\ndef pol2cart(theta, rho):\n x = rho * np.cos(theta)\n y = rho * np.sin(theta)\n return(x, y)\n\ndef sample_spiral():\n # Only 2 clusters in this case. This is hard-coded.\n points_per_cluster = 500\n bandwidth = 0.1\n\n data = np.empty((points_per_cluster, 2))\n\n w = np.arange(1, points_per_cluster + 1).astype(np.float32) / points_per_cluster\n data[:,0] = (4 * w + 1) * np.cos(2*np.pi * w) + np.random.randn(points_per_cluster) * bandwidth\n data[:,1] = (4 * w + 1) * np.sin(2*np.pi * w) + np.random.randn(points_per_cluster) * bandwidth\n data = np.vstack((data, -data))\n\n return data\n\ndef plot_data(data, assignments, title, data_type):\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot(data[assignments == 0, 0], data[assignments == 0, 1], 'o', color='r')\n ax.plot(data[assignments == 1, 0], data[assignments == 1, 1], 'o', color='b')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.axis('square')\n ax.grid(True)\n ax.set_title(title)\n plt.tight_layout()\n pml.savefig(f\"{data_type}_{title.replace(' ', '_')}.pdf\")\n\nif __name__ == '__main__':\n spectral_clustering_demo()\n", "# Bayesian Binary logistic regression in 2d for iris flwoers\n\n# Code is based on \n# https://github.com/aloctavodia/BAP/blob/master/code/Chp4/04_Generalizing_linear_models.ipynb\n\nimport superimport\n\nimport pymc3 as pm\nimport numpy as np\nimport pandas as pd\nimport theano.tensor as tt\n#import seaborn as sns\nimport scipy.stats as stats\nfrom scipy.special import expit as logistic\nimport matplotlib.pyplot as plt\nimport arviz as az\nfrom sklearn.datasets import load_iris\nimport pyprobml_utils as pml\n\niris = load_iris()\nX = iris.data \ny = iris.target\n\n# Convert to pandas dataframe \ndf_iris = pd.DataFrame(data=iris.data, \n columns=['sepal_length', 'sepal_width', \n 'petal_length', 'petal_width'])\ndf_iris['species'] = pd.Series(iris.target_names[y], dtype='category')\n\n\ndf = df_iris.query(\"species == ('setosa', 'versicolor')\") \n\n# We reduce the sample size from 50 to 25 per class,\n# or to 5 + 45 in the unbalanced setting.\n# The latter will increase posterior uncertainty\nunbalanced = False # True\nif unbalanced:\n df = df[45:95]\nelse:\n df = df[25:75]\nassert(len(df)==50)\n\ny_1 = pd.Categorical(df['species']).codes \nx_n = ['sepal_length', 'sepal_width'] \nx_1 = df[x_n].values\n\n\nwith pm.Model() as model_1: \n α = pm.Normal('α', mu=0, sd=10) \n β = pm.Normal('β', mu=0, sd=2, shape=len(x_n)) \n \n μ = α + pm.math.dot(x_1, β) \n θ = pm.Deterministic('θ', 1 / (1 + pm.math.exp(-μ))) \n bd = pm.Deterministic('bd', -α/β[1] - β[0]/β[1] * x_1[:,0])\n \n yl = pm.Bernoulli('yl', p=θ, observed=y_1) \n \n trace_1 = pm.sample(2000, cores=1, chains=2)\n \nvarnames = ['α', 'β'] \n#az.plot_forest(trace_1, var_names=varnames);\n\nidx = np.argsort(x_1[:,0]) \nbd = trace_1['bd'].mean(0)[idx] \n\nplt.figure()\nplt.scatter(x_1[:,0], x_1[:,1], c=[f'C{x}' for x in y_1]) \nplt.plot(x_1[:,0][idx], bd, color='k'); \n\naz.plot_hdi(x_1[:,0], trace_1['bd'], color='k')\n \nplt.xlabel(x_n[0]) \nplt.ylabel(x_n[1])\n\nplt.tight_layout()\nif unbalanced:\n pml.savefig('logreg_iris_bayes_2d_unbalanced.pdf', dpi=300)\nelse:\n pml.savefig('logreg_iris_bayes_2d.pdf', dpi=300)\n \nplt.show()", "\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch import Tensor\nfrom typing import Optional, Callable\n\nclass VectorQuantizer(nn.Module):\n \"\"\"\n Reference:\n [1] https://github.com/deepmind/sonnet/blob/v2/sonnet/src/nets/vqvae.py\n \"\"\"\n def __init__(self,\n num_embeddings: int,\n embedding_dim: int,\n beta: float = 0.25):\n super(VectorQuantizer, self).__init__()\n self.K = num_embeddings\n self.D = embedding_dim\n self.beta = beta\n\n self.embedding = nn.Embedding(self.K, self.D)\n self.embedding.weight.data.uniform_(-1 / self.K, 1 / self.K)\n\n def get_codebook_indices(self, latents:Tensor) -> Tensor:\n flat_latents = latents.view(-1, self.D) # [BHW x D]\n\n # Compute L2 distance between latents and embedding weights\n dist = torch.sum(flat_latents ** 2, dim=1, keepdim=True) + \\\n torch.sum(self.embedding.weight ** 2, dim=1) - \\\n 2 * torch.matmul(flat_latents, self.embedding.weight.t()) # [BHW x K]\n\n # Get the encoding that has the min distance\n encoding_inds = torch.argmin(dist, dim=1).unsqueeze(1) # [BHW, 1]\n return encoding_inds\n\n def forward(self, latents: Tensor) -> Tensor:\n latents = latents.permute(0, 2, 3, 1).contiguous() # [B x D x H x W] -> [B x H x W x D]\n latents_shape = latents.shape\n encoding_inds = self.get_codebook_indices(latents)\n\n # Convert to one-hot encodings\n device = latents.device\n encoding_one_hot = torch.nn.functional.one_hot(encoding_inds, num_classes=self.K).float().to(device)\n\n # Quantize the latents\n quantized_latents = torch.matmul(encoding_one_hot, self.embedding.weight) # [BHW, D]\n quantized_latents = quantized_latents.view(latents_shape) # [B x H x W x D]\n\n # Compute the VQ Losses\n commitment_loss = F.mse_loss(quantized_latents.detach(), latents)\n embedding_loss = F.mse_loss(quantized_latents, latents.detach())\n\n vq_loss = commitment_loss * self.beta + embedding_loss\n\n # Add the residue back to the latents\n quantized_latents = latents + (quantized_latents - latents).detach()\n\n return quantized_latents.permute(0, 3, 1, 2).contiguous(), vq_loss # [B x D x H x W]\n\nclass ResidualLayer(nn.Module):\n\n def __init__(self,\n in_channels: int,\n out_channels: int):\n super(ResidualLayer, self).__init__()\n self.resblock = nn.Sequential(nn.Conv2d(in_channels, out_channels,\n kernel_size=3, padding=1, bias=False),\n nn.ReLU(True),\n nn.Conv2d(out_channels, out_channels,\n kernel_size=1, bias=False))\n\n def forward(self, input: Tensor) -> Tensor:\n return input + self.resblock(input)\n\nclass Encoder(nn.Module):\n\n def __init__(self, \n in_channels: int = 3, \n hidden_dims: Optional[list] = None,\n latent_dim: int = 256):\n super(Encoder, self).__init__()\n\n modules = []\n if hidden_dims is None:\n hidden_dims = [128, 256]\n\n # Build Encoder\n for h_dim in hidden_dims:\n modules.append(\n nn.Sequential(\n nn.Conv2d(in_channels, out_channels=h_dim,\n kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU())\n )\n in_channels = h_dim\n\n modules.append(\n nn.Sequential(\n nn.Conv2d(in_channels, in_channels,\n kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU())\n )\n\n for _ in range(6):\n modules.append(ResidualLayer(in_channels, in_channels))\n modules.append(nn.LeakyReLU())\n\n modules.append(\n nn.Sequential(\n nn.Conv2d(in_channels, latent_dim,\n kernel_size=1, stride=1),\n nn.LeakyReLU())\n )\n\n self.encoder = nn.Sequential(*modules)\n\n def forward(self, x):\n result = self.encoder(x)\n return [result]\n\nclass Decoder(nn.Module):\n\n def __init__(self,\n hidden_dims: Optional[list] = None,\n latent_dim: int = 256):\n super(Decoder, self).__init__()\n\n modules = []\n\n if hidden_dims is None:\n hidden_dims = [128, 256]\n\n modules.append(\n nn.Sequential(\n nn.Conv2d(latent_dim,\n hidden_dims[-1],\n kernel_size=3,\n stride=1,\n padding=1),\n nn.LeakyReLU())\n )\n\n for _ in range(6):\n modules.append(ResidualLayer(hidden_dims[-1], hidden_dims[-1]))\n\n modules.append(nn.LeakyReLU())\n\n hidden_dims.reverse()\n\n for i in range(len(hidden_dims) - 1):\n modules.append(\n nn.Sequential(\n nn.ConvTranspose2d(hidden_dims[i],\n hidden_dims[i + 1],\n kernel_size=4,\n stride=2,\n padding=1),\n nn.LeakyReLU())\n )\n\n modules.append(\n nn.Sequential(\n nn.ConvTranspose2d(hidden_dims[-1],\n out_channels=3,\n kernel_size=4,\n stride=2, padding=1),\n nn.Tanh()))\n\n self.decoder = nn.Sequential(*modules)\n\n def forward(self, z):\n result = self.decoder(z)\n return result\n\ndef loss(config, x_hat, x, vq_loss):\n\n recons_loss = F.mse_loss(x_hat, x)\n\n loss = recons_loss + vq_loss\n return loss\n\nclass VQVAE(nn.Module):\n\n def __init__(self,\n name: str, \n loss: Callable, \n encoder: Callable,\n decoder: Callable,\n config: dict) -> None:\n super(VQVAE, self).__init__()\n\n self.name = name\n self.loss = loss\n self.encoder = encoder\n self.decoder = decoder\n self.vq_layer = VectorQuantizer(config[\"num_embeddings\"],\n config[\"embedding_dim\"],\n config[\"beta\"])\n\n def forward(self, x: Tensor):\n encoding = self.encoder(x)[0]\n quantized_inputs, vq_loss = self.vq_layer(encoding)\n return self.decoder(quantized_inputs)\n\n def _run_step(self, x: Tensor):\n encoding = self.encoder(x)[0]\n quantized_inputs, vq_loss = self.vq_layer(encoding)\n return self.decoder(quantized_inputs), x, vq_loss\n \n def compute_loss(self, x):\n x_hat, x, vq_loss = self._run_step(x)\n\n loss = self.loss(x_hat, x, vq_loss)\n\n return loss\n", "# Ilustration of how singularities can arise in the likelihood function\n# of GMMs\n\n# Author: Gerardo Durán Martín\n\nimport superimport\n\nimport numpy as np\nimport pyprobml_utils as pml\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\n\ndef main():\n f1 = norm(loc=0.5, scale=0.12)\n f2 = norm(loc=0.15, scale=0.02)\n\n domain = np.arange(0, 1, 0.001)\n datapoints = np.array([0.15, 0.21, 0.25, 0.32, 0.45, 0.58, 0.72, 0.88])\n\n def f3(x): return f1.pdf(x) + f2.pdf(x)\n\n plt.stem(datapoints, f3(datapoints), linefmt=\"tab:green\", basefmt=\" \")\n for datapoint in datapoints:\n plt.scatter(datapoint, -0.1, c=\"black\", zorder=2)\n plt.plot(domain, f3(domain), c=\"tab:red\", zorder=1)\n plt.xlabel(\"x\", fontsize=13)\n plt.ylabel(\"p(x)\", fontsize=13)\n plt.xlim(0.01, 0.98)\n plt.xticks([])\n plt.yticks([])\n pml.savefig('gmm_singularity.pdf')\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n", "import superimport\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nimport pyprobml_utils as pml\n\nxmin = -5\nxmax = 0\nymin = -20\nymax = 150\ndomain = np.arange(xmin, xmax+0.01, 0.01)\n\n\ndef f(x): return - np.power(x, 3)\n\n\nXk = -4\ndef f1(x): return - 3 * np.power(x, 2)\ndef f2(x): return - 6 * x\ndef t(x): return f(Xk) + f1(Xk)*(x - Xk) + (1/2)*f2(Xk) * np.power((x - Xk), 2)\n\n\nminNDX = np.argmin(t(domain))\nminimum = domain[minNDX]\n\nh1 = plt.plot(domain, f(domain), '-r')\nh2 = plt.plot(domain, t(domain), '--b')\nplt.plot(Xk, f(Xk), '.k')\nplt.plot([Xk, Xk], [ymin, f(Xk)], ':k')\nplt.plot(minimum, t(minimum), '.k')\nplt.plot([minimum, minimum], [ymin, t(minimum)], ':k')\nplt.axis([xmin, xmax, ymin, ymax])\nplt.xticks([], [])\nplt.yticks([], [])\nplt.text(-4.1, -30, '\\u03B8'+'\\u2096', fontsize=14)\nplt.text(-2.1, -30, '\\u03B8'+'\\u2096'+'+'+'d'+'\\u2096', fontsize=14)\npml.savefig(r'newtonsMethodMinQuadTheta.pdf')\nplt.show()\n", "from datetime import datetime\nfrom github import Github\nimport pandas as pd\nimport os\npd.set_option(\"display.max_colwidth\", 100)\n\npublic_access_token = os.environ[\"GH_PUBLIC_ACCESS_TOKEN\"]\ng = Github(public_access_token)\nrepo = g.get_repo(\"probml/pyprobml\")\nprint(repo)", "'''\nFinds the stationary distributions for the graph consisting of 6 nodes and one for Harvard500. Then, compares\nthe results found by matrix inversion and power method. Plots the bar plots.\nAuthor: Cleve Moler, Aleyna Kara\nThis file is converted to Python from https://github.com/probml/pmtk3/blob/master/demos/pagerankDemoPmtk.m\n'''\n\nimport superimport\n\nimport numpy as np\nfrom pagerank_power_method_sparse import pagerank_power_method_sparse\nimport matplotlib.pyplot as plt\nimport pyprobml_utils as pml\nfrom scipy.io import loadmat\n\nimport requests\nfrom io import BytesIO\n\nurl = 'https://github.com/probml/probml-data/blob/main/data/harvard500.mat?raw=true'\nresponse = requests.get(url)\nrawdata = BytesIO(response.content)\nmat = loadmat(rawdata)\nG_harvard = mat['G']\n\n#plt.figure(figsize=(6, 6))\nplt.spy(G_harvard, c='blue', marker='.', markersize=1)\nplt.xticks([])\nplt.yticks([])\nplt.tight_layout()\npml.savefig('harvard500-spy')\nplt.show()\n\np = 0.85\npi_sparse_harvard = pagerank_power_method_sparse(G_harvard, p)[0]\n\nfig, ax = plt.subplots()\nplt.bar(np.arange(0, pi_sparse_harvard.shape[0]), pi_sparse_harvard, width=1.0, color='darkblue')\nax.set_ylim([0, 0.02])\npml.savefig('harvard500-pagerank')\nplt.show()\n\n", "\"\"\"\ncode taken from\nhttps://github.com/ctgk/PRML/blob/master/prml/kernel/relevance_vector_regressor.py\n\"\"\"\n\nimport superimport\n\nimport numpy as np\n\n\nclass RelevanceVectorRegressor(object):\n\n def __init__(self, kernel, alpha=1., beta=1.):\n \"\"\"\n construct relevance vector regressor\n Parameters\n ----------\n kernel : Kernel\n kernel function to compute components of feature vectors\n alpha : float\n initial precision of prior weight distribution\n beta : float\n precision of observation\n \"\"\"\n self.kernel = kernel\n self.alpha = alpha\n self.beta = beta\n\n def fit(self, X, t, iter_max=1000):\n \"\"\"\n maximize evidence with respect to hyperparameter\n Parameters\n ----------\n X : (sample_size, n_features) ndarray\n input\n t : (sample_size,) ndarray\n corresponding target\n iter_max : int\n maximum number of iterations\n Attributes\n -------\n X : (N, n_features) ndarray\n relevance vector\n t : (N,) ndarray\n corresponding target\n alpha : (N,) ndarray\n hyperparameter for each weight or training sample\n cov : (N, N) ndarray\n covariance matrix of weight\n mean : (N,) ndarray\n mean of each weight\n \"\"\"\n if X.ndim == 1:\n X = X[:, None]\n assert X.ndim == 2\n assert t.ndim == 1\n N = len(t)\n Phi = self.kernel(X, X)\n self.alpha = np.zeros(N) + self.alpha\n for _ in range(iter_max):\n params = np.hstack([self.alpha, self.beta])\n precision = np.diag(self.alpha) + self.beta * Phi.T @ Phi\n covariance = np.linalg.inv(precision)\n mean = self.beta * covariance @ Phi.T @ t\n gamma = 1 - self.alpha * np.diag(covariance)\n self.alpha = gamma / np.square(mean)\n np.clip(self.alpha, 0, 1e10, out=self.alpha)\n self.beta = (N - np.sum(gamma)) / np.sum((t - Phi.dot(mean)) ** 2)\n if np.allclose(params, np.hstack([self.alpha, self.beta])):\n break\n mask = self.alpha < 1e9\n self.X = X[mask]\n self.t = t[mask]\n self.alpha = self.alpha[mask]\n Phi = self.kernel(self.X, self.X)\n precision = np.diag(self.alpha) + self.beta * Phi.T @ Phi\n self.covariance = np.linalg.inv(precision)\n self.mean = self.beta * self.covariance @ Phi.T @ self.t\n\n def predict(self, X, with_error=True):\n \"\"\"\n predict output with this model\n Parameters\n ----------\n X : (sample_size, n_features)\n input\n with_error : bool\n if True, predict with standard deviation of the outputs\n Returns\n -------\n mean : (sample_size,) ndarray\n mean of predictive distribution\n std : (sample_size,) ndarray\n standard deviation of predictive distribution\n \"\"\"\n if X.ndim == 1:\n X = X[:, None]\n assert X.ndim == 2\n phi = self.kernel(X, self.X)\n mean = phi @ self.mean\n if with_error:\n var = 1 / self.beta + np.sum(phi @ self.covariance * phi, axis=1)\n return mean, np.sqrt(var)\n return mean\n", "# Vanishing gradients for certain activation functions\n\n# Based on \n#https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b\n\nimport superimport\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_grad(x):\n p = sigmoid(x)\n return p*(1-p)\n\ndef relu(x):\n return np.maximum(0, x)\n\ndef heaviside(x):\n return (x > 0)\n\ndef relu_grad(x):\n return heaviside(x)\n\nx = np.linspace(-10, 10, 100)\ny = sigmoid(x);\nplt.figure()\nplt.plot(x, y)\nplt.title('sigmoid function')\nplt.savefig('../figures/sigmoid.pdf')\nplt.show()\n\ny = sigmoid_grad(x);\nplt.figure()\nplt.plot(x, y)\nplt.title('derivative of sigmoid')\nplt.ylim(0,1)\nplt.savefig('../figures/sigmoid_deriv.pdf')\nplt.show()\n\nx = np.linspace(-10, 10, 100)\ny = relu(x);\nplt.figure()\nplt.plot(x, y)\nplt.title('relu function')\nplt.savefig('../figures/relu.pdf')\nplt.show()\n\ny = relu_grad(x);\nplt.figure()\nplt.plot(x, y)\nplt.title('derivative of relu')\nplt.ylim(-0.1,1.1)\nplt.savefig('../figures/relu_deriv.pdf')\nplt.show()", "# Bayesian Linear and logistic Regression with ARD prior (fitted with Variational Bayes)\n\n#https://github.com/AmazaspShumik/sklearn-bayes/blob/master/skbayes/rvm_ard_models/vrvm.py\n\nimport superimport\n\nimport numpy as np\nfrom sklearn.externals import six\nfrom scipy.special import expit\nfrom scipy.linalg import solve_triangular\nfrom sklearn.linear_model.base import LinearModel, LinearClassifierMixin\nfrom sklearn.base import RegressorMixin, BaseEstimator\nfrom sklearn.utils import check_X_y,check_array\nfrom sklearn.metrics.pairwise import pairwise_kernels\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.utils.multiclass import check_classification_targets\nfrom sklearn.utils import as_float_array\nimport warnings\n\n\nclass VBRegressionARD(LinearModel,RegressorMixin):\n '''\n Bayesian Linear Regression with ARD prior (fitted with Variational Bayes)\n \n Parameters\n ----------\n n_iter: int, optional (DEFAULT = 100)\n Maximum number of iterations\n fit_intercept : boolean, optional (DEFAULT = True)\n If True, intercept will be used in computation\n \n tol: float, optional (DEFAULT = 1e-3)\n If absolute change in precision parameter for weights is below threshold\n algorithm terminates.\n \n copy_X : boolean, optional (DEFAULT = True)\n If True, X will be copied, otherwise it will be overwritten.\n \n verbose : boolean, optional (DEFAULT = True)\n Verbose mode when fitting the model \n \n a: float, optional, (DEFAULT = 1e-5)\n Shape parameters for Gamma distributed precision of weights\n \n b: float, optional, (DEFAULT = 1e-5)\n Rate parameter for Gamma distributed precision of weights\n \n c: float, optional, (DEFAULT = 1e-5)\n Shape parameter for Gamma distributed precision of noise\n \n d: float, optional, (DEFAULT = 1e-5)\n Rate parameter for Gamma distributed precision of noise\n \n prune_thresh: float, ( DEFAULT = 1e-3 )\n Threshold for pruning out variable (applied after model is fitted)\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise\n sigma_ : array, shape = (n_features, n_features)\n Estimated covariance matrix of the weights, computed only\n for non-zero coefficients\n \n Reference:\n ----------\n [1] Bishop & Tipping (2000), Variational Relevance Vector Machine\n [2] Jan Drugowitch (2014), Variational Bayesian Inference for Bayesian Linear \n and Logistic Regression\n [3] Bishop (2006) Pattern Recognition and Machine Learning (ch. 7)\n '''\n def __init__(self, n_iter = 100, tol = 1e-3, fit_intercept = True,\n a = 1e-5, b = 1e-5, c = 1e-5, d = 1e-5, copy_X = True, \n prune_thresh = 1e-3, verbose = False):\n self.n_iter = n_iter\n self.tol = tol\n self.fit_intercept = fit_intercept\n self.a,self.b = a,b\n self.c,self.d = c,d\n self.copy_X = copy_X\n self.verbose = verbose\n self.prune_thresh = prune_thresh\n \n \n def _center_data(self,X,y):\n ''' Centers data'''\n X = as_float_array(X,self.copy_X)\n # normalisation should be done in preprocessing!\n X_std = np.ones(X.shape[1], dtype = X.dtype)\n if self.fit_intercept:\n X_mean = np.average(X,axis = 0)\n y_mean = np.average(y,axis = 0)\n X -= X_mean\n y = y - y_mean\n else:\n X_mean = np.zeros(X.shape[1],dtype = X.dtype)\n y_mean = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype)\n return X,y, X_mean, y_mean, X_std\n \n \n def fit(self,X,y):\n '''\n Fits variational relevance ARD regression\n \n Parameters\n -----------\n X: array-like of size [n_samples, n_features]\n Training data, matrix of explanatory variables\n \n y: array-like of size [n_samples, n_features] \n Target values\n \n Returns\n -------\n self : object\n Returns self.\n '''\n # precompute some values for faster iterations \n X, y = check_X_y(X, y, dtype=np.float64, y_numeric=True)\n n_samples, n_features = X.shape\n X, y, X_mean, y_mean, X_std = self._center_data(X, y)\n XX = np.dot(X.T,X)\n XY = np.dot(X.T,y)\n Y2 = np.sum(y**2)\n \n # final update for a and c\n a = (self.a + 0.5) * np.ones(n_features, dtype = np.float)\n c = (self.c + 0.5 * n_samples) #* np.ones(n_features, dtype = np.float)\n # initial values of b,d before mean field approximation\n d = self.d #* np.ones(n_features, dtype = np.float)\n b = self.b * np.ones(n_features, dtype = np.float)\n active = np.ones(n_features, dtype = np.bool)\n w0 = np.zeros(n_features) \n w = np.copy(w0)\n \n for i in range(self.n_iter):\n # ---------------------- update q(w) -----------------------\n \n # calculate expectations for precision of noise & precision of weights\n e_tau = c / d\n e_A = a / b\n XXa = XX[active,:][:,active]\n XYa = XY[active]\n Xa = X[:,active]\n # parameters of updated posterior distribution\n w[active],Ri = self._posterior_weights(XXa,XYa,e_tau,e_A[active])\n \n # --------------------- update q(tau) ------------------------\n # update rate parameter for Gamma distributed precision of noise \n XSX = np.sum( np.dot(Xa,Ri.T)**2)\n XMw = np.sum( np.dot(Xa,w[active])**2 ) \n XYw = np.sum( w[active]*XYa )\n d = self.d + 0.5*(Y2 + XMw + XSX) - XYw\n \n # -------------------- update q(alpha(j)) for each j ----------\n # update rate parameter for Gamma distributed precision of weights\n b[active] = self.b + 0.5*(w[active]**2 + np.sum(Ri**2,axis = 1))\n \n # -------------------- check convergence ----------------------\n # determine relevant vector as is described in Bishop & Tipping \n # (i.e. using mean of posterior distribution)\n active = np.abs(w) > self.prune_thresh\n \n # make sure there is at least one relevant feature\n if np.sum(active) == 0:\n active[np.argmax(np.abs(w))] = True\n # all irrelevant features are forced to zero\n w[~active] = 0\n # check convergence\n if np.sum(abs(w-w0) > self.tol) == 0 or i==self.n_iter-1:\n break\n w0 = np.copy(w)\n # if only one relevant feature => terminate\n if np.sum(active)== 1:\n if X.shape[1] > 3 and self.prune_thresh > 1e-1:\n warnings.warn((\"Only one relevant feature found! it can be useful to decrease\"\n \"value for parameter prune_thresh\"))\n break\n \n # update parameters after last update\n e_tau = c / d\n e_A = a / b \n XXa = XX[active,:][:,active]\n XYa = XY[active]\n w[active], self.sigma_ = self._posterior_weights(XXa,XYa,e_tau,e_A[active],True)\n self._e_tau_ = e_tau \n self.coef_ = w\n self._set_intercept(X_mean,y_mean,X_std)\n self.active_ = active \n return self\n \n \n \n def predict_dist(self,X):\n '''\n Computes predictive distribution for test set.\n Predictive distribution for each data point is one dimensional\n Gaussian and therefore is characterised by mean and standard\n deviation.\n \n Parameters\n -----------\n X: {array-like, sparse} [n_samples_test, n_features]\n Test data, matrix of explanatory variables\n \n Returns\n -------\n y_hat: numpy array of size (n_samples_test,)\n Estimated values of targets on test set (Mean of predictive distribution)\n \n var_hat: numpy array of size (n_samples_test,)\n Error bounds (Standard deviation of predictive distribution)\n '''\n y_hat = self._decision_function(X)\n data_noise = 1./self._e_tau_\n model_noise = np.sum( np.dot(X[:,self.active_],self.sigma_) * X[:,self.active_], axis = 1)\n var_hat = data_noise + model_noise \n return y_hat, var_hat\n \n \n \n def _posterior_weights(self, XX, XY, exp_tau, exp_A, full_covar = False):\n '''\n Calculates parameters of posterior distribution of weights\n \n Parameters:\n -----------\n X: numpy array of size n_features\n Matrix of active features (changes at each iteration)\n \n XY: numpy array of size [n_features]\n Dot product of X and Y (for faster computations)\n exp_tau: float\n Mean of precision parameter of noise\n \n exp_A: numpy array of size n_features\n Vector of precisions for weights\n \n Returns:\n --------\n [Mw, Sigma]: list of two numpy arrays\n \n Mw: mean of posterior distribution\n Sigma: covariance matrix\n '''\n # compute precision parameter\n S = exp_tau*XX \n np.fill_diagonal(S, np.diag(S) + exp_A)\n \n # cholesky decomposition\n R = np.linalg.cholesky(S)\n \n # find mean of posterior distribution\n RtMw = solve_triangular(R, exp_tau*XY, lower = True, check_finite = False)\n Mw = solve_triangular(R.T, RtMw, lower = False, check_finite = False)\n \n # use cholesky decomposition of S to find inverse ( or diagonal of inverse)\n Ri = solve_triangular(R, np.eye(R.shape[1]), lower = True, check_finite = False)\n if full_covar:\n Sigma = np.dot(Ri.T,Ri)\n return [Mw,Sigma]\n else:\n return [Mw,Ri]\n\n\n#---------------------- Classification ---------------------------------------------\n\n\n\ndef lam(eps):\n ''' \n Calculates lambda eps [part of local variational approximation\n to sigmoid function]\n '''\n return 0.5 / eps * ( expit(eps) - 0.5 )\n \n\nclass VBClassificationARD(LinearClassifierMixin, BaseEstimator):\n '''\n Variational Bayesian Logistic Regression with local variational approximation.\n \n \n Parameters:\n -----------\n n_iter: int, optional (DEFAULT = 50 )\n Maximum number of iterations\n \n tol: float, optional (DEFAULT = 1e-3)\n Convergence threshold, if cange in coefficients is less than threshold\n algorithm is terminated\n \n fit_intercept: bool, optinal ( DEFAULT = True )\n If True uses bias term in model fitting\n \n a: float, optional (DEFAULT = 1e-6)\n Rate parameter for Gamma prior on precision parameter of coefficients\n \n b: float, optional (DEFAULT = 1e-6)\n Shape parameter for Gamma prior on precision parameter of coefficients\n \n prune_thresh: float, optional (DEFAULT = 1e-4)\n Threshold for pruning out variable (applied after model is fitted)\n \n verbose: bool, optional (DEFAULT = False)\n Verbose mode\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n sigma_ : array, shape = (n_features, n_features)\n estimated covariance matrix of the weights, computed only\n for non-zero coefficients\n \n intercept_: array, shape = (n_features)\n intercepts\n \n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise \n References:\n -----------\n [1] Bishop 2006, Pattern Recognition and Machine Learning ( Chapter 7,10 )\n [2] Murphy 2012, Machine Learning A Probabilistic Perspective ( Chapter 14,21 )\n [3] Bishop & Tipping 2000, Variational Relevance Vector Machine\n '''\n def __init__(self, n_iter = 100, tol = 1e-3, fit_intercept = True,\n a = 1e-4, b = 1e-4, prune_thresh = 1e-4, verbose = True):\n self.n_iter = n_iter\n self.tol = tol\n self.verbose = verbose\n self.prune_thresh = prune_thresh\n self.fit_intercept = fit_intercept\n self.a = a\n self.b = b\n \n \n def fit(self,X,y):\n '''\n Fits variational Bayesian Logistic Regression with local variational bound\n \n Parameters\n ----------\n X: array-like of size (n_samples, n_features)\n Matrix of explanatory variables\n \n y: array-like of size (n_samples,)\n Vector of dependent variables\n Returns\n -------\n self: object\n self\n '''\n # preprocess data\n X,y = check_X_y( X, y , dtype = np.float64)\n check_classification_targets(y)\n self.classes_ = np.unique(y)\n n_classes = len(self.classes_)\n \n # take into account bias term if required \n n_samples, n_features = X.shape\n n_features = n_features + int(self.fit_intercept)\n if self.fit_intercept:\n X = np.hstack( (np.ones([n_samples,1]),X))\n \n # handle multiclass problems using One-vs-Rest \n if n_classes < 2:\n raise ValueError(\"Need samples of at least 2 classes\")\n if n_classes > 2:\n self.coef_, self.sigma_ = [0]*n_classes,[0]*n_classes\n self.intercept_ = [0]*n_classes\n self.active_ = [0]*n_classes\n else:\n self.coef_, self.sigma_, self.intercept_ = [0],[0],[0]\n self.active_ = [0]\n \n # hyperparameters of precision for weights\n a = self.a + 0.5 * np.ones(n_features)\n b = self.b * np.ones(n_features)\n \n for i in range(len(self.coef_)):\n if n_classes == 2:\n pos_class = self.classes_[1]\n else:\n pos_class = self.classes_[i]\n mask = (y == pos_class)\n y_bin = np.ones(y.shape)\n y_bin[~mask] = 0\n coef_, sigma_, intercept_, active_ = self._fit(X,y_bin,a,b)\n self.coef_[i] = coef_\n self.intercept_[i] = intercept_\n self.sigma_[i] = sigma_\n self.active_[i] = active_\n \n self.coef_ = np.asarray(self.coef_)\n return self\n \n\n def predict_proba(self,x):\n '''\n Predicts probabilities of targets for test set\n \n Parameters\n ----------\n X: array-like of size [n_samples_test,n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n -------\n probs: numpy array of size [n_samples_test]\n Estimated probabilities of target classes\n '''\n scores = self.decision_function(x)\n if self.fit_intercept:\n x = np.hstack( (np.ones([x.shape[0],1]),x))\n var = [np.sum(np.dot(x[:,a],s)*x[:,a],axis = 1) for a,s in zip(self.active_,self.sigma_)]\n sigma = np.asarray(var)\n ks = 1. / ( 1. + np.pi*sigma / 8)**0.5\n probs = expit(scores.T*ks).T\n if probs.shape[1] == 1:\n probs = np.hstack([1 - probs, probs])\n else:\n probs /= np.reshape(np.sum(probs, axis = 1), (probs.shape[0],1))\n return probs\n\n \n def _fit(self,X,y,a,b):\n '''\n Fits single classifier for each class (for OVR framework)\n '''\n eps = 1 # default starting parameter for Jaakola Jordan bound\n w0 = np.zeros(X.shape[1])\n w = np.copy(w0)\n active = np.ones(X.shape[1], dtype = np.bool)\n XY = np.dot(X.T, y - 0.5)\n \n for i in range(self.n_iter):\n # In the E-step we update approximation of \n # posterior distribution q(w,alpha) = q(w)*q(alpha)\n\n # --------- update q(w) ------------------\n l = lam(eps)\n Xa = X[:,active]\n XYa = XY[active] #np.dot(Xa.T,(y-0.5))\n w[active],Ri = u,v = self._posterior_dist(Xa,l,a[active],b[active],XYa)\n \n # -------- update q(alpha) ---------------\n b[active] = self.b + 0.5*(w[active]**2 + np.sum(Ri**2,1))\n \n # -------- update eps ------------\n # In the M-step we update parameter eps which controls \n # accuracy of local variational approximation to lower bound\n XMX = np.dot(Xa,w[active])**2\n XSX = np.sum( np.dot(Xa,Ri.T)**2, axis = 1)\n eps = np.sqrt( XMX + XSX )\n \n # determine relevant vector as is described in Bishop & Tipping \n # (i.e. using mean of posterior distribution)\n active = np.abs(w) > self.prune_thresh\n \n # do not prune intercept & make sure there is at least one 'relevant feature'.\n # If only one relevant feature , then choose rv with largest posterior mean\n if self.fit_intercept:\n active[0] = True\n if np.sum(active[1:]) == 0:\n active[np.argmax(np.abs(w[1:]))] = True\n else:\n if np.sum(active) == 0:\n active[np.argmax(np.abs(w))] = True\n # all irrelevant features are forced to zero\n w[~active] = 0\n # check convergence\n if np.sum(abs(w-w0) > self.tol) == 0 or i==self.n_iter-1:\n break\n w0 = np.copy(w)\n # if only one relevant feature => terminate\n if np.sum(active) - 1*self.fit_intercept == 1:\n if X.shape[1] > 3 and self.prune_thresh > 1e-1:\n warnings.warn((\"Only one relevant feature found! it can be useful to decrease\"\n \"value for parameter prune_thresh\"))\n break\n \n l = lam(eps)\n Xa = X[:,active]\n XYa = np.dot(Xa.T,(y-0.5)) \n w[active] , sigma_ = self._posterior_dist(Xa,l,a[active],b[active],XYa,True)\n \n # separate intercept & coefficients\n intercept_ = 0\n if self.fit_intercept:\n intercept_ = w[0]\n coef_ = np.copy(w[1:])\n else:\n coef_ = w\n return coef_, sigma_ , intercept_, active\n\n\n def _posterior_dist(self,X,l,a,b,XY,full_covar = False):\n '''\n Finds gaussian approximation to posterior of coefficients\n '''\n sigma_inv = 2*np.dot(X.T*l,X)\n alpha_vec = a / b\n if self.fit_intercept:\n alpha_vec[0] = np.finfo(np.float64).eps\n np.fill_diagonal(sigma_inv, np.diag(sigma_inv) + alpha_vec)\n R = np.linalg.cholesky(sigma_inv)\n Z = solve_triangular(R,XY, lower = True)\n mean_ = solve_triangular(R.T,Z,lower = False)\n Ri = solve_triangular(R,np.eye(X.shape[1]), lower = True)\n if full_covar:\n sigma_ = np.dot(Ri.T,Ri)\n return mean_ , sigma_\n else:\n return mean_ , Ri\n\n\n" ]
[ [ "matplotlib.pyplot.yticks", "matplotlib.pyplot.imshow", "numpy.random.seed", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.grid", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.sqrt", "sklearn.cluster.KMeans", "numpy.random.randn", "matplotlib.pyplot.tight_layout", "numpy.arange", "numpy.sin", "scipy.linalg.eigh", "numpy.zeros", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure", "numpy.testing.assert_allclose", "sklearn.metrics.pairwise.rbf_kernel", "matplotlib.pyplot.show", "numpy.sum", "numpy.random.seed", "numpy.cos", "numpy.linalg.norm", "numpy.empty", "numpy.random.uniform", "numpy.vstack" ], [ "matplotlib.pyplot.tight_layout", "pandas.Series", "matplotlib.pyplot.scatter", "pandas.Categorical", "sklearn.datasets.load_iris", "pandas.DataFrame", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.argsort", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "torch.nn.Sequential", "torch.nn.ConvTranspose2d", "torch.nn.Conv2d", "torch.sum", "torch.argmin", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.functional.mse_loss", "torch.matmul", "torch.nn.LeakyReLU", "torch.nn.functional.one_hot", "torch.nn.ReLU" ], [ "matplotlib.pyplot.yticks", "matplotlib.pyplot.scatter", "numpy.arange", "scipy.stats.norm", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "matplotlib.pyplot.yticks", "numpy.power", "numpy.arange", "matplotlib.pyplot.axis", "matplotlib.pyplot.text", "matplotlib.pyplot.show", "matplotlib.pyplot.xticks" ], [ "pandas.set_option" ], [ "matplotlib.pyplot.spy", "matplotlib.pyplot.yticks", "matplotlib.pyplot.tight_layout", "numpy.arange", "scipy.io.loadmat", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show" ], [ "numpy.diag", "numpy.hstack", "numpy.square", "numpy.sqrt", "numpy.clip", "numpy.linalg.inv", "numpy.zeros", "numpy.sum" ], [ "numpy.maximum", "matplotlib.pyplot.title", "numpy.linspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.exp", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.diag", "numpy.dot", "numpy.sqrt", "numpy.asarray", "scipy.linalg.solve_triangular", "numpy.hstack", "sklearn.utils.check_X_y", "numpy.unique", "numpy.eye", "numpy.finfo", "numpy.copy", "numpy.zeros", "numpy.linalg.cholesky", "numpy.sum", "sklearn.utils.as_float_array", "numpy.abs", "scipy.special.expit", "sklearn.utils.multiclass.check_classification_targets", "numpy.ones", "numpy.average" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MatthiasDR96/industrial_robotics_simulator
[ "9039e7a581ce97c583c73294e9937664de90530b", "9039e7a581ce97c583c73294e9937664de90530b" ]
[ "src/Interpolator.py", "src/arms/ThreeDofArm.py" ]
[ "import numpy as np\nfrom sympy import *\n\n\ndef interpolate_cubic(p1, p2, k_traj, t):\n '''\n Computes a smooth cubic polynomail between 2 N-dimensional points\n Input:\n p1: Nx1 numpy array the first point\n p2: Nx1 numpy array the second point\n dp1: Nx1 numpy array of the required velocities at the first point\n dp2: Nx1 numpy array of the required velocities at the second point\n T: Scalar which denotes the time needed to traverse the polynomal from point 1 to point 2\n f: Scalar which denotes the frequency of sampling\n Returns:\n traj: (N+1) x (Txf) matrix with all interpolated position points for each axis + timesteps\n dtraj: (N+1) x (Txf) matrix with all interpolated velocities for each axis + timesteps\n ddtraj: (N+1) x (Txf) matrix with all interpolated accelerations for each axis + timesteps\n '''\n\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_third_degree_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef interpolate_quintic(p1, p2, k_traj, t):\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_fifth_degree_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef interpolate_septic(p1, p2, k_traj, t):\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_seventh_degree_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef interpolate_nonic(p1, p2, k_traj, t):\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_ninth_degree_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef interpolate_trapezoid(p1, p2, k_traj, t):\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_trapezoid_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef interpolate_minimum_jerk_derivative(p1, p2, k_traj, t):\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(k_traj) == int and (type(t) == float or type(t) == int)\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n dddtraj_list = []\n s, ds, dds, ddds = get_normalized_minimum_jerk_derivative_polynomial(k_traj)\n for i in range(len(p1)):\n traj_ = [((p2[i] - p1[i]) * s[j] + p1[i]) for j in range(len(s))]\n dtraj_ = np.divide([((p2[i] - p1[i]) * ds[j]) for j in range(len(ds))], t)\n ddtraj_ = np.divide([((p2[i] - p1[i]) * dds[j]) for j in range(len(dds))], t ** 2)\n dddtraj_ = np.divide([((p2[i] - p1[i]) * ddds[j]) for j in range(len(ddds))], t ** 3)\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n dddtraj_list.append(dddtraj_)\n\n tv = np.linspace(0, t, k_traj)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n dddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n dddtraj = np.asarray(dddtraj_list)\n\n return traj, dtraj, ddtraj, dddtraj\n\n\ndef get_normalized_first_degree_polynomial(k_traj):\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(k_traj):\n t = tau[i]\n stau[i] = t\n dstau_dtau[i] = 1\n ddstau_ddtau[i] = 0\n dddstau_dddtau[i] = 0\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_third_degree_polynomial(k_traj):\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(k_traj):\n t = tau[i]\n stau[i] = -2 * (t ** 3) + 3 * (t ** 2)\n dstau_dtau[i] = -6 * (t ** 2) + 6 * t\n ddstau_ddtau[i] = -12 * t + 6\n dddstau_dddtau[i] = -12\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_fifth_degree_polynomial(k_traj):\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(k_traj):\n t = tau[i]\n stau[i] = 6 * (t ** 5) - 15 * (t ** 4) + 10 * (t ** 3)\n dstau_dtau[i] = 30 * (t ** 4) - 60 * (t ** 3) + 30 * (t ** 2)\n ddstau_ddtau[i] = 120 * (t ** 3) - 180 * (t ** 2) + 60 * t\n dddstau_dddtau[i] = 360 * (t ** 2) - 360 * t + 60\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_seventh_degree_polynomial(k_traj):\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(k_traj):\n t = tau[i]\n stau[i] = -20 * (t ** 7) + 70 * (t ** 6) - 84 * (t ** 5) + 35 * (t ** 4)\n dstau_dtau[i] = -140 * (t ** 6) + 420 * (t ** 5) - 420 * (t ** 4) + 140 * (t ** 3)\n ddstau_ddtau[i] = -840 * (t ** 5) + 2100 * (t ** 4) - 1680 * (t ** 3) + 420 * (t ** 2)\n dddstau_dddtau[i] = -4200 * (t ** 4) + 8400 * (t ** 3) - 5040 * (t ** 2) + 840 * t\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_ninth_degree_polynomial(k_traj):\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(1, k_traj):\n t = tau[i]\n stau[i] = 70 * (t ** 9) - 315 * (t ** 8) + 540 * (t ** 7) - 420 * (t ** 6) + 126 * (t ** 5)\n dstau_dtau[i] = 630 * (t ** 8) - 2520 * (t ** 7) + 3780 * (t ** 6) - 2520 * (t ** 5) + 630 * (t ** 4)\n ddstau_ddtau[i] = 5040 * (t ** 7) - 17640 * (t ** 6) + 22680 * (t ** 5) - 12600 * (t ** 4) + 2520 * (t ** 3)\n dddstau_dddtau[i] = 35280 * (t ** 6) - 105840 * (t ** 5) + 113400 * (t ** 4) - 50400 * (t ** 3) + 7560 * (\n t ** 2)\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_trapezoid_polynomial(k_traj):\n t_acc = 1 / 10.\n t_ct = 1 - 2 * t_acc\n v_m = 1.0 / (t_acc + t_ct)\n x = t_acc\n\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n for i in range(k_traj):\n t = tau[i]\n if 0 <= t <= x:\n res = 0.5 * v_m * (t ** 2) / t_acc\n vel = v_m * t / t_acc\n elif x < t <= 1 - x:\n res = 0.5 * v_m * (t_acc ** 2) / t_acc + v_m * (t - t_acc)\n vel = v_m\n elif t > 1 - x:\n res = 0.5 * v_m * (t_acc ** 2) / t_acc + v_m * t_ct + v_m * (t - t_acc - t_ct) - 0.5 * v_m / t_acc * (\n t - t_acc - t_ct) ** 2\n vel = v_m - v_m / t_acc * (t - t_acc - t_ct)\n else:\n res = None\n vel = None\n stau[i] = res\n dstau_dtau[i] = vel\n\n for i in range(tau.size - 2):\n dstau_dtau[i] = (stau[i + 1] - stau[i]) / (tau[i + 1] - tau[i])\n\n for i in range(tau.size - 2):\n ddstau_ddtau[i] = (dstau_dtau[i + 1] - dstau_dtau[i]) / (tau[i + 1] - tau[i])\n\n for i in range(tau.size - 2):\n dddstau_dddtau[i] = (ddstau_ddtau[i + 1] - ddstau_ddtau[i]) / (tau[i + 1] - tau[i])\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_minimum_jerk_derivative_polynomial(k_traj):\n x = (1 - np.sqrt(0.5)) / 2\n\n tau = np.linspace(0, 1, k_traj)\n stau = np.linspace(0, 1, k_traj)\n dstau_dtau = np.linspace(0, 0, k_traj)\n ddstau_ddtau = np.linspace(0, 0, k_traj)\n dddstau_dddtau = np.linspace(0, 0, k_traj)\n\n res = None\n for i in range(k_traj - 1):\n t = tau[i]\n if 0 <= t <= x:\n res = 16 * (t ** 4)\n elif x < t <= 0.5:\n res = -16 * (t ** 4) + 128 * x * (t ** 3) - 192 * (x ** 2) * (t ** 2) + 128 * (x ** 3) * t - 32 * (x ** 4)\n elif 0.5 < t <= 1 - x:\n res = 1 + 16 * ((1 - t) ** 4) - 128 * x * ((1 - t) ** 3) + 192 * (x ** 2) * ((1 - t) ** 2) - 128 * (\n x ** 3) * (1 - t) + 32 * (x ** 4)\n elif 1 - x < t <= 1:\n res = 1 - 16 * (1 - t) ** 4\n stau[i] = res\n\n for i in range(tau.size - 2):\n dstau_dtau[i] = (stau[i + 1] - stau[i]) / (tau[i + 1] - tau[i])\n\n for i in range(tau.size - 2):\n ddstau_ddtau[i] = (dstau_dtau[i + 1] - dstau_dtau[i]) / (tau[i + 1] - tau[i])\n\n for i in range(tau.size - 2):\n dddstau_dddtau[i] = (ddstau_ddtau[i + 1] - ddstau_ddtau[i]) / (tau[i + 1] - tau[i])\n\n return stau, dstau_dtau, ddstau_ddtau, dddstau_dddtau\n\n\ndef get_normalized_cubic_polynomial_coefficients():\n # Kinematic equations for a cubic polynomial\n x0 = [1, 0, 0, 0]\n xt = [1, 1, pow(1, 2), pow(1, 3)]\n v0 = [0, 1, 0, 0]\n vt = [0, 1, 2 * 1, 3 * pow(1, 2)]\n\n # Solve polynomial coefficients\n a = np.array([x0, xt, v0, vt], dtype='float')\n b = np.array([[0], [1], [0], [0]], dtype='float')\n polynomial = np.linalg.solve(a, b)\n return polynomial\n\n\ndef get_normalized_quintic_polynomial_coefficients():\n # Kinematic equations for a cubic polynomial\n x0 = [1, 0, 0, 0, 0, 0]\n xt = [1, 1, pow(1, 2), pow(1, 3), pow(1, 4), pow(1, 5)]\n v0 = [0, 1, 0, 0, 0, 0]\n vt = [0, 1, 2 * 1, 3 * pow(1, 2), 4 * pow(1, 3), 5 * pow(1, 4)]\n a0 = [0, 0, 2, 0, 0, 0]\n at = [0, 0, 2, 6 * 1, 12 * pow(1, 2), 20 * pow(1, 3)]\n\n # Solve polynomial coefficients\n a = np.array([x0, xt, v0, vt, a0, at], dtype='float')\n b = np.array([[0], [1], [0], [0], [0], [0]], dtype='float')\n polynomial = np.linalg.solve(a, b)\n return polynomial\n\n\ndef get_normalized_septic_polynomial_coefficients():\n # Kinematic equations for a cubic polynomial\n x0 = [1, 0, 0, 0, 0, 0, 0, 0]\n xt = [1, 1, pow(1, 2), pow(1, 3), pow(1, 4), pow(1, 5), pow(1, 6), pow(1, 7)]\n v0 = [0, 1, 0, 0, 0, 0, 0, 0]\n vt = [0, 1, 2 * 1, 3 * pow(1, 2), 4 * pow(1, 3), 5 * pow(1, 4), 6 * pow(1, 5), 7 * pow(1, 6)]\n a0 = [0, 0, 2, 0, 0, 0, 0, 0]\n at = [0, 0, 2, 6 * 1, 12 * pow(1, 2), 20 * pow(1, 3), 30 * pow(1, 4), 42 * pow(1, 5)]\n j0 = [0, 0, 0, 6, 0, 0, 0, 0]\n jt = [0, 0, 0, 6, 24 * 1, 60 * pow(1, 2), 120 * pow(1, 3), 210 * pow(1, 4)]\n\n # Solve polynomial coefficients\n a = np.array([x0, xt, v0, vt, a0, at, j0, jt], dtype='float')\n b = np.array([[0], [1], [0], [0], [0], [0], [0], [0]], dtype='float')\n polynomial = np.linalg.solve(a, b)\n return polynomial\n\n\ndef get_normalized_nonic_polynomial_coefficients():\n # Kinematic equations for a cubic polynomial\n x0 = [1, 0, 0, 0, 0, 0]\n xt = [1, 1, pow(1, 2), pow(1, 3), pow(1, 4), pow(1, 5)]\n v0 = [0, 1, 0, 0, 0, 0]\n vt = [0, 1, 2 * 1, 3 * pow(1, 2), 4 * pow(1, 3), 5 * pow(1, 4)]\n a0 = [0, 0, 2, 0, 0, 0]\n at = [0, 0, 2, 6 * 1, 12 * pow(1, 2), 20 * pow(1, 3)]\n j0 = [0, 0, 0, 6, 0, 0, 0, 0]\n jt = [0, 0, 0, 6, 24 * 1, 60 * pow(1, 2), 120 * pow(1, 3), 210 * pow(1, 4)]\n\n # Solve polynomial coefficients\n a = np.array([x0, xt, v0, vt, a0, at, j0, jt], dtype='float')\n b = np.array([[0], [1], [0], [0], [0], [0], [0], [0]], dtype='float')\n polynomial = np.linalg.solve(a, b)\n return polynomial\n\n\ndef interpolate_quint_2(p1, p2, dp1, dp2, ddp1, ddp2, k_traj, T):\n '''\n Computes a smooth quintic polynomial between 2 N-dimensional points\n Input:\n p1: Nx1 numpy array the first point\n p2: Nx1 numpy array the second point\n dp1: Nx1 numpy array of the required velocities at the first point\n dp2: Nx1 numpy array of the required velocities at the second point\n ddp1: Nx1 numpy array of the required accelerations the first point\n ddp2: Nx1 numpy array of the required accelerations the second point\n T: Scalar which denotes the time needed to traverse the polynomal from point 1 to point 2\n f: Scalar which denotes the frequency of sampling\n Returns:\n traj: (N+1) x (Txf) matrix with all interpolated position points for each axis + timesteps\n dtraj: (N+1) x (Txf) matrix with all interpolated velocities for each axis + timesteps\n ddtraj: (N+1) x (Txf) matrix with all interpolated accelerations for each axis + timesteps\n '''\n\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(dp1) == np.ndarray and type(dp2) == np.ndarray\n assert type(ddp1) == np.ndarray and type(ddp2) == np.ndarray\n assert type(k_traj) == int and (type(T) == float or type(T) == int)\n\n # Kinematic equations for a quintic polynomial\n x0 = [1, 0, 0, 0, 0, 0]\n xT = [1, T, pow(T, 2), pow(T, 3), pow(T, 4), pow(T, 5)]\n v0 = [0, 1, 0, 0, 0, 0]\n vT = [0, 1, 2 * T, 3 * pow(T, 2), 4 * pow(T, 3), 5 * pow(T, 4)]\n a0 = [0, 0, 2, 0, 0, 0]\n aT = [0, 0, 2, 6 * T, 12 * pow(T, 2), 20 * pow(T, 3)]\n\n # Kinematic matrix\n A = np.array([x0, xT, v0, vT, a0, aT], dtype='float')\n\n # Interpolate\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n t = Symbol('t')\n tv = np.linspace(0, T, k_traj)\n for i in range(len(p1)):\n B = np.array([[p1[i]], [p2[i]], [dp1[i]], [dp2[i]], [ddp1[i]], [ddp2[i]]], dtype='float')\n x = np.linalg.solve(A, B)\n traj = x[0, 0] + x[1, 0] * t + x[2, 0] * pow(t, 2) + x[3, 0] * pow(t, 3) + x[4, 0] * pow(t, 4) + x[\n 5, 0] * pow(t, 5)\n dtraj = x[1, 0] + 2 * x[2, 0] * t + 3 * x[3, 0] * pow(t, 2) + 4 * x[4, 0] * pow(t, 3) + 5 * x[\n 5, 0] * pow(t, 4)\n ddtraj = 2 * x[2, 0] + 6 * x[3, 0] * t + 12 * x[4, 0] * pow(t, 2) + 20 * x[5, 0] * pow(t, 3)\n traj_ = [traj.subs(t, tv_) for tv_ in tv]\n dtraj_ = [dtraj.subs(t, tv_) for tv_ in tv]\n ddtraj_ = [ddtraj.subs(t, tv_) for tv_ in tv]\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n traj = np.asarray(traj_list)\n dtraj = np.asarray(dtraj_list)\n ddtraj = np.asarray(ddtraj_list)\n\n return traj, dtraj, ddtraj\n\n\ndef interpolate_cubic_2(p1, p2, k_traj, T, dp1=np.zeros((6, 1)), dp2=np.zeros((6, 1))):\n '''\n Computes a smooth cubic polynomal between 2 N-dimensional points\n Input:\n p1: Nx1 numpy array the first point\n p2: Nx1 numpy array the second point\n dp1: Nx1 numpy array of the required velocities at the first point\n dp2: Nx1 numpy array of the required velocities at the second point\n T: Scalar which denotes the time needed to traverse the polynomal from point 1 to point 2\n f: Scalar which denotes the frequency of sampling\n Returns:\n traj: (N+1) x (Txf) matrix with all interpolated position points for each axis + timesteps\n dtraj: (N+1) x (Txf) matrix with all interpolated velocities for each axis + timesteps\n ddtraj: (N+1) x (Txf) matrix with all interpolated accelerations for each axis + timesteps\n '''\n\n assert type(p1) == np.ndarray and type(p2) == np.ndarray\n assert type(dp1) == np.ndarray and type(dp2) == np.ndarray\n assert type(k_traj) == int and (type(T) == float or type(T) == int)\n\n # Kinematic equations for a cubic polynomial\n x0 = [1, 0, 0, 0]\n xT = [1, T, pow(T, 2), pow(T, 3)]\n v0 = [0, 1, 0, 0]\n vT = [0, 1, 2 * T, 3 * pow(T, 2)]\n\n # Kinematic matrix\n A = np.array([x0, xT, v0, vT], dtype='float')\n\n traj_list = []\n dtraj_list = []\n ddtraj_list = []\n t = Symbol('t')\n tv = np.linspace(0, T, k_traj)\n for i in range(len(p1)):\n B = np.array([[p1[i]], [p2[i]], [dp1[i]], [dp2[i]]], dtype='float')\n x = np.linalg.solve(A, B)\n traj = x[0, 0] + x[1, 0] * t + x[2, 0] * pow(t, 2) + x[3, 0] * pow(t, 3)\n dtraj = x[1, 0] + 2 * x[2, 0] * t + 3 * x[3, 0] * pow(t, 2)\n ddtraj = 2 * x[2, 0] + 6 * x[3, 0] * t\n traj_ = [traj.subs(t, tv_) for tv_ in tv]\n dtraj_ = [dtraj.subs(t, tv_) for tv_ in tv]\n ddtraj_ = [ddtraj.subs(t, tv_) for tv_ in tv]\n traj_list.append(traj_)\n dtraj_list.append(dtraj_)\n ddtraj_list.append(ddtraj_)\n traj_list.append(tv)\n dtraj_list.append(tv)\n ddtraj_list.append(tv)\n traj = np.array(traj_list)\n dtraj = np.array(dtraj_list)\n ddtraj = np.array(ddtraj_list)\n\n return traj, dtraj, ddtraj\n\n\ndef interpolate_viapoints(p, v1, vn, k_traj, t):\n '''\n Computes a smooth cubic polynomal between M N-dimensional points\n Input:\n p: MxN numpy array containing all points\n v1: Nx1 numpy array of the required velocities at the first point\n vn: Nx1 numpy array of the required velocities at the last point\n t: Mx1 numpy array of the timesteps at which the points should be reached\n f: Scalar which denotes the frequency of sampling\n Returns:\n traj: (N+1) x (Txf) matrix with all interpolated position points for each axis + timesteps\n dtraj: (N+1) x (Txf) matrix with all interpolated velocities for each axis + timesteps\n ddtraj: (N+1) x (Txf) matrix with all interpolated accelerations for each axis + timesteps\n '''\n\n assert type(p) == np.ndarray and type(k_traj) == int\n\n # Compute time interval matrix\n h = list(np.zeros((len(t) - 1, 1)))\n for i in range(len(t) - 1):\n h[i] = t[i + 1] - t[i]\n\n # Compute A(h) matrix\n A = np.zeros((len(h) - 1, len(h) - 1))\n for i in range(len(h) - 1):\n for j in range(len(h) - 1):\n if i == j:\n A[i][j] = 2 * (h[i] + h[i + 1])\n if i == j + 1:\n A[i][j] = h[i + 1]\n if j == i + 1:\n A[i][j] = h[i]\n\n # Compute known B(p0,p1,h,v1,vn) matrix\n B = np.zeros((len(h) - 1, len(p[0])))\n for i in range(len(h) - 1):\n B[i] = (3 / (h[i] * h[i + 1])) * (\n pow(h[i], 2) * (np.subtract(p[i + 2], p[i + 1])) + pow(h[i + 1], 2) * (np.subtract(p[i + 1], p[i])))\n B[0] = B[0] - np.dot(h[1], v1)\n B[-1] = B[-1] - np.dot(h[-2], vn)\n\n # Solve for all unknown velocities of intermediate knots\n x = np.linalg.solve(A, B)\n vel = [v1.copy()]\n [vel.append(x[i]) for i in range(len(x))]\n vel.append(vn.copy())\n\n # Compute N-1 polynomials using computed velocities\n traj = [[0], [0], [0], [0], [0], [0], [0]]\n dtraj = [[0], [0], [0], [0], [0], [0], [0]]\n ddtraj = [[0], [0], [0], [0], [0], [0], [0]]\n for i in range(len(p) - 1):\n traj_, dtraj_, ddtraj_ = interpolate_cubic_2(p[i], p[i + 1], k_traj, float(h[i]), vel[i], vel[i + 1])\n for j in range(len(traj) - 1):\n traj[j].extend(traj_[j])\n dtraj[j].extend(dtraj_[j])\n ddtraj[j].extend(ddtraj_[j])\n traj[-1].extend(traj_[-1] + traj[-1][-1])\n dtraj[-1].extend(dtraj_[-1] + dtraj[-1][-1])\n ddtraj[-1].extend(ddtraj_[-1] + ddtraj[-1][-1])\n traj = np.asarray(np.delete(traj, 0, 1))\n dtraj = np.asarray(np.delete(traj, 0, 1))\n ddtraj = np.asarray(np.delete(traj, 0, 1))\n\n return traj, dtraj, ddtraj\n", "from math import *\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.optimize\n\n\"\"\" A class to calculate all the kinematics and dynamics\n for a three link arm. Also stores the mass of each of the links.\"\"\"\n\n\nclass ThreeDofArm:\n\n def __init__(self, dt=1e-5, singularity_threshold=0.005):\n\n # Arm params\n self.DOF = 3\n self.dt = dt\n self.singularity_threshold = singularity_threshold\n self.params = {\"mass\": [1., 1., 1.], \"damping\": [0.1, 0.1, 0.1], \"stiffness\": [0], \"inertia\": [1., 1., 1.],\n \"length\": [1., 1., 1.], \"center_of_gravity\": [1.0, 0.6, 0.45], \"gravity\": 9.81}\n\n # Create mass matrices at COM for each link\n self.M1 = np.zeros((6, 6))\n self.M2 = np.zeros((6, 6))\n self.M3 = np.zeros((6, 6))\n self.M1[0:3, 0:3] = np.eye(3) * self.params[\"mass\"][0]\n self.M1[5, 5] = self.params[\"inertia\"][0]\n self.M2[0:3, 0:3] = np.eye(3) * self.params[\"mass\"][1]\n self.M2[5, 5] = self.params[\"inertia\"][1]\n self.M3[0:3, 0:3] = np.eye(3) * self.params[\"mass\"][2]\n self.M3[5, 5] = self.params[\"inertia\"][2]\n\n # Arm state\n self.q = np.array([[0.0], [0.0], [0.0]])\n self.dq = np.array([[0.0], [0.0], [0.0]])\n\n # Arm state\n self.tau_limit = 20 # Nm\n\n # Simulation time\n self.time_elapsed = 0.0\n\n # Rest angles (for null space control)\n self.rest_angles = np.array([[pi / 4], [-pi / 4], [-pi / 4]])\n\n def __str__(self):\n string = \"Three degree of freedom arm:\\n\"\n for i in range(self.DOF):\n string += \"\\tLink \" + str(i) + \": \\n\\t\\tMass: \" + str(self.params[\"mass\"][0]) \\\n + \"\\n\\t\\tLength: \" + str(self.params[\"length\"][0]) \\\n + \"\\n\\t\\tInertia: \" + str(self.params[\"inertia\"][0]) \\\n + \"\\n\\t\\tCOM: \" + str(self.params[\"center_of_gravity\"][0]) + \"\\n\"\n return string\n\n def set_q_init(self, q_init):\n assert len(q_init) == self.DOF\n self.q = q_init\n\n def plot(self, q=None):\n fig = plt.figure()\n ax1 = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-4, 4), ylim=(-4, 4))\n ax1.grid()\n ax1.set_xlabel(\"X\")\n ax1.set_ylabel(\"Y\")\n line1, = ax1.plot([], [], 'o-', lw=2)\n if not q is None:\n self.q = q\n [x, y] = self.position()\n line1.set_data(x, y)\n\n def position(self, q=None):\n if q is None:\n q = self.q\n x1 = self.params[\"length\"][0] * np.cos(self.q[0])\n y1 = self.params[\"length\"][0] * np.sin(self.q[0])\n x2 = self.params[\"length\"][1] * np.cos(self.q[0] + self.q[1])\n y2 = self.params[\"length\"][1] * np.sin(self.q[0] + self.q[1])\n x3 = self.params[\"length\"][2] * np.cos(self.q[0] + self.q[1] + self.q[2])\n y3 = self.params[\"length\"][2] * np.sin(self.q[0] + self.q[1] + self.q[2])\n x = np.cumsum([0, x1, x2, x3])\n y = np.cumsum([0, y1, y2, y3])\n return x, y\n\n def reset(self, q, dq):\n assert len(q) == self.DOF\n assert len(dq) == self.DOF\n self.q = q\n self.dq = dq\n self.time_elapsed = 0.0\n\n def forward_kinematics(self, q):\n assert len(q) == self.DOF\n T_01 = np.resize([[cos(q[0]), -sin(q[0]), 0, cos(q[0]) * self.params[\"length\"][0]],\n [sin(q[0]), cos(q[0]), 0, sin(q[0]) * self.params[\"length\"][0]],\n [0, 0, 1, 0],\n [0, 0, 0, 1]], (4, 4))\n T_12 = [[cos(q[1]), -sin(q[1]), 0, cos(q[1]) * self.params[\"length\"][1]],\n [sin(q[1]), cos(q[1]), 0, sin(q[1]) * self.params[\"length\"][1]],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]\n T_23 = [[cos(q[2]), -sin(q[2]), 0, cos(q[2]) * self.params[\"length\"][2]],\n [sin(q[2]), cos(q[2]), 0, sin(q[2]) * self.params[\"length\"][2]],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]\n T = np.dot(T_01, np.dot(T_12, T_23))\n fk = np.dot(T, np.resize([0, 0, 0, 1], (4, 1)))\n return fk[0:2]\n\n def inverse_kinematics(self, xy, q_init=None):\n\n if q_init is None:\n q_init = self.q\n\n def distance_to_target(q, xy):\n fxy = self.forward_kinematics(q)\n return np.sqrt((fxy[0] - xy[0]) ** 2 + (fxy[1] - xy[1]) ** 2)\n\n return scipy.optimize.minimize(fun=distance_to_target, x0=q_init, args=([xy[0], xy[1]]))['x']\n\n def forward_dynamics(self, q, dq, tau_=None):\n assert len(q) == self.DOF\n assert len(dq) == self.DOF\n if tau_ is None:\n tau_ = [[0.0], [0.0], [0.0]]\n assert np.shape(tau_) == (self.DOF, 1)\n inert = self.inertia()\n grav = self.gravity()\n damp = self.damping(dq)\n ddtheta = np.dot(np.linalg.inv(inert), (tau_ - grav - damp))\n return ddtheta\n\n def inverse_dynamics(self, q, dq, ddq):\n inert = self.inertia()\n grav = self.gravity()\n damp = self.damping(dq)\n tau_ = np.dot(inert, np.resize(ddq, (self.DOF, 1))) + grav + damp\n return np.reshape(tau_, (self.DOF, 1))\n\n def inertia(self, q=None):\n if q is None:\n q = self.q\n jac1 = self.generate_jacobian_com1(q)\n jac2 = self.generate_jacobian_com2(q)\n jac3 = self.generate_jacobian_com3(q)\n Mq = (np.dot(jac1.T, np.dot(self.M1, jac1)) +\n np.dot(jac2.T, np.dot(self.M2, jac2)) +\n np.dot(jac3.T, np.dot(self.M3, jac3)))\n return Mq\n\n def gravity(self, q=None):\n if q is None:\n q = self.q\n jac1 = self.generate_jacobian_com1(q)\n jac2 = self.generate_jacobian_com2(q)\n jac3 = self.generate_jacobian_com3(q)\n gr = np.dot(jac1.T, [0, self.params['gravity'], 0, 0, 0, 0]) + \\\n np.dot(jac2.T, [0, self.params['gravity'], 0, 0, 0, 0]) + \\\n np.dot(jac3.T, [0, self.params['gravity'], 0, 0, 0, 0])\n return np.resize(gr, (self.DOF, 1))\n\n def damping(self, dq):\n return np.resize([[self.params['damping'][0] * dq[0]], [self.params['damping'][1] * dq[1]],\n [self.params['damping'][2] * dq[2]]], (self.DOF, 1))\n\n def generate_jacobian_com1(self, q):\n jac = np.zeros((6, self.DOF))\n jac[0, 0] = self.params[\"center_of_gravity\"][0] * -np.sin(q[0])\n jac[1, 0] = self.params[\"center_of_gravity\"][0] * np.cos(q[0])\n jac[5, 0] = 1.0\n return jac\n\n def generate_jacobian_com2(self, q):\n q0 = q[0]\n q01 = q[0] + q[1]\n jac = np.zeros((6, 3))\n jac[0, 1] = self.params[\"center_of_gravity\"][1] * -np.sin(q01)\n jac[1, 1] = self.params[\"center_of_gravity\"][1] * np.cos(q01)\n jac[5, 1] = 1.0\n jac[0, 0] = self.params[\"center_of_gravity\"][0] * -np.sin(q0) + jac[0, 1]\n jac[1, 0] = self.params[\"center_of_gravity\"][0] * np.cos(q0) + jac[1, 1]\n jac[5, 0] = 1.0\n return jac\n\n def generate_jacobian_com3(self, q):\n q0 = q[0]\n q01 = q[0] + q[1]\n q012 = q[0] + q[1] + q[2]\n jac = np.zeros((6, self.DOF))\n jac[0, 2] = self.params[\"center_of_gravity\"][2] * -np.sin(q012)\n jac[1, 2] = self.params[\"center_of_gravity\"][2] * np.cos(q012)\n jac[5, 2] = 1.0\n jac[0, 1] = self.params[\"center_of_gravity\"][1] * -np.sin(q01) + jac[0, 2]\n jac[1, 1] = self.params[\"center_of_gravity\"][1] * np.cos(q01) + jac[1, 2]\n jac[5, 1] = 1.0\n jac[0, 0] = self.params[\"center_of_gravity\"][0] * -np.sin(q0) + jac[0, 1]\n jac[1, 0] = self.params[\"center_of_gravity\"][0] * np.cos(q0) + jac[1, 1]\n jac[5, 0] = 1.0\n return jac\n\n def generate_jacobian_ee(self, q):\n q0 = q[0]\n q01 = q[0] + q[1]\n q012 = q[0] + q[1] + q[2]\n jac = np.zeros((6, self.DOF))\n jac[0, 2] = self.params[\"center_of_gravity\"][2] * -np.sin(q012)\n jac[1, 2] = self.params[\"center_of_gravity\"][2] * np.cos(q012)\n jac[5, 2] = 1.0\n jac[0, 1] = self.params[\"center_of_gravity\"][1] * -np.sin(q01) + jac[0, 2]\n jac[1, 1] = self.params[\"center_of_gravity\"][1] * np.cos(q01) + jac[1, 2]\n jac[5, 1] = 1.0\n jac[0, 0] = self.params[\"center_of_gravity\"][0] * -np.sin(q0) + jac[0, 1]\n jac[1, 0] = self.params[\"center_of_gravity\"][0] * np.cos(q0) + jac[1, 1]\n jac[5, 0] = 1.0\n return jac\n\n def gen_Mx(self):\n\n # Get inertia in joint space\n Mq = self.inertia()\n\n # Get ee jacobian\n jac = self.generate_jacobian_ee(self.q)\n\n # Get inverse operational inertia matrix\n Mx_inv = np.dot(jac, np.dot(np.linalg.inv(Mq), jac.T))\n\n # Handle singularities\n if abs(np.linalg.det(np.dot(jac, jac.T))) > .005 ** 2:\n Mx = np.linalg.inv(Mx_inv)\n else:\n # In the case that the robot is entering near singularity\n u, s, v = np.linalg.svd(Mx_inv)\n for i in range(len(s)):\n if s[i] < self.singularity_threshold:\n s[i] = 0\n else:\n s[i] = 1.0 / float(s[i])\n Mx = np.dot(v.T, np.dot(np.diag(s), u.T))\n\n return Mx\n\n def step(self, tau_, delta_t):\n\n # Compute accelerations\n ddq = self.forward_dynamics(self.q, self.dq, tau_)\n\n # Compute velocity\n self.dq += ddq * delta_t\n\n # Compute position\n self.q += self.dq * delta_t\n\n # Get new state\n self.time_elapsed += delta_t\n" ]
[ [ "numpy.dot", "numpy.linalg.solve", "numpy.sqrt", "numpy.linspace", "numpy.asarray", "numpy.subtract", "numpy.delete", "numpy.array", "numpy.zeros" ], [ "numpy.diag", "numpy.dot", "numpy.linalg.svd", "numpy.resize", "numpy.sqrt", "numpy.reshape", "numpy.linalg.inv", "numpy.eye", "numpy.cumsum", "numpy.cos", "numpy.sin", "numpy.shape", "numpy.array", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AwhLorraine/mshoot
[ "d6981fa37c55da0457ac0371f9850743858a3543", "d6981fa37c55da0457ac0371f9850743858a3543" ]
[ "test/test_mpc.py", "examples/tutorial/tutorial.py" ]
[ "import unittest\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import StateSpace\nimport matplotlib.pyplot as plt\n\nimport mshoot\n\n\ndef cfun(xdf, ydf):\n \"\"\"\n :param ydf: DataFrame, model states\n :param ydf: DataFrame, model outputs\n :return: float\n \"\"\"\n qout = ydf['qout'].values\n c = np.sum(qout ** 2) / qout.size\n return c\n\n\nclass TestMPC(unittest.TestCase):\n\n def setUp(self):\n fmupath = os.path.join('resources', 'fmus', 'R1C1', 'R1C1.fmu')\n parameters = {'C': 1e6, 'R': 0.01}\n self.model = mshoot.SimFMU(\n fmupath,\n outputs=['qout', 'Tr'],\n states=['heatCapacitor.T'],\n parameters=parameters,\n verbose=False)\n\n def tearDown(self):\n pass\n\n def test_mpc(self):\n # Inputs\n t = np.arange(0, 3600 * 10, 3600)\n inp = pd.DataFrame(index=pd.Index(t, name='time'), columns=['q', 'Tout'])\n inp['q'] = np.full(t.size, 0)\n inp['Tout'] = np.full(t.size, 273.15)\n\n # Bounds\n ubounds = [(0., 4000.)]\n xbounds = [(293.15, 296.15)]\n\n # Initial state\n x0 = [293.65]\n\n # Optimization\n mpc = mshoot.MPCEmulation(emumod=self.model, cfun=cfun)\n\n u, xctr, xemu, yemu, uhist = mpc.optimize(\n model=self.model,\n inp_ctr=inp.copy(),\n inp_emu=inp.copy(),\n free=['q'],\n ubounds=ubounds,\n xbounds=xbounds,\n x0=x0,\n ynominal=[4000., 293.15],\n step=1,\n horizon=3\n )\n\n # ax = u.plot(title='u')\n # ax.set_ylim(0, 4000)\n # ax = xemu.plot(title='xemu')\n # ax.set_ylim(292.15, 296.15)\n # plt.show()\n\n # Assert the solution is correct\n self.assertLess(abs(xemu['heatCapacitor.T'].iloc[-1] - 293.15), 0.3) # Ideally, should be even closer\n\n # Validate emulation with optimized control\n inp['q'] = u['q']\n yvld, xvld = self.model.simulate(inp, x0)\n\n # self.assertTrue(((yvld - yemu).abs() < 1e-3).all().all()) # Might not be true for FMUs *\n self.assertTrue(((xvld - xemu).abs() < 1e-3).all().all()) # Might not be true for FMUs *\n # * FMU results might be shifted in time by one time step.\n # The reason is unknown, but FMU- or pyFMI-specific.\n\n def test_mpc_inp_clb(self):\n # Inputs\n t = np.arange(0, 3600 * 10, 3600)\n inp = pd.DataFrame(index=pd.Index(t, name='time'), columns=['q', 'Tout'])\n inp['q'] = np.full(t.size, 0)\n inp['Tout'] = np.full(t.size, 273.15)\n\n # Bounds\n ubounds = [(0., 4000.)]\n xbounds = [(293.15, 296.15)]\n\n # Initial state\n x0 = [293.65]\n\n # Input callback function\n def inp_clb(index):\n return inp.loc[index]\n\n # Optimization\n mpc = mshoot.MPCEmulation(emumod=self.model, cfun=cfun)\n\n u, xctr, xemu, yemu, uhist = mpc.optimize(\n model=self.model,\n inp_ctr=None,\n inp_clb=inp_clb,\n inp_emu=inp.copy(),\n free=['q'],\n ubounds=ubounds,\n xbounds=xbounds,\n x0=x0,\n ynominal=[4000., 293.15],\n step=1,\n horizon=3\n )\n\n # Assert the solution is correct\n self.assertLess(abs(xemu['heatCapacitor.T'].iloc[-1] - 293.15), 0.3) # Ideally, should be even closer\n\n # Validate emulation with optimized control\n inp['q'] = u['q']\n yvld, xvld = self.model.simulate(inp, x0)\n\n # self.assertTrue(((yvld - yemu).abs() < 1e-3).all().all()) # Might not be true for FMUs *\n self.assertTrue(((xvld - xemu).abs() < 1e-3).all().all()) # Might not be true for FMUs *\n # * FMU results might be shifted in time by one time step.\n # The reason is unknown, but FMU- or pyFMI-specific.\n\n # def test_2_inputs(self):\n # \"\"\"THE SOLVER HAS PROBLEMS WITH GETTING THE RIGHT SOLUTION. (?)\"\"\"\n # # Inputs\n # t = np.arange(0, 3600 * 10, 3600)\n # inp = pd.DataFrame(index=pd.Index(t, name='time'), columns=['q', 'Tout'])\n # inp['q'] = np.full(t.size, 0)\n # inp['Tout'] = np.full(t.size, 273.15)\n\n # # Bounds\n # ubounds = [(0., 10000.), (272.15, 275.)] # <-- Solver should try to yield Tout = 275\n # xbounds = [(293.15, 296.15)]\n\n # # Initial state\n # x0 = [293.65]\n\n # # Optimization\n # mpc = mshoot.MPCEmulation(emumod=self.model, cfun=cfun)\n\n # u, xctr, xemu, yemu, uhist = mpc.optimize(\n # model=self.model,\n # inp=inp,\n # free=['q', 'Tout'],\n # ubounds=ubounds,\n # xbounds=xbounds,\n # x0=x0,\n # unominal=[4000., 273.15],\n # ynominal=[4000., 293.15],\n # step=1,\n # horizon=4\n # )\n\n # ax = u.plot(title='u', subplots=True)\n # ax = xemu.plot(title='xemu')\n # plt.show()\n\n # # Assert the solution is correct\n # self.assertLess(abs(xemu['heatCapacitor.T'].iloc[-1] - 293.15), 0.01)\n\n # # Validate emulation with optimized control\n # inp['q'] = u['q']\n # yvld, xvld = self.model.simulate(inp, x0)\n\n # # self.assertTrue((yvld - yemu < 1e-3).all().all()) # Might not be true for FMUs *\n # # self.assertTrue((xvld - xemu < 1e-3).all().all()) # Might not be true for FMUs *\n # # * FMU results might be shifted in time by one time step.\n # # The reason is unknown, but FMU- or pyFMI-specific.\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n", "import os\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mshoot\n\nfmupath = os.path.join('examples', 'tutorial', 'modelica', 'R3C3.fmu')\n\n# 1) Emulation model\nmodel_emu = mshoot.SimFMU(\n fmupath,\n outputs=['y', 'u1_y'],\n states=['heatCapacitor1.T', 'heatCapacitor2.T', 'heatCapacitor3.T'],\n parameters={'C1': 75000, 'C2': 100000, 'C3': 50000, 'R1': 0.01, 'R2': 0.01, 'R3': 0.01})\n\n# 2) Control model\nmodel_ctr = mshoot.SimFMU(\n fmupath,\n outputs=['y', 'u1_y'],\n states=['heatCapacitor1.T', 'heatCapacitor2.T', 'heatCapacitor3.T'],\n parameters={'C1': 75000, 'C2': 100000, 'C3': 50000, 'R1': 0.01, 'R2': 0.01, 'R3': 0.01})\n\n# 3) Cost function\ndef cfun(xdf, ydf):\n cost = (ydf['u1_y'] ** 2).sum()\n return cost\n\n# 4) Define inputs (48 hours emulation, 1h step)\nt = np.arange(0, 48. * 3600., 3600.)\nu1 = np.zeros(48)\nu2 = np.sin(t / 86400. * 2. * np.pi) * 1000. + np.random.rand(48) * 1000. - 500. # Noisy sinusoid\n\ninp = pd.DataFrame(index = pd.Index(t, name = 'time'))\ninp['u1'] = u1\ninp['u2'] = u2\n\ninp.plot()\nplt.show()\n\n# 5) Define bounds\nTlo = np.where((t > 86400 / 2) & (t < 86400 * 1.5), 273.15 + 23, 273.15 + 17)\nThi = 273.15 + 25\n\n# 6) Instantiate MPCEmulation\nmpc = mshoot.MPCEmulation(model_emu, cfun)\n\n# 7) Optimize\nu, xctr, xemu, yemu, u_hist = mpc.optimize(\n model = model_ctr,\n inp_ctr = inp,\n inp_emu = inp,\n free = ['u1'],\n ubounds = [(-1000, 1000)],\n xbounds = [(273.15, 333.15), (273.15, 333.15), (Tlo, Thi)],\n x0 = [293.15, 293.15, 293.15],\n maxiter = 20,\n ynominal = [293.15, 1000.],\n step = 1,\n horizon = 3\n)\n\n# 8) Plot some results\nax1 = xemu.plot()\nax1.plot(xemu.index, Tlo, color = 'black')\nax1.plot(xemu.index, np.full(48, Thi), color = 'black')\n\nax2 = u.plot()\nax2.plot(u.index, u2, color = 'red')\n\nplt.show()\n" ]
[ [ "numpy.arange", "pandas.Index", "numpy.sum", "numpy.full" ], [ "numpy.arange", "pandas.Index", "numpy.full", "numpy.sin", "numpy.random.rand", "matplotlib.pyplot.show", "numpy.zeros", "numpy.where" ] ]
[ { "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": [] }, { "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": [] } ]
edges-collab/edges-cal
[ "9b7b28f71e1aa5347f901af38ef3bc0d28766e21" ]
[ "src/edges_cal/cal_coefficients.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nThe main user-facing module of ``edges-cal``.\n\nThis module contains wrappers around lower-level functions in other modules, providing\na one-stop interface for everything related to calibration.\n\"\"\"\nfrom __future__ import annotations\n\nimport attr\nimport h5py\nimport numpy as np\nimport tempfile\nimport warnings\nimport yaml\nfrom abc import ABCMeta, abstractmethod\nfrom astropy.convolution import Gaussian1DKernel, convolve\nfrom copy import copy\nfrom edges_io import io\nfrom edges_io.logging import logger\nfrom functools import lru_cache\nfrom hashlib import md5\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\nfrom scipy.interpolate import InterpolatedUnivariateSpline as Spline\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nfrom . import DATA_PATH\nfrom . import modelling as mdl\nfrom . import receiver_calibration_func as rcf\nfrom . import reflection_coefficient as rc\nfrom . import s11_correction as s11\nfrom . import tools\nfrom . import types as tp\nfrom . import xrfi\nfrom .cached_property import cached_property\nfrom .tools import EdgesFrequencyRange, FrequencyRange\n\n\nclass S1P:\n def __init__(\n self,\n s1p: tp.PathLike | io.S1P,\n f_low: float | None = None,\n f_high: float | None = None,\n switchval: int | None = None,\n ):\n \"\"\"\n An object representing the measurements of a VNA.\n\n The measurements are read in via a .s1p file\n\n Parameters\n ----------\n s1p : str, Path or :class:`io.S1P`\n The path to a valid .s1p file containing VNA measurements, or an S1P\n object of such a type.\n f_low, f_high : float\n The minimum/maximum frequency to keep.\n switchval : int\n The standard value of the switch for the component.\n \"\"\"\n try:\n s1p = Path(s1p)\n self.s1p = io.S1P(s1p)\n except TypeError:\n if isinstance(s1p, io.S1P):\n self.s1p = s1p\n else:\n raise TypeError(\n \"s1p must be a path to an s1p file, or an io.S1P object\"\n )\n\n self.load_name = self.s1p.kind\n self.repeat_num = self.s1p.repeat_num\n\n spec = self.s1p.s11\n f = self.s1p.freq\n\n self.freq = FrequencyRange(f, f_low, f_high)\n self.s11 = spec[self.freq.mask]\n self._switchval = switchval\n\n @cached_property\n def switchval(self):\n \"\"\"The standard value of the switch for the component.\"\"\"\n if self._switchval is not None:\n return self._switchval * np.ones_like(self.freq.freq)\n else:\n return None\n\n\n# For backwards compatibility\nVNA = S1P\n\n\nclass _S11Base(metaclass=ABCMeta):\n default_nterms = {\n \"ambient\": 37,\n \"hot_load\": 37,\n \"open\": 105,\n \"short\": 105,\n \"AntSim2\": 55,\n \"AntSim3\": 55,\n \"AntSim4\": 55,\n \"lna\": 37,\n }\n\n def __init__(\n self,\n *,\n load_s11: Union[io._S11SubDir, io.ReceiverReading],\n f_low: Optional[float] = None,\n f_high: Optional[float] = None,\n n_terms: Optional[int] = None,\n model_type: tp.Modelable = \"fourier\",\n ):\n \"\"\"\n A class representing relevant switch corrections for a load.\n\n Parameters\n ----------\n load_s11 : :class:`io._S11SubDir`\n An instance of the basic ``io`` S11 folder.\n f_low : float\n Minimum frequency to use. Default is all frequencies.\n f_high : float\n Maximum frequency to use. Default is all frequencies.\n resistance : float\n The resistance of the switch (in Ohms).\n n_terms : int\n The number of terms to use in fitting a model to the S11 (used to both\n smooth and interpolate the data). Must be odd.\n \"\"\"\n self.load_s11 = load_s11\n self.base_path = self.load_s11.path\n\n try:\n self.load_name = getattr(self.load_s11, \"load_name\")\n except AttributeError:\n self.load_name = None\n\n self.run_num = self.load_s11.run_num\n\n switchvals = {\"open\": 1, \"short\": -1, \"match\": 0}\n\n for name in self.load_s11.STANDARD_NAMES:\n setattr(\n self,\n name.lower(),\n S1P(\n s1p=self.load_s11.children[name.lower()],\n f_low=f_low,\n f_high=f_high,\n switchval=switchvals.get(name.lower()),\n ),\n )\n\n # Expose one of the frequency objects\n self.freq = self.open.freq\n self._nterms = int(n_terms) if n_terms is not None else None\n self.model_type = model_type\n\n @cached_property\n def n_terms(self):\n \"\"\"Number of terms to use (by default) in modelling the S11.\n\n Raises\n ------\n ValueError\n If n_terms is even.\n \"\"\"\n res = self._nterms or self.default_nterms.get(self.load_name, None)\n if not (isinstance(res, int) and res % 2):\n raise ValueError(\n f\"n_terms must be odd for S11 models. For {self.load_name} got \"\n f\"n_terms={res}.\"\n )\n return res\n\n @classmethod\n @abstractmethod\n def from_path(cls, **kwargs):\n pass # pragma: no cover\n\n @cached_property\n @abstractmethod\n def measured_load_s11_raw(self):\n pass # pragma: no cover\n\n @cached_property\n def corrected_load_s11(self) -> np.ndarray:\n \"\"\"The measured S11 of the load, corrected for internal switch.\"\"\"\n return self.measured_load_s11_raw\n\n @lru_cache()\n def get_corrected_s11_model(\n self,\n n_terms: int | None = None,\n model_type: tp.Modelable | None = None,\n ):\n \"\"\"Generate a callable model for the S11 correction.\n\n This should closely match :method:`s11_correction`.\n\n Parameters\n ----------\n n_terms : int\n Number of terms used in the fourier-based model. Not necessary if\n `load_name` is specified in the class.\n\n Returns\n -------\n callable :\n A function of one argument, f, which should be a frequency in the same units\n as `self.freq.freq`.\n\n Raises\n ------\n ValueError\n If n_terms is not an integer, or not odd.\n \"\"\"\n n_terms = n_terms or self.n_terms\n model_type = mdl.get_mdl(model_type or self.model_type)\n model = model_type(\n n_terms=n_terms,\n transform=mdl.UnitTransform(range=[self.freq.min, self.freq.max]),\n )\n emodel = model.at(x=self.freq.freq)\n\n cmodel = mdl.ComplexMagPhaseModel(mag=emodel, phs=emodel)\n\n s11_correction = self.corrected_load_s11\n\n return cmodel.fit(ydata=s11_correction)\n\n @cached_property\n def s11_model(self) -> callable:\n \"\"\"The S11 model.\"\"\"\n return self.get_corrected_s11_model()\n\n def plot_residuals(\n self,\n fig=None,\n ax=None,\n color_abs=\"C0\",\n color_diff=\"g\",\n label=None,\n title=None,\n decade_ticks=True,\n ylabels=True,\n ) -> plt.Figure:\n \"\"\"\n Make a plot of the residuals of the S11 model and the correction data.\n\n Residuals obtained via :func:`get_corrected_s11_model`\n\n Returns\n -------\n fig :\n Matplotlib Figure handle.\n \"\"\"\n if fig is None or ax is None or len(ax) != 4:\n fig, ax = plt.subplots(\n 4, 1, sharex=True, gridspec_kw={\"hspace\": 0.05}, facecolor=\"w\"\n )\n\n if decade_ticks:\n for axx in ax:\n axx.xaxis.set_ticks(\n [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180],\n minor=[],\n )\n axx.grid(True)\n ax[-1].set_xlabel(\"Frequency [MHz]\")\n\n corr = self.corrected_load_s11\n model = self.s11_model(self.freq.freq)\n\n ax[0].plot(\n self.freq.freq, 20 * np.log10(np.abs(model)), color=color_abs, label=label\n )\n if ylabels:\n ax[0].set_ylabel(r\"$|S_{11}|$\")\n\n ax[1].plot(self.freq.freq, np.abs(model) - np.abs(corr), color_diff)\n if ylabels:\n ax[1].set_ylabel(r\"$\\Delta |S_{11}|$\")\n\n ax[2].plot(\n self.freq.freq, np.unwrap(np.angle(model)) * 180 / np.pi, color=color_abs\n )\n if ylabels:\n ax[2].set_ylabel(r\"$\\angle S_{11}$\")\n\n ax[3].plot(\n self.freq.freq,\n np.unwrap(np.angle(model)) - np.unwrap(np.angle(corr)),\n color_diff,\n )\n if ylabels:\n ax[3].set_ylabel(r\"$\\Delta \\angle S_{11}$\")\n\n if title is None:\n title = f\"{self.load_name} Reflection Coefficient Models\"\n\n if title:\n fig.suptitle(f\"{self.load_name} Reflection Coefficient Models\", fontsize=14)\n if label:\n ax[0].legend()\n\n return fig\n\n\nclass LoadS11(_S11Base):\n def __init__(self, *, internal_switch: s11.InternalSwitch, **kwargs):\n \"\"\"S11 for a lab calibration load.\n\n Parameters\n ----------\n internal_switch : :class:`s11.InternalSwitch`\n The internal switch state corresponding to the load.\n\n Other Parameters\n ----------------\n Passed through to :class:`_S11Base`.\n \"\"\"\n assert isinstance(internal_switch, s11.InternalSwitch)\n self.internal_switch = internal_switch\n super().__init__(**kwargs)\n\n @classmethod\n def from_path(\n cls,\n load_name: str,\n path: tp.PathLike,\n run_num_load: int = 1,\n run_num_switch: int = 1,\n repeat_num_load: int = None,\n repeat_num_switch: int = None,\n resistance: float = 50.166,\n model_internal_switch: mdl.Model = attr.NOTHING,\n **kwargs,\n ):\n \"\"\"\n Create a new object from a given path and load name.\n\n Parameters\n ----------\n load_name : str\n The name of the load to create.\n path : str or Path\n The path to the overall calibration observation.\n run_num_load : int\n The run to use (default is last run available).\n run_num_switch : int\n The run to use for the switch S11 (default is last run available).\n kwargs\n All other arguments are passed through to the constructor of\n :class:`LoadS11`.\n\n Returns\n -------\n s11 : :class:`LoadS11`\n The S11 of the load.\n \"\"\"\n antsim = load_name.startswith(\"AntSim\")\n path = Path(path)\n\n if not antsim:\n load_name = io.LOAD_ALIASES[load_name]\n\n s11_load_dir = (io.AntSimS11 if antsim else io.LoadS11)(\n path / \"S11\" / f\"{load_name}{run_num_load:02}\", repeat_num=repeat_num_load\n )\n\n internal_switch = s11.InternalSwitch(\n data=io.SwitchingState(\n path / \"S11\" / f\"SwitchingState{run_num_switch:02}\",\n repeat_num=repeat_num_switch,\n ),\n resistance=resistance,\n model=model_internal_switch,\n )\n return cls(load_s11=s11_load_dir, internal_switch=internal_switch, **kwargs)\n\n @cached_property\n def measured_load_s11_raw(self):\n \"\"\"The measured S11 of the load, calculated from raw internal standards.\"\"\"\n return rc.de_embed(\n self.open.switchval,\n self.short.switchval,\n self.match.switchval,\n self.open.s11,\n self.short.s11,\n self.match.s11,\n self.external.s11,\n )[0]\n\n @cached_property\n def corrected_load_s11(self) -> np.ndarray:\n \"\"\"The measured S11 of the load, corrected for the internal switch.\"\"\"\n return rc.gamma_de_embed(\n self.internal_switch.s11_model(self.freq.freq),\n self.internal_switch.s12_model(self.freq.freq),\n self.internal_switch.s22_model(self.freq.freq),\n self.measured_load_s11_raw,\n )\n\n\nclass LNA(_S11Base):\n def __init__(\n self, load_s11: io.ReceiverReading, resistance: float = 50.009, **kwargs\n ):\n \"\"\"A special case of :class:`SwitchCorrection` for the LNA.\n\n Parameters\n ----------\n load_s11 : :class:`io.ReceiverReading`\n The Receiver Reading S11 measurements.\n resistance : float\n The resistance of the receiver.\n kwargs :\n All other arguments passed to :class:`SwitchCorrection`.\n \"\"\"\n super().__init__(load_s11=load_s11, **kwargs)\n self.resistance = resistance\n self.load_name = \"lna\"\n self.repeat_num = self.load_s11.repeat_num\n\n @classmethod\n def from_path(\n cls,\n path: Union[str, Path],\n repeat_num: Optional[int] = None,\n run_num: int = 1,\n **kwargs,\n ):\n \"\"\"\n Create an instance from a given path.\n\n Parameters\n ----------\n path : str or Path\n Path to overall Calibration Observation.\n run_num_load : int\n The run to use for the LNA (default latest available).\n run_num_switch : int\n The run to use for the switching state (default lastest available).\n kwargs\n All other arguments passed through to :class:`SwitchCorrection`.\n\n Returns\n -------\n lna : :class:`LNA`\n The LNA object.\n \"\"\"\n path = Path(path)\n load_s11 = io.ReceiverReading(\n path=path / \"S11\" / f\"ReceiverReading{run_num:02}\",\n repeat_num=repeat_num,\n fix=False,\n )\n\n return cls(load_s11=load_s11, **kwargs)\n\n @cached_property\n def external(self):\n \"\"\"VNA S11 measurements for the load.\"\"\"\n return S1P(\n self.load_s11.children[\"receiverreading\"],\n f_low=self.freq.freq.min(),\n f_high=self.freq.freq.max(),\n )\n\n @cached_property\n def measured_load_s11_raw(self):\n \"\"\"Measured S11 of of the LNA.\"\"\"\n # Models of standards\n oa, sa, la = rc.agilent_85033E(\n self.freq.freq, self.resistance, match_delay=True\n )\n\n # Correction at switch\n return rc.de_embed(\n oa, sa, la, self.open.s11, self.short.s11, self.match.s11, self.external.s11\n )[0]\n\n\nclass LoadSpectrum:\n def __init__(\n self,\n spec_obj: List[io.Spectrum],\n resistance_obj: io.Resistance,\n switch_correction: Optional[LoadS11] = None,\n f_low: float = 40.0,\n f_high: Optional[float] = None,\n ignore_times_percent: float = 5.0,\n rfi_removal: str = \"1D2D\",\n rfi_kernel_width_time: int = 16,\n rfi_kernel_width_freq: int = 16,\n rfi_threshold: float = 6,\n cache_dir: Optional[Union[str, Path]] = None,\n t_load: float = 300.0,\n t_load_ns: float = 400.0,\n ):\n \"\"\"A class representing a measured spectrum from some Load.\n\n Parameters\n ----------\n spec_obj : :class:`io.Spectrum`\n The base Spectrum object defining the on-disk spectra.\n resistance_obj : :class:`io.Resistance`\n The base Resistance object defining the on-disk resistance measurements.\n switch_correction : :class:`SwitchCorrection`\n A `SwitchCorrection` for this particular load. If not given, will be\n constructed automatically.\n f_low : float\n Minimum frequency to keep.\n f_high : float\n Maximum frequency to keep.\n ignore_times_percent : float\n Must be between 0 and 100. Number of time-samples in a file to reject\n from the start of the file.\n rfi_removal : str\n Either '1D', '2D' or '1D2D'. If given, will perform median and mean-filtered\n xRFI over either the\n 2D waterfall, or integrated 1D spectrum. The latter is usually reasonable\n for calibration sources, while the former is good for field data. \"1D2D\"\n is a hybrid approach in which the variance per-frequency is determined\n from the 2D data, but filtering occurs only over frequency.\n rfi_kernel_width_time : int\n The kernel width for the detrending of data for\n RFI removal in the time dimension (only used if `rfi_removal` is \"2D\").\n rfi_kernel_width_freq : int\n The kernel width for the detrending of data for\n RFI removal in the frequency dimension.\n rfi_threshold : float\n The threshold (in equivalent standard deviation units) above which to\n flag data as RFI.\n cache_dir : str or Path\n An alternative directory in which to load/save cached reduced files. By\n default, the same as the path to the .mat files. If you don't have\n write permission there, it may be useful to use an alternative path.\n t_load\n Fiducial guess for the temperature of the internal load.\n t_load_ns\n Fiducial guess for the temperature of the internal load + noise source.\n \"\"\"\n self.spec_obj = spec_obj\n self.resistance_obj = resistance_obj\n\n self.load_name = self.spec_obj[0].load_name\n assert (\n self.load_name == self.resistance_obj.load_name\n ), \"spec and resistance load_name must be the same\"\n\n self.spec_files = (spec_obj.path for spec_obj in self.spec_obj)\n self.resistance_file = self.resistance_obj.path\n\n self.run_num = self.spec_obj[0].run_num\n\n self.cache_dir = Path(cache_dir or \".\")\n\n self.rfi_kernel_width_time = rfi_kernel_width_time\n self.rfi_kernel_width_freq = rfi_kernel_width_freq\n self.rfi_threshold = rfi_threshold\n\n assert rfi_removal in [\n \"1D\",\n \"2D\",\n \"1D2D\",\n False,\n None,\n ], \"rfi_removal must be either '1D', '2D', '1D2D, or False/None\"\n\n self.rfi_removal = rfi_removal\n\n self.switch_correction = switch_correction\n\n self.ignore_times_percent = ignore_times_percent\n self.freq = EdgesFrequencyRange(f_low=f_low, f_high=f_high)\n self.t_load = t_load\n self.t_load_ns = t_load_ns\n\n @classmethod\n def from_load_name(\n cls,\n load_name: str,\n direc: Union[str, Path],\n run_num: Optional[int] = None,\n filetype: Optional[str] = None,\n **kwargs,\n ):\n \"\"\"Instantiate the class from a given load name and directory.\n\n Parameters\n ----------\n load_name : str\n The load name (one of 'ambient', 'hot_load', 'open' or 'short').\n direc : str or Path\n The top-level calibration observation directory.\n run_num : int\n The run number to use for the spectra.\n filetype : str\n The filetype to look for (acq or h5).\n kwargs :\n All other arguments to :class:`LoadSpectrum`.\n\n Returns\n -------\n :class:`LoadSpectrum`.\n \"\"\"\n direc = Path(direc)\n\n spec = io.Spectrum.from_load(\n load=load_name, direc=direc / \"Spectra\", run_num=run_num, filetype=filetype\n )\n res = io.Resistance.from_load(\n load=load_name,\n direc=direc / \"Resistance\",\n run_num=run_num,\n filetype=filetype,\n )\n return cls(spec_obj=spec, resistance_obj=res, **kwargs)\n\n @cached_property\n def averaged_Q(self) -> np.ndarray:\n \"\"\"Ratio of powers averaged over time.\n\n Notes\n -----\n The formula is\n\n .. math:: Q = (P_source - P_load)/(P_noise - P_load)\n \"\"\"\n # TODO: should also get weights!\n spec = self._ave_and_var_spec[0][\"Q\"]\n\n if self.rfi_removal == \"1D\":\n flags, _ = xrfi.xrfi_medfilt(\n spec, threshold=self.rfi_threshold, kf=self.rfi_kernel_width_freq\n )\n spec[flags] = np.nan\n return spec\n\n @property\n def variance_Q(self) -> np.ndarray:\n \"\"\"Variance of Q across time (see averaged_Q).\"\"\"\n return self._ave_and_var_spec[1][\"Q\"]\n\n @property\n def averaged_spectrum(self) -> np.ndarray:\n \"\"\"T* = T_noise * Q + T_load.\"\"\"\n return self.averaged_Q * self.t_load_ns + self.t_load\n\n @property\n def variance_spectrum(self) -> np.ndarray:\n \"\"\"Variance of uncalibrated spectrum across time (see averaged_spectrum).\"\"\"\n return self.variance_Q * self.t_load_ns ** 2\n\n @property\n def ancillary(self) -> dict:\n \"\"\"Ancillary measurement data.\"\"\"\n return [d.data[\"meta\"] for d in self.spec_obj]\n\n @property\n def averaged_p0(self) -> np.ndarray:\n \"\"\"Power of the load, averaged over time.\"\"\"\n return self._ave_and_var_spec[0][\"p0\"]\n\n @property\n def averaged_p1(self) -> np.ndarray:\n \"\"\"Power of the noise-source, averaged over time.\"\"\"\n return self._ave_and_var_spec[0][\"p1\"]\n\n @property\n def averaged_p2(self) -> np.ndarray:\n \"\"\"Power of the load plus noise-source, averaged over time.\"\"\"\n return self._ave_and_var_spec[0][\"p2\"]\n\n @property\n def variance_p0(self) -> np.ndarray:\n \"\"\"Variance of the load, averaged over time.\"\"\"\n return self._ave_and_var_spec[1][\"p0\"]\n\n @property\n def variance_p1(self) -> np.ndarray:\n \"\"\"Variance of the noise-source, averaged over time.\"\"\"\n return self._ave_and_var_spec[1][\"p1\"]\n\n @property\n def variance_p2(self) -> np.ndarray:\n \"\"\"Variance of the load plus noise-source, averaged over time.\"\"\"\n return self._ave_and_var_spec[1][\"p2\"]\n\n @property\n def n_integrations(self) -> int:\n \"\"\"The number of integrations recorded for the spectrum (after ignoring).\"\"\"\n return self._ave_and_var_spec[2]\n\n def _get_integrated_filename(self):\n \"\"\"Determine a unique filename for the reduced data of this instance.\"\"\"\n params = (\n self.rfi_threshold,\n self.rfi_kernel_width_time,\n self.rfi_kernel_width_freq,\n self.rfi_removal,\n self.ignore_times_percent,\n self.freq.min,\n self.freq.max,\n self.t_load,\n self.t_load_ns,\n tuple(path.name for path in self.spec_files),\n )\n hsh = md5(str(params).encode()).hexdigest()\n\n return self.cache_dir / f\"{self.load_name}_{hsh}.h5\"\n\n @cached_property\n def _ave_and_var_spec(self) -> Tuple[Dict, Dict, int]:\n \"\"\"Get the mean and variance of the spectra.\"\"\"\n fname = self._get_integrated_filename()\n\n kinds = [\"p0\", \"p1\", \"p2\", \"Q\"]\n if fname.exists():\n logger.info(\n f\"Reading in previously-created integrated {self.load_name} spectra...\"\n )\n means = {}\n variances = {}\n with h5py.File(fname, \"r\") as fl:\n for kind in kinds:\n means[kind] = fl[kind + \"_mean\"][...]\n variances[kind] = fl[kind + \"_var\"][...]\n n_integrations = fl.attrs.get(\"n_integrations\", 0)\n return means, variances, n_integrations\n\n logger.info(f\"Reducing {self.load_name} spectra...\")\n spectra = self.get_spectra()\n\n means = {}\n variances = {}\n\n for key, spec in spectra.items():\n # Weird thing where there are zeros in the spectra.\n spec[spec == 0] = np.nan\n\n mean = np.nanmean(spec, axis=1)\n var = np.nanvar(spec, axis=1)\n n_intg = spec.shape[1]\n\n if self.rfi_removal == \"1D2D\":\n nsample = np.sum(~np.isnan(spec), axis=1)\n varfilt = xrfi.flagged_filter(\n var, size=2 * self.rfi_kernel_width_freq + 1\n )\n resid = mean - xrfi.flagged_filter(\n mean, size=2 * self.rfi_kernel_width_freq + 1\n )\n flags = np.logical_or(\n resid > self.rfi_threshold * np.sqrt(varfilt / nsample),\n var - varfilt\n > self.rfi_threshold * np.sqrt(2 * varfilt ** 2 / (nsample - 1)),\n )\n\n mean[flags] = np.nan\n var[flags] = np.nan\n\n means[key] = mean\n variances[key] = var\n\n if not self.cache_dir.exists():\n self.cache_dir.mkdir()\n\n with h5py.File(fname, \"w\") as fl:\n logger.info(f\"Saving reduced spectra to cache at {fname}\")\n for kind in kinds:\n fl[kind + \"_mean\"] = means[kind]\n fl[kind + \"_var\"] = variances[kind]\n fl.attrs[\"n_integrations\"] = n_intg\n\n return means, variances, n_intg\n\n def get_spectra(self) -> dict:\n \"\"\"Read all spectra and remove RFI.\n\n Returns\n -------\n dict :\n A dictionary with keys being different powers (p1, p2, p3, Q), and values\n being ndarrays.\n \"\"\"\n spec = self._read_spectrum()\n\n if self.rfi_removal == \"2D\":\n for key, val in spec.items():\n # Need to set nans and zeros to inf so that median/mean detrending\n # can work.\n val[np.isnan(val)] = np.inf\n\n if key != \"Q\":\n val[val == 0] = np.inf\n\n flags, _ = xrfi.xrfi_medfilt(\n val,\n threshold=self.rfi_threshold,\n kt=self.rfi_kernel_width_time,\n kf=self.rfi_kernel_width_freq,\n )\n val[flags] = np.nan\n spec[key] = val\n return spec\n\n def _read_spectrum(self) -> dict:\n \"\"\"\n Read the contents of the spectrum files into memory.\n\n Removes a starting percentage of times, and masks out certain frequencies.\n\n Returns\n -------\n dict :\n A dictionary of the contents of the file. Usually p0, p1, p2 (un-normalised\n powers of source, load, and load+noise respectively), and ant_temp (the\n uncalibrated, but normalised antenna temperature).\n \"\"\"\n data = [spec_obj.data for spec_obj in self.spec_obj]\n\n n_times = sum(len(d[\"time_ancillary\"][\"times\"]) for d in data)\n out = {\n \"p0\": np.empty((len(self.freq.freq), n_times)),\n \"p1\": np.empty((len(self.freq.freq), n_times)),\n \"p2\": np.empty((len(self.freq.freq), n_times)),\n \"Q\": np.empty((len(self.freq.freq), n_times)),\n }\n\n index_start_spectra = int((self.ignore_times_percent / 100) * n_times)\n for key, val in out.items():\n nn = 0\n for d in data:\n n = len(d[\"time_ancillary\"][\"times\"])\n val[:, nn : (nn + n)] = d[\"spectra\"][key][self.freq.mask]\n nn += n\n\n out[key] = val[:, index_start_spectra:]\n\n return out\n\n @cached_property\n def thermistor(self) -> np.ndarray:\n \"\"\"The thermistor readings.\"\"\"\n ary = self.resistance_obj.read()[0]\n\n return ary[int((self.ignore_times_percent / 100) * len(ary)) :]\n\n @cached_property\n def thermistor_temp(self):\n \"\"\"The associated thermistor temperature in K.\"\"\"\n return rcf.temperature_thermistor(self.thermistor[\"load_resistance\"])\n\n @cached_property\n def temp_ave(self):\n \"\"\"Average thermistor temperature (over time and frequency).\"\"\"\n return np.nanmean(self.thermistor_temp)\n\n def write(self, path=None):\n \"\"\"\n Write a HDF5 file containing the contents of the LoadSpectrum.\n\n Parameters\n ----------\n path : str\n Directory into which to save the file, or full path to file.\n If a directory, filename will be <load_name>_averaged_spectrum.h5.\n Default is current directory.\n \"\"\"\n path = Path(path or \".\")\n\n # Allow to pass in a directory name *or* full path.\n if path.is_dir():\n path /= f\"{self.load_name}_averaged_spectrum.h5\"\n\n with h5py.File(path, \"w\") as fl:\n fl.attrs[\"load_name\"] = self.load_name\n fl[\"freq\"] = self.freq.freq\n fl[\"averaged_raw_spectrum\"] = self.averaged_spectrum\n fl[\"temperature\"] = self.thermistor_temp\n\n def plot(\n self, thermistor=False, fig=None, ax=None, xlabel=True, ylabel=True, **kwargs\n ):\n \"\"\"\n Make a plot of the averaged uncalibrated spectrum associated with this load.\n\n Parameters\n ----------\n thermistor : bool\n Whether to plot the thermistor temperature on the same axis.\n fig : Figure\n Optionally, pass a matplotlib figure handle which will be used to plot.\n ax : Axis\n Optional, pass a matplotlib Axis handle which will be added to.\n xlabel : bool\n Whether to make an x-axis label.\n ylabel : bool\n Whether to plot the y-axis label\n kwargs :\n All other arguments are passed to `plt.subplots()`.\n \"\"\"\n if fig is None:\n fig, ax = plt.subplots(\n 1, 1, facecolor=kwargs.pop(\"facecolor\", \"white\"), **kwargs\n )\n\n if thermistor:\n ax.plot(self.freq.freq, self.thermistor_temp)\n if ylabel:\n ax.set_ylabel(\"Temperature [K]\")\n else:\n ax.plot(self.freq.freq, self.averaged_spectrum)\n if ylabel:\n ax.set_ylabel(\"$T^*$ [K]\")\n\n ax.grid(True)\n if xlabel:\n ax.set_xlabel(\"Frequency [MHz]\")\n\n\nclass HotLoadCorrection:\n\n _kinds = {\"s11\": 0, \"s12\": 1, \"s22\": 2}\n\n def __init__(\n self,\n path: Union[str, Path] = \":semi_rigid_s_parameters_WITH_HEADER.txt\",\n f_low: Optional[float] = None,\n f_high: Optional[float] = None,\n n_terms: int = 21,\n ):\n \"\"\"\n Corrections for the hot load.\n\n Measurements required to define the HotLoad temperature, from Monsalve et al.\n (2017), Eq. 8+9.\n\n Parameters\n ----------\n path : str or Path, optional\n Path to a file containing measurements of the semi-rigid cable reflection\n parameters. A preceding colon (:) indicates to prefix with DATA_PATH.\n The default file was measured in 2015, but there is also a file included\n that can be used from 2017: \":semi_rigid_s_parameters_2017.txt\".\n f_low, f_high : float\n Lowest/highest frequency to retain from measurements.\n \"\"\"\n # Get the path to the S11 file.\n if not isinstance(path, Path):\n path = DATA_PATH / path[1:] if path[0] == \":\" else Path(path)\n self.path = path\n data = np.genfromtxt(self.path)\n\n f = data[:, 0]\n self.freq = FrequencyRange(f, f_low, f_high)\n\n if data.shape[1] == 7: # Original file from 2015\n self.data = data[self.freq.mask, 1::2] + 1j * data[self.freq.mask, 2::2]\n elif data.shape[1] == 6: # File from 2017\n self.data = np.array(\n [\n data[self.freq.mask, 1] + 1j * data[self.freq.mask, 2],\n data[self.freq.mask, 3],\n data[self.freq.mask, 4] + 1j * data[self.freq.mask, 5],\n ]\n ).T\n else:\n raise IOError(\"Semi-Rigid Cable file has wrong data format.\")\n\n self.n_terms = int(n_terms)\n\n def _get_model_kind(self, kind):\n model = mdl.Polynomial(\n n_terms=self.n_terms,\n transform=mdl.UnitTransform(range=(self.freq.min, self.freq.max)),\n )\n model = mdl.ComplexMagPhaseModel(mag=model, phs=model)\n return model.fit(xdata=self.freq.freq, ydata=self.data[:, self._kinds[kind]])\n\n @cached_property\n def s11_model(self):\n \"\"\"The reflection coefficient.\"\"\"\n return self._get_model_kind(\"s11\")\n\n @cached_property\n def s12_model(self):\n \"\"\"The transmission coefficient.\"\"\"\n return self._get_model_kind(\"s12\")\n\n @cached_property\n def s22_model(self):\n \"\"\"The reflection coefficient from the other side.\"\"\"\n return self._get_model_kind(\"s22\")\n\n def power_gain(self, freq: np.ndarray, hot_load_s11: LoadS11) -> np.ndarray:\n \"\"\"\n Calculate the power gain.\n\n Parameters\n ----------\n freq : np.ndarray\n The frequencies.\n hot_load_s11 : :class:`LoadS11`\n The S11 of the hot load.\n\n Returns\n -------\n gain : np.ndarray\n The power gain as a function of frequency.\n \"\"\"\n assert isinstance(\n hot_load_s11, LoadS11\n ), \"hot_load_s11 must be a switch correction\"\n assert (\n hot_load_s11.load_name == \"hot_load\"\n ), \"hot_load_s11 must be a hot_load s11\"\n\n return self.get_power_gain(\n {\n \"s11\": self.s11_model(freq),\n \"s12s21\": self.s12_model(freq),\n \"s22\": self.s22_model(freq),\n },\n hot_load_s11.s11_model(freq),\n )\n\n @staticmethod\n def get_power_gain(\n semi_rigid_sparams: dict, hot_load_s11: np.ndarray\n ) -> np.ndarray:\n \"\"\"Define Eq. 9 from M17.\n\n Parameters\n ----------\n semi_rigid_sparams : dict\n A dictionary of reflection coefficient measurements as a function of\n frequency for the semi-rigid cable.\n hot_load_s11 : array-like\n The S11 measurement of the hot_load.\n\n Returns\n -------\n gain : np.ndarray\n The power gain.\n \"\"\"\n rht = rc.gamma_de_embed(\n semi_rigid_sparams[\"s11\"],\n semi_rigid_sparams[\"s12s21\"],\n semi_rigid_sparams[\"s22\"],\n hot_load_s11,\n )\n\n return (\n np.abs(semi_rigid_sparams[\"s12s21\"])\n * (1 - np.abs(rht) ** 2)\n / (\n (np.abs(1 - semi_rigid_sparams[\"s11\"] * rht)) ** 2\n * (1 - np.abs(hot_load_s11) ** 2)\n )\n )\n\n\nclass Load:\n def __init__(\n self,\n spectrum: LoadSpectrum,\n reflections: LoadS11,\n hot_load_correction: Optional[HotLoadCorrection] = None,\n ambient: Optional[LoadSpectrum] = None,\n ):\n \"\"\"Wrapper class containing all relevant information for a given load.\n\n Parameters\n ----------\n spectrum : :class:`LoadSpectrum`\n The spectrum for this particular load.\n reflections : :class:`SwitchCorrection`\n The S11 measurements for this particular load.\n hot_load_correction : :class:`HotLoadCorrection`\n If this is a hot load, provide a hot load correction.\n ambient : :class:`LoadSpectrum`\n If this is a hot load, need to provide an ambient spectrum to correct it.\n \"\"\"\n assert isinstance(spectrum, LoadSpectrum), \"spectrum must be a LoadSpectrum\"\n assert isinstance(reflections, LoadS11), \"spectrum must be a SwitchCorrection\"\n assert spectrum.load_name == reflections.load_name\n\n self.spectrum = spectrum\n self.reflections = reflections\n self.load_name = spectrum.load_name\n self.t_load = self.spectrum.t_load\n self.t_load_ns = self.spectrum.t_load_ns\n\n if self.load_name == \"hot_load\":\n self._correction = hot_load_correction\n self._ambient = ambient\n\n @classmethod\n def from_path(\n cls,\n path: Union[str, Path],\n load_name: str,\n f_low: Optional[float] = None,\n f_high: Optional[float] = None,\n reflection_kwargs: Optional[dict] = None,\n spec_kwargs: Optional[dict] = None,\n ):\n \"\"\"\n Define a full :class:`Load` from a path and name.\n\n Parameters\n ----------\n path : str or Path\n Path to the top-level calibration observation.\n load_name : str\n Name of a load to define.\n f_low, f_high : float\n Min/max frequencies to keep in measurements.\n reflection_kwargs : dict\n Extra arguments to pass through to :class:`SwitchCorrection`.\n spec_kwargs : dict\n Extra arguments to pass through to :class:`LoadSpectrum`.\n\n Returns\n -------\n load : :class:`Load`\n The load object, containing all info about spectra and S11's for that load.\n \"\"\"\n if not spec_kwargs:\n spec_kwargs = {}\n if not reflection_kwargs:\n reflection_kwargs = {}\n\n spec = LoadSpectrum.from_load_name(\n load_name,\n path,\n f_low=f_low,\n f_high=f_high,\n **spec_kwargs,\n )\n\n refl = LoadS11.from_path(\n load_name,\n path,\n f_low=f_low,\n f_high=f_high,\n **reflection_kwargs,\n )\n\n return cls(spec, refl)\n\n @property\n def s11_model(self):\n \"\"\"The S11 model.\"\"\"\n return self.reflections.s11_model\n\n @cached_property\n def temp_ave(self):\n \"\"\"The average temperature of the thermistor (over frequency and time).\"\"\"\n if self.load_name != \"hot_load\":\n return self.spectrum.temp_ave\n\n gain = self._correction.power_gain(self.freq.freq, self.reflections)\n # temperature\n return gain * self.spectrum.temp_ave + (1 - gain) * self._ambient.temp_ave\n\n @property\n def averaged_Q(self):\n \"\"\"Averaged power ratio.\"\"\"\n return self.spectrum.averaged_Q\n\n @property\n def averaged_spectrum(self):\n \"\"\"Averaged uncalibrated temperature.\"\"\"\n return self.spectrum.averaged_spectrum\n\n @property\n def freq(self):\n \"\"\"A :class:`FrequencyRange` object corresponding to this measurement.\"\"\"\n return self.spectrum.freq\n\n\nclass CalibrationObservation:\n _sources = (\"ambient\", \"hot_load\", \"open\", \"short\")\n\n def __init__(\n self,\n path: Union[str, Path],\n semi_rigid_path: Union[str, Path] = \":semi_rigid_s_parameters_WITH_HEADER.txt\",\n f_low: Optional[float] = 40,\n f_high: Optional[float] = None,\n run_num: Union[None, int, dict] = None,\n repeat_num: Union[None, int, dict] = None,\n resistance_f: Optional[float] = None,\n cterms: int = 5,\n wterms: int = 7,\n load_kwargs: Optional[dict] = None,\n s11_kwargs: Optional[dict] = None,\n load_spectra: Optional[dict] = None,\n load_s11s: Optional[dict] = None,\n compile_from_def: bool = True,\n include_previous: bool = False,\n internal_switch_kwargs: Optional[Dict[str, Any]] = None,\n ):\n \"\"\"\n A composite object representing a full Calibration Observation.\n\n This includes spectra of all calibrators, and methods to find the calibration\n parameters. It strictly follows Monsalve et al. (2017) in its formalism.\n While by default the class uses the calibrator sources (\"ambient\", \"hot_load\",\n \"open\", \"short\"), it can be modified to take other sources by setting\n ``CalibrationObservation._sources`` to a new tuple of strings.\n\n Parameters\n ----------\n path : str or Path\n Path to the directory containing all relevant measurements. It is assumed\n that in this directory is an `S11`, `Resistance` and `Spectra` directory.\n semi_rigid_path : str or Path, optional\n Path to a file containing S11 measurements for the semi rigid cable. Used to\n correct the hot load S11. Found automatically if not given.\n ambient_temp : int\n Ambient temperature (C) at which measurements were taken.\n f_low : float\n Minimum frequency to keep for all loads (and their S11's). If for some\n reason different frequency bounds are desired per-load, one can pass in\n full load objects through ``load_spectra``.\n f_high : float\n Maximum frequency to keep for all loads (and their S11's). If for some\n reason different frequency bounds are desired per-load, one can pass in\n full load objects through ``load_spectra``.\n run_num : int or dict\n Which run number to use for the calibrators. Default is to use the last run\n for each. Passing an int will attempt to use that run for each source. Pass\n a dict mapping sources to numbers to use different combinations.\n repeat_num : int or dict\n Which repeat number to use for the calibrators. Default is to use the last\n repeat for each. Passing an int will attempt to use that repeat for each\n source. Pass a dict mapping sources to numbers to use different\n combinations.\n resistance_f : float\n Female resistance (Ohms). Used for the LNA S11.\n cterms : int\n The number of terms to use for the polynomial fits to the calibration\n functions.\n wterms : int\n The number of terms to use for the polynomial fits to the noise-wave\n calibration functions.\n load_kwargs : dict\n Keyword arguments used to instantiate the calibrator :class:`LoadSpectrum`\n objects. See its documentation for relevant parameters. Parameters specified\n here are used for _all_ calibrator sources.\n s11_kwargs : dict\n Keyword arguments used to instantiate the calibrator :class:`LoadS11`\n objects. See its documentation for relevant parameters. Parameters specified\n here are used for _all_ calibrator sources.\n load_spectra : dict\n A dictionary mapping load names of calibration sources (eg. ambient, short)\n to either :class:`LoadSpectrum` instances or dictionaries of keywords to\n instantiate those objects. Useful for individually specifying\n properties of each load separately. Values in these dictionaries (if\n supplied) over-ride those given in ``load_kwargs`` (but values in\n ``load_kwargs`` are still used if not over-ridden).\n load_s11s : dict\n A dictionary mapping load names of calibration sources (eg. ambient, short)\n to :class:`LoadS11` instances or dictionaries of keywords to instantiate\n those objects. Useful for individually specifying properties of each load\n separately. Values in these dictionaries (if supplied) over-ride those\n given in ``s11_kwargs`` (but values in ``s11_kwargs`` are still used if not\n over-ridden).\n compile_from_def : bool\n Whether to attempt compiling a virtual observation from a\n ``definition.yaml`` inside the observation directory. This is the default\n behaviour, but can be turned off to enforce that the current directory\n should be used directly.\n include_previous : bool\n Whether to include the previous observation by default to supplement this\n one if required files are missing.\n\n Examples\n --------\n This will setup an observation with all default options applied:\n\n >>> path = '/CalibrationObservations/Receiver01_25C_2019_11_26_040_to_200MHz'\n >>> calobs = CalibrationObservation(path)\n\n To specify some options for constructing the various calibrator load spectra:\n\n >>> calobs = CalibrationObservation(\n >>> path,\n >>> load_kwargs={\"cache_dir\":\".\", \"ignore_times_percent\": 50}\n >>> )\n\n But if we typically wanted 50% of times ignored, but in one special case we'd\n like 80%:\n\n >>> calobs = CalibrationObservation(\n >>> path,\n >>> load_kwargs={\"cache_dir\":\".\", \"ignore_times_percent\": 50},\n >>> load_spectra={\"short\": {\"ignore_times_percent\": 80}}\n >>> )\n\n \"\"\"\n load_spectra = load_spectra or {}\n load_s11s = load_s11s or {}\n load_kwargs = load_kwargs or {}\n s11_kwargs = s11_kwargs or {}\n internal_switch_kwargs = internal_switch_kwargs or {}\n\n assert all(name in self._sources for name in load_spectra)\n assert all(name in self._sources + (\"lna\",) for name in load_s11s)\n\n self.io = io.CalibrationObservation(\n path,\n run_num=run_num,\n repeat_num=repeat_num,\n fix=False,\n compile_from_def=compile_from_def,\n include_previous=include_previous,\n )\n self.compiled_from_def = compile_from_def\n self.previous_included = include_previous\n\n self.path = Path(self.io.path)\n\n hot_load_correction = HotLoadCorrection(semi_rigid_path, f_low, f_high)\n\n self.internal_switch = s11.InternalSwitch(\n data=self.io.s11.switching_state,\n resistance=self.io.definition[\"measurements\"][\"resistance_m\"][\n self.io.s11.switching_state.run_num\n ],\n **internal_switch_kwargs,\n )\n\n self._loads = {}\n for source in self._sources:\n load = load_spectra.get(source, {})\n\n if isinstance(load, dict):\n load = LoadSpectrum(\n spec_obj=getattr(self.io.spectra, source),\n resistance_obj=getattr(self.io.resistance, source),\n f_low=f_low,\n f_high=f_high,\n **{**load_kwargs, **load},\n )\n\n # Ensure that we finally have a LoadSpectrum\n if not isinstance(load, LoadSpectrum):\n raise TypeError(\"load_spectra must be a dict of LoadSpectrum or dicts.\")\n\n refl = load_s11s.get(source, {})\n\n if isinstance(refl, dict):\n refl = LoadS11(\n load_s11=getattr(self.io.s11, source),\n internal_switch=self.internal_switch,\n f_low=f_low,\n f_high=f_high,\n **{**s11_kwargs, **refl},\n )\n\n if source == \"hot_load\":\n self._loads[source] = Load(\n load,\n refl,\n hot_load_correction=hot_load_correction,\n ambient=self._loads[\"ambient\"].spectrum,\n )\n else:\n self._loads[source] = Load(load, refl)\n\n for name, load in self._loads.items():\n setattr(self, name, load)\n\n refl = load_s11s.get(\"lna\", {})\n\n self.lna = LNA(\n load_s11=self.io.s11.receiver_reading,\n f_low=f_low,\n f_high=f_high,\n resistance=resistance_f\n or self.io.definition[\"measurements\"][\"resistance_f\"][\n self.io.s11.receiver_reading.run_num\n ],\n **{**s11_kwargs, **refl},\n )\n\n # We must use the most restricted frequency range available from all available\n # sources as well as the LNA.\n fmin = max(\n sum(\n (\n [load.spectrum.freq.min, load.reflections.freq.min]\n for load in self._loads.values()\n ),\n [],\n )\n + [self.lna.freq.min]\n )\n\n fmax = min(\n sum(\n (\n [load.spectrum.freq.max, load.reflections.freq.max]\n for load in self._loads.values()\n ),\n [],\n )\n + [self.lna.freq.max]\n )\n\n if fmax <= fmin:\n raise ValueError(\n \"The inputs loads and S11s have non-overlapping frequency ranges!\"\n )\n\n self.freq = EdgesFrequencyRange(f_low=fmin, f_high=fmax)\n\n # Now make everything actually consistent in its frequency range.\n for load in self._loads.values():\n load.spectrum.freq = self.freq\n\n self.cterms = cterms\n self.wterms = wterms\n self.t_load = self.ambient.t_load\n self.t_load_ns = self.ambient.t_load_ns\n\n @property\n def load_names(self) -> Tuple[str]:\n \"\"\"Names of the loads.\"\"\"\n return tuple(self._loads.keys())\n\n def new_load(\n self,\n load_name: str,\n run_num: int = 1,\n reflection_kwargs: Optional[dict] = None,\n spec_kwargs: Optional[dict] = None,\n ):\n \"\"\"Create a new load with the given load name.\n\n Uses files inside the current observation.\n\n Parameters\n ----------\n load_name : str\n The name of the load ('ambient', 'hot_load', 'open', 'short').\n run_num_spec : dict or int\n Run number to use for the spectrum.\n run_num_load : dict or int\n Run number to use for the load's S11.\n reflection_kwargs : dict\n Keyword arguments to construct the :class:`SwitchCorrection`.\n spec_kwargs : dict\n Keyword arguments to construct the :class:`LoadSpectrum`.\n \"\"\"\n reflection_kwargs = reflection_kwargs or {}\n spec_kwargs = spec_kwargs or {}\n\n # Fill up kwargs with keywords from this instance\n if \"resistance\" not in reflection_kwargs:\n reflection_kwargs[\n \"resistance\"\n ] = self.open.reflections.internal_switch.resistance\n\n for key in [\n \"ignore_times_percent\",\n \"rfi_removal\",\n \"rfi_kernel_width_freq\",\n \"rfi_kernel_width_time\",\n \"rfi_threshold\",\n \"cache_dir\",\n \"t_load\",\n \"t_load_ns\",\n ]:\n if key not in spec_kwargs:\n spec_kwargs[key] = getattr(self.open.spectrum, key)\n\n reflection_kwargs[\"run_num_load\"] = run_num\n reflection_kwargs[\"repeat_num_switch\"] = self.io.s11.switching_state.repeat_num\n reflection_kwargs[\"run_num_switch\"] = self.io.s11.switching_state.run_num\n spec_kwargs[\"run_num\"] = run_num\n\n return Load.from_path(\n path=self.io.path,\n load_name=load_name,\n f_low=self.freq.min,\n f_high=self.freq.max,\n reflection_kwargs=reflection_kwargs,\n spec_kwargs=spec_kwargs,\n )\n\n def plot_raw_spectra(self, fig=None, ax=None) -> plt.Figure:\n \"\"\"\n Plot raw uncalibrated spectra for all calibrator sources.\n\n Parameters\n ----------\n fig : :class:`plt.Figure`\n A matplotlib figure on which to make the plot. By default creates a new one.\n ax : :class:`plt.Axes`\n A matplotlib Axes on which to make the plot. By default creates a new one.\n\n Returns\n -------\n fig : :class:`plt.Figure`\n The figure on which the plot was made.\n \"\"\"\n if fig is None and ax is None:\n fig, ax = plt.subplots(\n len(self._sources), 1, sharex=True, gridspec_kw={\"hspace\": 0.05}\n )\n\n for i, (name, load) in enumerate(self._loads.items()):\n load.spectrum.plot(\n fig=fig, ax=ax[i], xlabel=(i == (len(self._sources) - 1))\n )\n ax[i].set_title(name)\n\n return fig\n\n def plot_s11_models(self, **kwargs):\n \"\"\"\n Plot residuals of S11 models for all sources.\n\n Returns\n -------\n dict:\n Each entry has a key of the source name, and the value is a matplotlib fig.\n \"\"\"\n out = {\n name: source.reflections.plot_residuals(**kwargs)\n for name, source in self._loads.items()\n }\n out.update({\"lna\": self.lna.plot_residuals(**kwargs)})\n return out\n\n @cached_property\n def s11_correction_models(self):\n \"\"\"Dictionary of S11 correction models, one for each source.\"\"\"\n try:\n return dict(self._injected_source_s11s)\n except (TypeError, AttributeError):\n return {\n name: source.s11_model(self.freq.freq)\n for name, source in self._loads.items()\n }\n\n @cached_property\n def source_thermistor_temps(self) -> Dict[str, Union[float, np.ndarray]]:\n \"\"\"Dictionary of input source thermistor temperatures.\"\"\"\n if (\n hasattr(self, \"_injected_source_temps\")\n and self._injected_source_temps is not None\n ):\n return self._injected_source_temps\n\n return {k: source.temp_ave for k, source in self._loads.items()}\n\n @cached_property\n def _calibration_coefficients(self):\n \"\"\"The calibration polynomials, evaluated at `freq.freq`.\"\"\"\n if (\n hasattr(self, \"_injected_averaged_spectra\")\n and self._injected_averaged_spectra is not None\n ):\n ave_spec = self._injected_averaged_spectra\n else:\n ave_spec = {\n k: source.averaged_spectrum for k, source in self._loads.items()\n }\n scale, off, Tu, TC, TS = rcf.get_calibration_quantities_iterative(\n self.freq.freq_recentred,\n temp_raw=ave_spec,\n gamma_rec=self.lna_s11,\n gamma_ant=self.s11_correction_models,\n temp_ant=self.source_thermistor_temps,\n cterms=self.cterms,\n wterms=self.wterms,\n temp_amb_internal=self.t_load,\n )\n return scale, off, Tu, TC, TS\n\n @cached_property\n def C1_poly(self): # noqa: N802\n \"\"\"`np.poly1d` object describing the Scaling calibration coefficient C1.\n\n The polynomial is defined to act on normalized frequencies such that `freq.min`\n and `freq.max` map to -1 and 1 respectively. Use :func:`~C1` as a direct\n function on frequency.\n \"\"\"\n return self._calibration_coefficients[0]\n\n @cached_property\n def C2_poly(self): # noqa: N802\n \"\"\"`np.poly1d` object describing the offset calibration coefficient C2.\n\n The polynomial is defined to act on normalized frequencies such that `freq.min`\n and `freq.max` map to -1 and 1 respectively. Use :func:`~C2` as a direct\n function on frequency.\n \"\"\"\n return self._calibration_coefficients[1]\n\n @cached_property\n def Tunc_poly(self): # noqa: N802\n \"\"\"`np.poly1d` object describing the uncorrelated noise-wave parameter, Tunc.\n\n The polynomial is defined to act on normalized frequencies such that `freq.min`\n and `freq.max` map to -1 and 1 respectively. Use :func:`~Tunc` as a direct\n function on frequency.\n \"\"\"\n return self._calibration_coefficients[2]\n\n @cached_property\n def Tcos_poly(self): # noqa: N802\n \"\"\"`np.poly1d` object describing the cosine noise-wave parameter, Tcos.\n\n The polynomial is defined to act on normalized frequencies such that `freq.min`\n and `freq.max` map to -1 and 1 respectively. Use :func:`~Tcos` as a direct\n function on frequency.\n \"\"\"\n return self._calibration_coefficients[3]\n\n @cached_property\n def Tsin_poly(self): # noqa: N802\n \"\"\"`np.poly1d` object describing the sine noise-wave parameter, Tsin.\n\n The polynomial is defined to act on normalized frequencies such that `freq.min`\n and `freq.max` map to -1 and 1 respectively. Use :func:`~Tsin` as a direct\n function on frequency.\n \"\"\"\n return self._calibration_coefficients[4]\n\n def C1(self, f: Optional[Union[float, np.ndarray]] = None): # noqa: N802\n \"\"\"\n Scaling calibration parameter.\n\n Parameters\n ----------\n f : array-like\n The frequencies at which to evaluate C1. By default, the frequencies of this\n instance.\n \"\"\"\n if hasattr(self, \"_injected_c1\") and self._injected_c1 is not None:\n return np.array(self._injected_c1)\n fnorm = self.freq.freq_recentred if f is None else self.freq.normalize(f)\n return self.C1_poly(fnorm)\n\n def C2(self, f: Optional[Union[float, np.ndarray]] = None): # noqa: N802\n \"\"\"\n Offset calibration parameter.\n\n Parameters\n ----------\n f : array-like\n The frequencies at which to evaluate C2. By default, the frequencies of this\n instance.\n \"\"\"\n if hasattr(self, \"_injected_c2\") and self._injected_c2 is not None:\n return np.array(self._injected_c2)\n fnorm = self.freq.freq_recentred if f is None else self.freq.normalize(f)\n return self.C2_poly(fnorm)\n\n def Tunc(self, f: Optional[Union[float, np.ndarray]] = None): # noqa: N802\n \"\"\"\n Uncorrelated noise-wave parameter.\n\n Parameters\n ----------\n f : array-like\n The frequencies at which to evaluate Tunc. By default, the frequencies of\n thisinstance.\n \"\"\"\n if hasattr(self, \"_injected_t_unc\") and self._injected_t_unc is not None:\n return np.array(self._injected_t_unc)\n fnorm = self.freq.freq_recentred if f is None else self.freq.normalize(f)\n return self.Tunc_poly(fnorm)\n\n def Tcos(self, f: Optional[Union[float, np.ndarray]] = None): # noqa: N802\n \"\"\"\n Cosine noise-wave parameter.\n\n Parameters\n ----------\n f : array-like\n The frequencies at which to evaluate Tcos. By default, the frequencies of\n this instance.\n \"\"\"\n if hasattr(self, \"_injected_t_cos\") and self._injected_t_cos is not None:\n return np.array(self._injected_t_cos)\n fnorm = self.freq.freq_recentred if f is None else self.freq.normalize(f)\n return self.Tcos_poly(fnorm)\n\n def Tsin(self, f: Optional[Union[float, np.ndarray]] = None): # noqa: N802\n \"\"\"\n Sine noise-wave parameter.\n\n Parameters\n ----------\n f : array-like\n The frequencies at which to evaluate Tsin. By default, the frequencies of\n this instance.\n \"\"\"\n if hasattr(self, \"_injected_t_sin\") and self._injected_t_sin is not None:\n return np.array(self._injected_t_sin)\n fnorm = self.freq.freq_recentred if f is None else self.freq.normalize(f)\n return self.Tsin_poly(fnorm)\n\n @cached_property\n def lna_s11(self):\n \"\"\"The corrected S11 of the LNA evaluated at the data frequencies.\"\"\"\n if hasattr(self, \"_injected_lna_s11\") and self._injected_lna_s11 is not None:\n return self._injected_lna_s11\n else:\n return self.lna.s11_model(self.freq.freq)\n\n def get_linear_coefficients(self, load: Union[Load, str]):\n \"\"\"\n Calibration coefficients a,b such that T = aT* + b (derived from Eq. 7).\n\n Parameters\n ----------\n load : str or :class:`Load`\n The load for which to get the linear coefficients.\n \"\"\"\n if isinstance(load, str):\n load_s11 = self.s11_correction_models[load]\n elif load.load_name in self.s11_correction_models:\n load_s11 = self.s11_correction_models[load.load_name]\n else:\n load_s11 = load.s11_model(self.freq.freq)\n\n return rcf.get_linear_coefficients(\n load_s11,\n self.lna_s11,\n self.C1(self.freq.freq),\n self.C2(self.freq.freq),\n self.Tunc(self.freq.freq),\n self.Tcos(self.freq.freq),\n self.Tsin(self.freq.freq),\n t_load=self.t_load,\n )\n\n def calibrate(self, load: Union[Load, str], q=None, temp=None):\n \"\"\"\n Calibrate the temperature of a given load.\n\n Parameters\n ----------\n load : :class:`Load` or str\n The load to calibrate.\n\n Returns\n -------\n array : calibrated antenna temperature in K, len(f).\n \"\"\"\n load = self._load_str_to_load(load)\n a, b = self.get_linear_coefficients(load)\n\n if q is not None:\n temp = self.t_load_ns * q + self.t_load\n elif temp is None:\n temp = load.averaged_spectrum\n\n return a * temp + b\n\n def _load_str_to_load(self, load: Union[Load, str]):\n if isinstance(load, str):\n try:\n load = self._loads[load]\n except AttributeError:\n raise AttributeError(\n \"load must be a Load object or a string (one of \"\n \"{ambient,hot_load,open,short})\"\n )\n else:\n assert isinstance(\n load, Load\n ), \"load must be a Load instance, got the {} {}\".format(load, type(Load))\n return load\n\n def decalibrate(\n self, temp: np.ndarray, load: Union[Load, str], freq: np.ndarray = None\n ):\n \"\"\"\n Decalibrate a temperature spectrum, yielding uncalibrated T*.\n\n Parameters\n ----------\n temp : array_like\n A temperature spectrum, with the same length as `freq.freq`.\n load : str or :class:`Load`\n The load to calibrate.\n freq : array-like\n The frequencies at which to decalibrate. By default, the frequencies of the\n instance.\n\n Returns\n -------\n array_like : T*, the normalised uncalibrated temperature.\n \"\"\"\n if freq is None:\n freq = self.freq.freq\n\n if freq.min() < self.freq.freq.min():\n warnings.warn(\n \"The minimum frequency is outside the calibrated range \"\n f\"({self.freq.freq.min()} - {self.freq.freq.max()} MHz)\"\n )\n\n if freq.min() > self.freq.freq.max():\n warnings.warn(\"The maximum frequency is outside the calibrated range \")\n\n a, b = self.get_linear_coefficients(load)\n return (temp - b) / a\n\n def get_K(\n self, freq: np.ndarray | None = None\n ) -> Dict[str, Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]:\n \"\"\"Get the source-S11-dependent factors of Monsalve (2017) Eq. 7.\"\"\"\n if freq is None:\n freq = self.freq.freq\n gamma_ants = self.s11_correction_models\n else:\n gamma_ants = {\n name: source.s11_model(freq) for name, source in self._loads.items()\n }\n\n lna_s11 = self.lna.s11_model(freq)\n return {\n name: rcf.get_K(gamma_rec=lna_s11, gamma_ant=gamma_ant)\n for name, gamma_ant in gamma_ants.items()\n }\n\n def plot_calibrated_temp(\n self,\n load: Union[Load, str],\n bins: int = 2,\n fig=None,\n ax=None,\n xlabel=True,\n ylabel=True,\n ):\n \"\"\"\n Make a plot of calibrated temperature for a given source.\n\n Parameters\n ----------\n load : :class:`~LoadSpectrum` instance\n Source to plot.\n bins : int\n Number of bins to smooth over (std of Gaussian kernel)\n fig : Figure\n Optionally provide a matplotlib figure to add to.\n ax : Axis\n Optionally provide a matplotlib Axis to add to.\n xlabel : bool\n Whether to write the x-axis label\n ylabel : bool\n Whether to write the y-axis label\n\n Returns\n -------\n fig :\n The matplotlib figure that was created.\n \"\"\"\n load = self._load_str_to_load(load)\n\n if fig is None and ax is None:\n fig, ax = plt.subplots(1, 1, facecolor=\"w\")\n\n # binning\n temp_calibrated = self.calibrate(load)\n\n if bins > 0:\n freq_ave_cal = convolve(\n temp_calibrated, Gaussian1DKernel(stddev=bins), boundary=\"extend\"\n )\n else:\n freq_ave_cal = temp_calibrated\n freq_ave_cal[np.isinf(freq_ave_cal)] = np.nan\n\n rms = np.sqrt(np.mean((freq_ave_cal - np.mean(freq_ave_cal)) ** 2))\n\n ax.plot(\n self.freq.freq,\n freq_ave_cal,\n label=f\"Calibrated {load.spectrum.load_name} [RMS = {rms:.3f}]\",\n )\n\n temp_ave = self.source_thermistor_temps.get(load.load_name, load.temp_ave)\n\n if not hasattr(temp_ave, \"__len__\"):\n ax.axhline(temp_ave, color=\"C2\", label=\"Average thermistor temp\")\n else:\n ax.plot(\n self.freq.freq,\n temp_ave,\n color=\"C2\",\n label=\"Average thermistor temp\",\n )\n\n ax.set_ylim([np.nanmin(freq_ave_cal), np.nanmax(freq_ave_cal)])\n if xlabel:\n ax.set_xlabel(\"Frequency [MHz]\")\n\n if ylabel:\n ax.set_ylabel(\"Temperature [K]\")\n\n plt.ticklabel_format(useOffset=False)\n ax.grid()\n ax.legend()\n\n return plt.gcf()\n\n def get_load_residuals(self):\n \"\"\"Get residuals of the calibrated temperature for a each load.\"\"\"\n out = {}\n for source in self._sources:\n load = self._load_str_to_load(source)\n cal = self.calibrate(load)\n true = self.source_thermistor_temps[source]\n out[source] = cal - true\n return out\n\n def get_rms(self, smooth: int = 4):\n \"\"\"Return a dict of RMS values for each source.\n\n Parameters\n ----------\n smooth : int\n The number of bins over which to smooth residuals before taking the RMS.\n \"\"\"\n resids = self.get_load_residuals()\n out = {}\n for name, res in resids.items():\n if smooth > 1:\n res = convolve(res, Gaussian1DKernel(stddev=smooth), boundary=\"extend\")\n out[name] = np.sqrt(np.nanmean(res ** 2))\n return out\n\n def plot_calibrated_temps(self, bins=64, fig=None, ax=None):\n \"\"\"\n Plot all calibrated temperatures in a single figure.\n\n Parameters\n ----------\n bins : int\n Number of bins in the smoothed spectrum\n\n Returns\n -------\n fig :\n Matplotlib figure that was created.\n \"\"\"\n if fig is None or ax is None or len(ax) != len(self._sources):\n fig, ax = plt.subplots(\n len(self._sources),\n 1,\n sharex=True,\n gridspec_kw={\"hspace\": 0.05},\n figsize=(10, 12),\n )\n\n for i, source in enumerate(self._sources):\n self.plot_calibrated_temp(\n source,\n bins=bins,\n fig=fig,\n ax=ax[i],\n xlabel=i == (len(self._sources) - 1),\n )\n\n fig.suptitle(\"Calibrated Temperatures for Calibration Sources\", fontsize=15)\n return fig\n\n def write_coefficients(self, path: Optional[str] = None):\n \"\"\"\n Save a text file with the derived calibration co-efficients.\n\n Parameters\n ----------\n path : str\n Directory in which to write the file. The filename starts with\n `All_cal-params` and includes parameters of the class in the filename.\n By default, current directory.\n \"\"\"\n path = Path(path or \".\")\n\n if path.is_dir():\n path /= (\n f\"calibration_parameters_fmin{self.freq.freq.min()}_\"\n f\"fmax{self.freq.freq.max()}_C{self.cterms}_W{self.wterms}.txt\"\n )\n\n np.savetxt(\n path,\n [\n self.freq.freq,\n self.C1(),\n self.C2(),\n self.Tunc(),\n self.Tcos(),\n self.Tsin(),\n ],\n )\n\n def plot_coefficients(self, fig=None, ax=None):\n \"\"\"\n Make a plot of the calibration models, C1, C2, Tunc, Tcos and Tsin.\n\n Parameters\n ----------\n fig : Figure\n Optionally pass a matplotlib figure to add to.\n ax : Axis\n Optionally pass a matplotlib axis to pass to. Must have 5 axes.\n \"\"\"\n if fig is None or ax is None:\n fig, ax = plt.subplots(\n 5, 1, facecolor=\"w\", gridspec_kw={\"hspace\": 0.05}, figsize=(10, 9)\n )\n\n labels = [\n \"Scale ($C_1$)\",\n \"Offset ($C_2$) [K]\",\n r\"$T_{\\rm unc}$ [K]\",\n r\"$T_{\\rm cos}$ [K]\",\n r\"$T_{\\rm sin}$ [K]\",\n ]\n for i, (kind, label) in enumerate(\n zip([\"C1\", \"C2\", \"Tunc\", \"Tcos\", \"Tsin\"], labels)\n ):\n ax[i].plot(self.freq.freq, getattr(self, kind)())\n ax[i].set_ylabel(label, fontsize=13)\n ax[i].grid()\n plt.ticklabel_format(useOffset=False)\n\n if i == 4:\n ax[i].set_xlabel(\"Frequency [MHz]\", fontsize=13)\n\n fig.suptitle(\"Calibration Parameters\", fontsize=15)\n return fig\n\n def invalidate_cache(self):\n \"\"\"Invalidate all cached attributes so they must be recalculated.\"\"\"\n if not hasattr(self, \"_cached_\"):\n return\n\n for cache in self._cached_:\n del self.__dict__[cache]\n\n def update(self, **kwargs):\n \"\"\"Update the class in-place, invalidating the cache as well.\n\n Parameters\n ----------\n kwargs :\n All parameters to be updated.\n \"\"\"\n self.invalidate_cache()\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def write(self, filename: Union[str, Path]):\n \"\"\"\n Write all information required to calibrate a new spectrum to file.\n\n Parameters\n ----------\n filename : path\n The filename to write to.\n \"\"\"\n with h5py.File(filename, \"w\") as fl:\n # Write attributes\n fl.attrs[\"path\"] = str(self.io.original_path)\n fl.attrs[\"cterms\"] = self.cterms\n fl.attrs[\"wterms\"] = self.wterms\n fl.attrs[\"switch_path\"] = str(self.internal_switch.data.path)\n fl.attrs[\"switch_repeat_num\"] = self.internal_switch.data.repeat_num\n fl.attrs[\"switch_resistance\"] = self.internal_switch.resistance\n fl.attrs[\"switch_nterms\"] = self.internal_switch.n_terms[0]\n fl.attrs[\"switch_model\"] = str(self.internal_switch.model)\n fl.attrs[\"t_load\"] = self.open.spectrum.t_load\n fl.attrs[\"t_load_ns\"] = self.open.spectrum.t_load_ns\n\n fl[\"C1\"] = self.C1_poly.coefficients\n fl[\"C2\"] = self.C2_poly.coefficients\n fl[\"Tunc\"] = self.Tunc_poly.coefficients\n fl[\"Tcos\"] = self.Tcos_poly.coefficients\n fl[\"Tsin\"] = self.Tsin_poly.coefficients\n fl[\"frequencies\"] = self.freq.freq\n fl[\"lna_s11_real\"] = self.lna.s11_model(self.freq.freq).real\n fl[\"lna_s11_imag\"] = self.lna.s11_model(self.freq.freq).imag\n\n fl[\"internal_switch_s11_real\"] = np.real(\n self.internal_switch.s11_model(self.freq.freq)\n )\n fl[\"internal_switch_s11_imag\"] = np.imag(\n self.internal_switch.s11_model(self.freq.freq)\n )\n fl[\"internal_switch_s12_real\"] = np.real(\n self.internal_switch.s12_model(self.freq.freq)\n )\n fl[\"internal_switch_s12_imag\"] = np.imag(\n self.internal_switch.s12_model(self.freq.freq)\n )\n fl[\"internal_switch_s22_real\"] = np.real(\n self.internal_switch.s22_model(self.freq.freq)\n )\n fl[\"internal_switch_s22_imag\"] = np.imag(\n self.internal_switch.s22_model(self.freq.freq)\n )\n\n load_grp = fl.create_group(\"loads\")\n\n for name, load in self._loads.items():\n grp = load_grp.create_group(name)\n grp.attrs[\"s11_model\"] = yaml.dump(load.s11_model)\n grp[\"averaged_Q\"] = load.spectrum.averaged_Q\n grp[\"variance_Q\"] = load.spectrum.variance_Q\n grp[\"temp_ave\"] = load.temp_ave\n grp.attrs[\"n_integrations\"] = load.spectrum.n_integrations\n\n def to_calfile(self):\n \"\"\"Directly create a :class:`Calibration` object without writing to file.\"\"\"\n return Calibration.from_calobs(self)\n\n def inject(\n self,\n lna_s11: np.ndarray = None,\n source_s11s: Dict[str, np.ndarray] = None,\n c1: np.ndarray = None,\n c2: np.ndarray = None,\n t_unc: np.ndarray = None,\n t_cos: np.ndarray = None,\n t_sin: np.ndarray = None,\n averaged_spectra: Dict[str, np.ndarray] = None,\n thermistor_temp_ave: Dict[str, np.ndarray] = None,\n ) -> CalibrationObservation:\n \"\"\"Make a new :class:`CalibrationObservation` based on this, with injections.\n\n Parameters\n ----------\n lna_s11\n The LNA S11 as a function of frequency to inject.\n source_s11s\n Dictionary of ``{source: S11}`` for each source to inject.\n c1\n Scaling parameter as a function of frequency to inject.\n c2 : [type], optional\n Offset parameter to inject as a function of frequency.\n t_unc\n Uncorrelated temperature to inject (as function of frequency)\n t_cos\n Correlated temperature to inject (as function of frequency)\n t_sin\n Correlated temperature to inject (as function of frequency)\n averaged_spectra\n Dictionary of ``{source: spectrum}`` for each source to inject.\n\n Returns\n -------\n :class:`CalibrationObservation`\n A new observation object with the injected models.\n \"\"\"\n new = copy(self)\n new.invalidate_cache()\n new._injected_lna_s11 = lna_s11\n new._injected_source_s11s = source_s11s\n new._injected_c1 = c1\n new._injected_c2 = c2\n new._injected_t_unc = t_unc\n new._injected_t_cos = t_cos\n new._injected_t_sin = t_sin\n new._injected_averaged_spectra = averaged_spectra\n new._injected_source_temps = thermistor_temp_ave\n\n return new\n\n\[email protected]\nclass _LittleS11:\n s11_model: Callable = attr.ib()\n\n\[email protected]\nclass _LittleSpectrum:\n averaged_Q: np.ndarray = attr.ib()\n variance_Q: np.ndarray = attr.ib()\n n_integrations: int = attr.ib()\n\n\[email protected]\nclass _LittleLoad:\n reflections: _LittleS11 = attr.ib()\n spectrum: _LittleSpectrum = attr.ib()\n temp_ave: np.ndarray = attr.ib()\n\n\nclass Calibration:\n def __init__(self, filename: Union[str, Path]):\n \"\"\"\n A class defining an interface to a HDF5 file containing calibration information.\n\n Parameters\n ----------\n filename : str or Path\n The path to the calibration file.\n \"\"\"\n self.calfile = Path(filename)\n\n with h5py.File(filename, \"r\") as fl:\n self.calobs_path = fl.attrs[\"path\"]\n self.cterms = int(fl.attrs[\"cterms\"])\n self.wterms = int(fl.attrs[\"wterms\"])\n self.t_load = fl.attrs.get(\"t_load\", 300)\n self.t_load_ns = fl.attrs.get(\"t_load_ns\", 400)\n\n self.C1_poly = np.poly1d(fl[\"C1\"][...])\n self.C2_poly = np.poly1d(fl[\"C2\"][...])\n self.Tcos_poly = np.poly1d(fl[\"Tcos\"][...])\n self.Tsin_poly = np.poly1d(fl[\"Tsin\"][...])\n self.Tunc_poly = np.poly1d(fl[\"Tunc\"][...])\n\n self.freq = FrequencyRange(fl[\"frequencies\"][...])\n\n self._loads = {}\n if \"loads\" in fl:\n lg = fl[\"loads\"]\n\n self.load_names = list(lg.keys())\n\n for name, grp in lg.items():\n self._loads[name] = _LittleLoad(\n reflections=_LittleS11(\n s11_model=yaml.load(\n grp.attrs[\"s11_model\"], Loader=yaml.FullLoader\n ).at(x=self.freq.freq)\n ),\n spectrum=_LittleSpectrum(\n averaged_Q=grp[\"averaged_Q\"][...],\n variance_Q=grp[\"variance_Q\"][...],\n n_integrations=grp.attrs[\"n_integrations\"],\n ),\n temp_ave=grp[\"temp_ave\"][...],\n )\n\n self._lna_s11_rl = Spline(self.freq.freq, fl[\"lna_s11_real\"][...])\n self._lna_s11_im = Spline(self.freq.freq, fl[\"lna_s11_imag\"][...])\n\n self._intsw_s11_rl = Spline(\n self.freq.freq, fl[\"internal_switch_s11_real\"][...]\n )\n self._intsw_s11_im = Spline(\n self.freq.freq, fl[\"internal_switch_s11_imag\"][...]\n )\n self._intsw_s12_rl = Spline(\n self.freq.freq, fl[\"internal_switch_s12_real\"][...]\n )\n self._intsw_s12_im = Spline(\n self.freq.freq, fl[\"internal_switch_s12_imag\"][...]\n )\n self._intsw_s22_rl = Spline(\n self.freq.freq, fl[\"internal_switch_s22_real\"][...]\n )\n self._intsw_s22_im = Spline(\n self.freq.freq, fl[\"internal_switch_s22_imag\"][...]\n )\n\n @classmethod\n def from_calobs(cls, calobs: CalibrationObservation) -> Calibration:\n \"\"\"Generate a :class:`Calibration` from an in-memory observation.\"\"\"\n tmp = tempfile.mktemp()\n calobs.write(tmp)\n return cls(tmp)\n\n def lna_s11(self, freq=None):\n \"\"\"Get the LNA S11 at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self._lna_s11_rl(freq) + 1j * self._lna_s11_im(freq)\n\n def internal_switch_s11(self, freq=None):\n \"\"\"Get the S11 of the internal switch at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self._intsw_s11_rl(freq) + 1j * self._intsw_s11_im(freq)\n\n def internal_switch_s12(self, freq=None):\n \"\"\"Get the S12 of the internal switch at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self._intsw_s12_rl(freq) + 1j * self._intsw_s12_im(freq)\n\n def internal_switch_s22(self, freq=None):\n \"\"\"Get the S22 of the internal switch at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self._intsw_s22_rl(freq) + 1j * self._intsw_s22_im(freq)\n\n def C1(self, freq=None):\n \"\"\"Evaluate the Scale polynomial at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self.C1_poly(self.freq.normalize(freq))\n\n def C2(self, freq=None):\n \"\"\"Evaluate the Offset polynomial at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self.C2_poly(self.freq.normalize(freq))\n\n def Tcos(self, freq=None):\n \"\"\"Evaluate the cos temperature polynomial at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self.Tcos_poly(self.freq.normalize(freq))\n\n def Tsin(self, freq=None):\n \"\"\"Evaluate the sin temperature polynomial at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self.Tsin_poly(self.freq.normalize(freq))\n\n def Tunc(self, freq=None):\n \"\"\"Evaluate the uncorrelated temperature polynomial at given frequencies.\"\"\"\n if freq is None:\n freq = self.freq.freq\n return self.Tunc_poly(self.freq.normalize(freq))\n\n def _linear_coefficients(self, freq, ant_s11):\n return rcf.get_linear_coefficients(\n ant_s11,\n self.lna_s11(freq),\n self.C1(freq),\n self.C2(freq),\n self.Tunc(freq),\n self.Tcos(freq),\n self.Tsin(freq),\n self.t_load,\n )\n\n def calibrate_temp(self, freq: np.ndarray, temp: np.ndarray, ant_s11: np.ndarray):\n \"\"\"\n Calibrate given uncalibrated spectrum.\n\n Parameters\n ----------\n freq : np.ndarray\n The frequencies at which to calibrate\n temp : np.ndarray\n The temperatures to calibrate (in K).\n ant_s11 : np.ndarray\n The antenna S11 for the load.\n\n Returns\n -------\n temp : np.ndarray\n The calibrated temperature.\n \"\"\"\n a, b = self._linear_coefficients(freq, ant_s11)\n return temp * a + b\n\n def decalibrate_temp(self, freq, temp, ant_s11):\n \"\"\"\n De-calibrate given calibrated spectrum.\n\n Parameters\n ----------\n freq : np.ndarray\n The frequencies at which to calibrate\n temp : np.ndarray\n The temperatures to calibrate (in K).\n ant_s11 : np.ndarray\n The antenna S11 for the load.\n\n Returns\n -------\n temp : np.ndarray\n The calibrated temperature.\n\n Notes\n -----\n Using this and then :method:`calibrate_temp` immediately should be an identity\n operation.\n \"\"\"\n a, b = self._linear_coefficients(freq, ant_s11)\n return (temp - b) / a\n\n def calibrate_Q(\n self, freq: np.ndarray, q: np.ndarray, ant_s11: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n Calibrate given power ratio spectrum.\n\n Parameters\n ----------\n freq : np.ndarray\n The frequencies at which to calibrate\n q : np.ndarray\n The power ratio to calibrate.\n ant_s11 : np.ndarray\n The antenna S11 for the load.\n\n Returns\n -------\n temp : np.ndarray\n The calibrated temperature.\n \"\"\"\n uncal_temp = self.t_load_ns * q + self.t_load\n\n return self.calibrate_temp(freq, uncal_temp, ant_s11)\n\n\ndef perform_term_sweep(\n calobs: CalibrationObservation,\n delta_rms_thresh: float = 0,\n max_cterms: int = 15,\n max_wterms: int = 15,\n explore_run_nums: bool = False,\n explore_repeat_nums: bool = False,\n direc=\".\",\n verbose=False,\n) -> CalibrationObservation:\n \"\"\"For a given calibration definition, perform a sweep over number of terms.\n\n There are options to save _every_ calibration solution, or just the \"best\" one.\n\n Parameters\n ----------\n calobs: :class:`CalibrationObservation` instance\n The definition calibration class. The `cterms` and `wterms` in this instance\n should define the *lowest* values of the parameters to sweep over.\n delta_rms_thresh : float\n The threshold in change in RMS between one set of parameters and the next that\n will define where to cut off. If zero, will run all sets of parameters up to\n the maximum terms specified.\n max_cterms : int\n The maximum number of cterms to trial.\n max_wterms : int\n The maximum number of wterms to trial.\n explore_run_nums : bool\n Whether to iterate over S11 run numbers to find the best residuals.\n explore_repeat_nums : bool\n Whether to iterate over S11 repeat numbers to find the best residuals.\n direc : str\n Directory to write resultant :class:`Calibration` file to.\n verbose : bool\n Whether to write out the RMS values derived throughout the sweep.\n\n Notes\n -----\n When exploring run/repeat nums, run nums are kept constant within a load (i.e. the\n match/short/open etc. all have either run_num=1 or run_num=2 for the same load.\n This is physically motivated.\n \"\"\"\n cterms = range(calobs.cterms, max_cterms)\n wterms = range(calobs.wterms, max_wterms)\n\n winner = np.zeros(len(cterms), dtype=int)\n\n s11_keys = [\"switching_state\", \"receiver_reading\"] + list(io.LOAD_ALIASES.keys())\n if explore_repeat_nums:\n # Note that we don't explore run_nums for spectra/resistance, because it's rare\n # to have those, and they'll only exist if one got completely botched (and that\n # should be set by the user).\n rep_num = {\n k: range(1, getattr(calobs.io.s11, k).max_repeat_num + 1) for k in s11_keys\n }\n else:\n rep_num = {k: [getattr(calobs.io.s11, k).repeat_num] for k in s11_keys}\n\n rep_num = tools.dct_of_list_to_list_of_dct(rep_num)\n\n if explore_run_nums:\n run_num = {\n \"switching_state\": range(\n 1, calobs.io.s11.get_highest_run_num(\"SwitchingState\") + 1\n ),\n \"receiver_reading\": range(\n 1, calobs.io.s11.get_highest_run_num(\"ReceiverReading\") + 1\n ),\n }\n else:\n run_num = {\n \"switching_state\": [calobs.io.s11.switching_state.run_num],\n \"receiver_reading\": [calobs.io.s11.receiver_reading.run_num],\n }\n\n run_num = tools.dct_of_list_to_list_of_dct(run_num)\n\n best_rms = np.inf\n for this_rep_num in rep_num:\n for this_run_num in run_num:\n\n tmp_run_num = copy(calobs.io.run_num)\n tmp_run_num.update(this_run_num)\n\n # Change the base io.CalObs because it will change with rep/run.\n calobs.io = io.CalibrationObservation(\n path=calobs.io.path,\n run_num=tmp_run_num,\n repeat_num=this_rep_num,\n fix=False,\n compile_from_def=calobs.compiled_from_def,\n include_previous=calobs.previous_included,\n )\n\n calobs.lna = LNA(\n calobs.io.s11.receiver_reading,\n f_low=calobs.freq.min,\n f_high=calobs.freq.max,\n resistance=calobs.lna.resistance,\n )\n\n # If we're changing anything else, we need to change each load.\n for name, load in calobs._loads.items():\n load.reflections = LoadS11.from_path(\n load_name=name,\n path=calobs.io.path,\n repeat_num_load=this_rep_num[name],\n run_num_switch=this_run_num[\"switching_state\"],\n repeat_num_switch=this_rep_num[\"switching_state\"],\n )\n\n if verbose:\n print(\n f\"SWEEPING SwSt={calobs.io.s11.switching_state.repeat_num}, \"\n f\"RcvRd={calobs.io.s11.receiver_reading.repeat_num} \"\n f\"[Sw={calobs.io.s11.switching_state.run_num}, \"\n f\"RR={calobs.io.s11.receiver_reading.run_num}, \"\n f\"open={calobs.io.s11.open.run_num}, \"\n f\"short={calobs.io.s11.short.run_num}, \"\n f\"ambient={calobs.io.s11.ambient.run_num}, \"\n f\"hot={calobs.io.s11.hot_load.run_num}]\"\n )\n print(\"-\" * 30)\n\n rms = np.zeros((len(cterms), len(wterms)))\n for i, c in enumerate(cterms):\n for j, w in enumerate(wterms):\n calobs.update(cterms=c, wterms=w)\n res = calobs.get_load_residuals()\n dof = sum(len(r) for r in res.values()) - c - w\n\n rms[i, j] = np.sqrt(\n sum(np.nansum(np.square(x)) for x in res.values()) / dof\n )\n\n if verbose:\n print(f\"Nc = {c:02}, Nw = {w:02}; RMS/dof = {rms[i, j]:1.3e}\")\n\n # If we've decreased by more than the threshold, this wterms becomes\n # the new winner (for this number of cterms)\n if j > 0 and rms[i, j] >= rms[i, j - 1] - delta_rms_thresh:\n winner[i] = j - 1\n break\n\n if (\n i > 0\n and rms[i, winner[i]]\n >= rms[i - 1, winner[i - 1]] - delta_rms_thresh\n ):\n break\n\n if verbose:\n print(\n f\"Best parameters found for Nc={cterms[i-1]}, \"\n f\"Nw={wterms[winner[i-1]]}, \"\n f\"with RMS = {rms[i-1, winner[i-1]]}.\"\n )\n print()\n\n if rms[i - 1, winner[i - 1]] < best_rms:\n best_run_combo = (\n calobs.io.run_num,\n calobs.io.s11.receiver_reading.repeat_num,\n calobs.io.s11.switching_state.repeat_num,\n )\n best_cterms = cterms[i - 1]\n best_wterms = wterms[winner[i - 1]]\n\n if verbose and (explore_repeat_nums or explore_run_nums):\n print(\"The very best parameters were found were for:\")\n print(f\"\\tSwitchingState Repeat = {best_run_combo[2]}\")\n print(f\"\\tReceiverReading Repeat = {best_run_combo[1]}\")\n print(f\"\\tRun Numbers = {best_run_combo[0]}\")\n print(f\"\\t# C-terms = {best_cterms}\")\n print(f\"\\t# W-terms = {best_wterms}\")\n\n calobs.update(cterms=best_cterms, wterms=best_wterms)\n calobs.io = io.CalibrationObservation(\n path=calobs.io.path,\n run_num=best_run_combo[0],\n repeat_num={\n \"switching_state\": best_run_combo[2],\n \"receiver_reading\": best_run_combo[1],\n },\n fix=False,\n compile_from_def=calobs.compiled_from_def,\n include_previous=calobs.previous_included,\n )\n\n calobs.lna = LNA(\n calobs.io.s11.receiver_reading,\n f_low=calobs.freq.min,\n f_high=calobs.freq.max,\n resistance=calobs.lna.resistance,\n )\n\n if direc is not None:\n direc = Path(direc)\n if not direc.exists():\n direc.mkdir(parents=True)\n\n pth = Path(calobs.path).parent.name\n\n pth = str(pth) + f\"_c{calobs.cterms}_w{calobs.wterms}.h5\"\n calobs.write(direc / pth)\n\n return calobs\n" ]
[ [ "numpy.nanmax", "numpy.poly1d", "numpy.sqrt", "numpy.nanmin", "numpy.mean", "numpy.nanmean", "numpy.square", "numpy.ones_like", "scipy.interpolate.InterpolatedUnivariateSpline", "numpy.nanvar", "matplotlib.pyplot.gcf", "numpy.isnan", "numpy.genfromtxt", "matplotlib.pyplot.ticklabel_format", "numpy.array", "numpy.abs", "matplotlib.pyplot.subplots", "numpy.angle", "numpy.isinf" ] ]
[ { "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": [] } ]
aivision2020/OctSceneScan
[ "3b22ecb4f701270f457a7c2d2702f758b8d584cf" ]
[ "test_module.py" ]
[ "from pathlib import Path\nimport copy\nimport time\nimport torch.optim as optim\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom model import *\nfrom data_utils import *\nimport torch.nn as nn\nfrom loguru import logger\n\nfeature_dim = 8\nblock_size = 16\npad=2\nn_conv=3\nthresh=0.5\ndebug = False\n\ndef test_bottom_io():\n tsdf = [torch.from_numpy(np.random.rand(1, 1, block_size+2*pad+2*n_conv,\n block_size+2*pad+2*n_conv,\n block_size+2*pad+2*n_conv)).float().to(device)]\n prev = {(0, 0, 0): torch.from_numpy(np.random.rand(1, feature_dim,\n block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad)\n ).float().to(device)}\n mod = BottomLevel(feature_dim, block_size=block_size)\n if device == 'cuda':\n mod.cuda()\n out = mod(tsdf, prev)\n assert type(out) == list\n assert len(out) == 1\n out = out[0]\n assert len(out) == 1\n for X in out.keys():\n assert out[X].shape == (1, 2, block_size, block_size, block_size), out[X].shape\n\n\ndef test_convtrans():\n conv1 = nn.ConvTranspose3d(10, 10, kernel_size=4, stride=2, output_padding=0, padding=0, bias=False)\n dat = torch.ones(1, 10, block_size, block_size, block_size)\n y = conv1(dat)\n assert y.shape[-1] == block_size*2+2 , (y.shape, dat.shape)\n\n pad = nn.ReplicationPad3d(1)\n conv1 = nn.ConvTranspose3d(1, 1, kernel_size=3, stride=2,\n output_padding=1, padding=1, bias=False)\n dat = Variable(torch.ones(1, 1, 4, 4, 4))\n y = conv1(dat)\n assert y.shape[-1] == 8, y.shape\n\n\ndef test_data():\n data = TsdfGenerator(64)\n vis = visdom.Visdom()\n gt, tsdf_in = data.__getitem__(0)\n assert np.abs(tsdf_in).max() < 33\n\n\ndef test_ellipsoid():\n arr = ellipsoid(10, 10, 10, levelset=True)*10 # the output is ~normalized. multiple by 10\n assert arr.shape == (23, 23, 23), arr.shape\n dist = np.sqrt(11**2*3)-10\n assert np.abs(arr[0, 0, 0]) > dist, (arr[0, 0, 0], dist)\n print(arr[0, 0, 0], dist)\n\n a, b, c = 10, 15, 25\n arr = ellipsoid(a, b, c, levelset=True)\n # if we move 1 voxel in space the sdf should also not change by more than 1\n # compare to 1.01 for numeric reasons\n assert np.all(np.abs(np.diff(arr, axis=0)) <= 1.01), np.abs(np.diff(arr, axis=0)).max()\n assert np.all(np.abs(np.diff(arr, axis=1)) <= 1.01)\n assert np.all(np.abs(np.diff(arr, axis=2)) <= 1.01)\n\n\ndef test_criteria_trivial():\n data = TsdfGenerator(block_size, sigma=0.)\n gt, tsdf_in = data.__getitem_split__()\n gt = gt[None, :] # add dim for batch\n assert np.abs(tsdf_in).max() < 33\n gt_label = np.zeros_like(gt)\n gt_label[gt >= 0] = 1\n gt_label = torch.from_numpy(gt_label.astype(int))\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n assert len(criteria.gt_octree) == 1\n mock_out = np.concatenate((tsdf_in[None,:]<0, tsdf_in[None,:]>=0),\n axis=1).astype(float)\n mock_out=1000*(mock_out-0.5)\n mock_out = [{(0,0,0):torch.from_numpy(mock_out).float()}]\n loss = criteria(mock_out)\n assert loss.dim()==0\n assert loss < 0.01, loss\n\ndef test_gt():\n pass\n #get gt, \n #get gt_octree\n #retnder gt\n #render gt_octree\n\ndef test_criteria(levels=2):\n res=2**(levels-1)*block_size\n data = TsdfGenerator(res, sigma=0.9)\n gt, tsdf_in = data.__getitem_split__()\n gt = gt[None, :] # add dim for batch\n assert np.abs(tsdf_in).max() < res\n #labels should be symetric\n def count_label(gt, label, level=1):\n gt_label = np.zeros_like(gt)\n gt_label[gt >= 0] = 1\n gt_label = torch.from_numpy(gt_label.astype(int))\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n gt=criteria.gt_octree[level]\n return np.count_nonzero(np.array(list(gt.values()))==label)\n\n n_outside = count_label(gt, OUTSIDE)\n n_inside = count_label(gt, INSIDE)\n n_mixed = count_label(gt, MIXED)\n assert n_outside+n_inside+n_mixed==(2**(levels-2))**3\n rev_inside = count_label(-gt, OUTSIDE)\n assert n_inside==rev_inside, (n_inside, rev_inside)\n\n\n gt_label = np.zeros_like(gt)\n gt_label[gt >= 0] = 1\n gt_label = torch.from_numpy(gt_label.astype(int))\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n assert len(criteria.gt_octree) == levels\n assert len(criteria.gt_octree[0]) == (2**(levels-1))**3, len(criteria.gt_octree[0])\n assert len(criteria.gt_octree[-1]) == 1, len(criteria.gt_octree[-1])\n for l, level in enumerate(criteria.gt_octree):\n for k, v in level.items():\n assert v.dim() > 0, (l, k, v)\n\n\ndef test_basic_debug():\n T = torch.zeros(1,1,36,36,36)\n outplane = 16\n mod = nn.Conv3d(1, outplane, kernel_size=3, stride=1,\n padding=0, bias=False)\n T = mod(T)\n mod = nn.BatchNorm3d(outplane)\n T = mod(T)\n mod = nn.ReLU(inplace=True)\n T = mod(T)\n mod = nn.Conv3d(outplane, outplane, kernel_size=3, stride=1, \n padding=0, bias=False)\n T = mod(T)\n mod = nn.BatchNorm3d(outplane)\n T = mod(T)\n assert T.shape == (1,16,32,32,32)\n\n\ndef test_simple_net_single_data():\n data = TsdfGenerator(block_size, sigma=0.9)\n vis = visdom.Visdom()\n gt, tsdf_in = data.__getitem__(0)\n gt = gt[None, :] # add dim for batch\n assert np.abs(tsdf_in).max() < block_size\n gt_label = np.zeros_like(gt)\n gt_label[gt >= 0] = 1\n gt_label = torch.from_numpy(gt_label.astype(int)).to(device)\n rep_pad = nn.ReplicationPad3d(pad+n_conv)\n tsdf = [rep_pad(torch.from_numpy(copy.copy(tsdf_in)[None, :]).float().to(device))]\n #prev = {(0, 0, 0): torch.rand(1, feature_dim, block_size//2, block_size//2,\n # block_size//2).float().to(device)}\n prev = {(0, 0, 0): torch.from_numpy(np.random.rand(1, feature_dim,\n block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad)\n ).float().to(device)}\n #assert tsdf[0].shape == (1, 1, block_size, block_size, block_size)\n assert gt_label.shape == (1, block_size, block_size, block_size)\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n mod = BottomLevel(feature_dim, block_size)\n if device=='cuda':\n mod.cuda()\n criteria.cuda()\n optimizer = optim.Adam(mod.parameters(), lr=0.001) # , momentum=0.9)\n for it in range(1, 100):\n out = mod(tsdf, prev)\n assert len(out) == 1\n assert out[0][(0,0,0)].shape[1] == 2, out.shape\n loss = criteria(out)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if (it+1) % 10 == 0:\n sdf_ = octree_to_sdf(out, block_size)\n print('level ', np.count_nonzero(sdf_ == 1))\n err = plotVoxelVisdom(gt[0], sdf_, tsdf_in[0], vis)\n assert np.abs(tsdf_in).max() < 33\n print(err)\n\n print(it, loss)\n assert err < 2\n\n\ndef test_bottom_layer( block_size = 32):\n dataset = TsdfGenerator(block_size, n_elips=1, sigma=0.9, epoch_size=1000)\n train_loader = torch.utils.data.DataLoader(dataset, batch_size=1,\n num_workers=4)\n\n vis = visdom.Visdom()\n mod = BottomLevel(feature_dim, block_size)\n if device=='cuda':\n mod.cuda()\n optimizer = optim.SGD(mod.parameters(), lr=0.0001, momentum=0.9)\n m = nn.ReplicationPad3d(mod.pad+mod.n_conv)\n prev = {(0, 0, 0): torch.rand(1, feature_dim,\n block_size//2+2*pad, block_size//2+2*pad, block_size//2+2*pad\n ).float().to(device)}\n gt_label = None\n for it, (gt, tsdf_in) in enumerate(train_loader):\n assert np.abs(tsdf_in).max() < 33\n assert gt.max() > 1 and gt.min() < -1\n gt_label = torch.ones_like(gt)*INSIDE\n gt_label[gt >= 0] = OUTSIDE\n gt_label = gt_label.long().to(device)\n tsdf = [m(tsdf_in).float().to(device)]\n for T in prev.values():\n assert torch.all(torch.isfinite(T))\n for T in tsdf:\n assert torch.all(torch.isfinite(T))\n out = mod(tsdf, prev)\n assert out[0][(0,0,0)].max()>out[0][(0,0,0)].min()\n for oct in out:\n if not np.all([torch.all(torch.isfinite(o)) for o in oct.values()]):\n import ipdb; ipdb.set_trace()\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n if device=='cuda':\n criteria.cuda()\n loss = criteria(out)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print(it, loss)\n if it>1 and it%100 == 0:\n sdf_ = octree_to_sdf(out, block_size)\n err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)\n print(it, err)\n assert err < 2, err\n\n\ndef test_2tier_net_single_data():\n res = block_size*2\n dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=100)\n\n vis = visdom.Visdom()\n mod = TopLevel(feature_dim, BottomLevel(feature_dim, block_size), block_size=block_size)\n if device == 'cuda':\n mod.cuda()\n\n optimizer = optim.Adam(mod.parameters(), lr=0.01)#, momentum=0.9)\n gt, tsdf_in = dataset.__getitem__(0)\n assert np.abs(tsdf_in).max() < 33\n assert gt.max() > 1 and gt.min() < -1\n gt = torch.from_numpy(gt[None, :])\n gt_label = torch.zeros_like(gt)\n gt_label[gt >= 0] = 1\n gt_label = gt_label.long().to(device)\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n if device == 'cuda':\n criteria.cuda()\n tsdf = torch.from_numpy(copy.copy(tsdf_in)[None, :]).float().to(device)\n for it in range(1000):\n out = mod(tsdf)\n assert len(out) == 2\n for l in out[1:]:\n for v in l.values():\n # only level 0 can have a full bloc\n assert v.shape[-1] < block_size, (v.shape)\n loss = criteria(out)\n assert len(out) == 2\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print(it, loss)\n if (it+1) % 10 == 0:\n #mod.eval()\n sdf_ = octree_to_sdf(out, block_size)\n err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0], vis)\n #mod.train()\n print(it, err)\n assert err < 2,err\n\n\ndef test_4tier_data(block_size=block_size):\n res=block_size*(2**3)\n dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=1000)\n gt, tsdf = dataset.__getitem__(0)\n\n mod = BottomLevel(feature_dim, block_size)\n for i in range(2): #add 2 mid layers\n print('adding mid layer')\n mod = MidLevel(feature_dim, feature_dim, mod, block_size,\n thresh=thresh, budget=4)\n mod = TopLevel(feature_dim, mod, block_size=block_size)\n out = mod(torch.from_numpy(tsdf[None,:]).float())\n\n\n\ndef test_2tier_net(res=64, block_size=block_size):\n dataset = TsdfGenerator(res, n_elips=1, sigma=0.9, epoch_size=10000, debug=False)\n train_loader = torch.utils.data.DataLoader(dataset, batch_size=1,\n num_workers=2)\n\n vis = visdom.Visdom()\n Force = False\n if not Force and Path('model_2tier.pth').exists():\n mod = torch.load('model_2tier.pth')\n else:\n layers = []\n layers.append(BottomLevel(feature_dim, block_size))\n while block_size*2**len(layers) <= res/2:\n print('adding mid layer', len(layers))\n layers.append(MidLevel(feature_dim, feature_dim, layers[-1],\n block_size, thresh=0.5, budget=4))\n mod = TopLevel(feature_dim, layers[-1], block_size=block_size)\n if device == 'cuda':\n mod.cuda()\n optimizer = optim.SGD(mod.parameters(), lr=0.0001, momentum=0.95)\n for it, (gt, tsdf_in) in enumerate(train_loader):\n assert np.abs(tsdf_in).max() < res\n assert gt.max() > 1 and gt.min() < -1\n gt_label = torch.zeros_like(gt, device=device)\n gt_label[gt >= 0] = 1\n gt_label = gt_label.long().to(device)\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n if device == 'cuda':\n criteria.cuda()\n #tsdf = tsdf_in.float().cuda()\n t_start = time.time()\n tsdf = tsdf_in.float().to(device)\n pred = mod(tsdf)\n forward_t = time.time()-t_start\n t = time.time()\n loss = criteria(pred)\n loss_t = time.time()-t\n t = time.time()\n optimizer.zero_grad()\n loss.backward()\n back_t = time.time()-t\n t = time.time()\n optimizer.step()\n step_t = time.time()-t\n t = time.time()\n print(it, loss.data)\n print('valuated ', [len(o) for o in pred])\n print('GT voxels ', np.count_nonzero([o.numel()>3 for o in criteria.gt_octree]))\n print('timing:{total:.3f}. forward {forward_t:.3f}, loss {loss_t:.3f}, back {back_t:.3f}, step {step_t:.3f}'.format(\n total=t-t_start, forward_t=forward_t, loss_t=loss_t, back_t=back_t, step_t=step_t))\n if (it+1) % 100 == 0:\n mod.eval()\n out = mod(tsdf)\n loss = criteria(out)\n for i in range(len(out)):\n resample = (2**i)\n print('Eval: level %d, %d/%d evaluated' % (i, len(out[i]),\n (res/block_size/resample)**3))\n sdf_ = octree_to_sdf(out, block_size)\n err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)\n if loss.data<1:\n import ipdb; ipdb.set_trace()\n mod.train()\n print(it, err)\n torch.save(mod, 'model_2tier.pth')\n if err < 2 :\n break\n #assert err < 2\n\ndef create_model(block_size, feature_dim, res):\n layers = []\n layers.append(BottomLevel(feature_dim, block_size))\n while block_size*2**len(layers) <= res/2:\n print('adding mid layer', len(layers))\n layers.append(MidLevel(feature_dim, feature_dim, layers[-1],\n block_size, thresh=0.1))\n mod = TopLevel(feature_dim, layers[-1], block_size=block_size)\n return mod\n\n\ndef test_simple_split(res=64, block_size=block_size):\n dataset = TsdfGenerator(res, n_elips=3, sigma=0.9, epoch_size=1000, debug=True)\n vis = visdom.Visdom()\n\n mod = torch.load('model.pth')\n if device == 'cuda':\n mod.cuda()\n mod.eval()\n gt, tsdf_in = dataset.__getitem_split__()\n gt = torch.from_numpy(gt[None, :])\n tsdf_in = torch.from_numpy(tsdf_in[None, :])\n\n gt_label = torch.zeros_like(gt, device=device)\n gt_label[gt >= 0] = 1\n gt_label = gt_label.long().to(device)\n criteria = OctreeCrossEntropyLoss(gt_label, block_size)\n if device == 'cuda':\n criteria.cuda()\n tsdf = tsdf_in.float().to(device)\n pred = mod(tsdf)\n loss = criteria(pred)\n print(loss.data)\n print('evaluated ', [len(o) for o in pred])\n\n for X in pred[0]:\n X_ = tuple(np.array(X)//2)\n print (X, pred[1][X_])\n assert pred[1][X_][0,2]>0.5\n sdf_ = octree_to_sdf(pred, block_size)\n err = plotVoxelVisdom(gt[0].numpy(), sdf_, tsdf_in[0][0].numpy(), vis)\n import ipdb; ipdb.set_trace()\n for X,v in criteria.gt_octree[0].items():\n if v.numel()>1:\n assert X[2]==1 #that's how we built the space\n\n\ndef test_split_subtree(padding=0):\n feat = torch.rand(1, feature_dim, block_size+2*padding,\n block_size+2*padding,\n block_size+2*padding\n ).float()\n split = split_tree(feat,padding=padding)\n assert len(split) == 8, len(split)\n assert torch.all(split[(0, 0, 0)][0, :, padding, padding, padding] ==\n feat[0, :, padding, padding, padding])\n assert torch.all(split[(1, 0, 0)][0, :, padding, padding, padding] ==\n feat[0, :, block_size//2+padding, padding, padding])\n split[(1, 0, 0)][0, 0, padding, padding, padding] = 12.13\n #this is no longer true, I don't know how to do this inplace\n #assert feat[0, 0, block_size//2, 0, 0] == 12.13\n\ndef test_split_subtree_with_padding():\n padding=2\n feat = torch.rand(1, feature_dim, block_size, block_size,\n block_size).float()\n split = split_tree(feat, padding=2)\n assert len(split) == 8, len(split)\n octant = split[(0,0,0)]\n assert torch.all(octant[0, :padding, 0, 0, 0] == 0)\n assert torch.all(octant[0, -padding:, 0, 0, 0] == 0)\n assert octant.shape[-3:]==feat.shape[-3:]//2+padding*2\n assert torch.all(octant[0, padding:-padding, 0, 0, 0] == feat[0, :, 0, 0, 0])\n assert torch.all(octant[0, padding:-padding, 0, 0, 0] == feat[0, :, 0, 0, 0])\n assert torch.all(split[(1, 0, 0)][0, :, padding, padding, padding] ==\n feat[0, :, block_size//2, 0, 0])\n split[(1, 0, 0)][0, 0, 0, 0, 0] = 12.13\n assert feat[0, 0, block_size//2+padding, 0, 0] == 12.13\n\nif __name__ == '__main__':\n import sys\n logger.remove()\n logger.add(sys.stderr , format=\"{time} {level} {message}\", level=\"INFO\")\n\n #test_4tier_data()\n #test_criteria_trivial()\n #test_criteria()\n #test_criteria(4)\n #test_data()\n #test_ellipsoid()\n #test_convtrans()\n #test_split_subtree()\n #test_split_subtree(padding=2)\n #test_basic_debug()\n #test_bottom_io()\n #test_simple_net_single_data()\n #test_bottom_layer()\n # TODO why does this not converge? interesting\n #test_2tier_net_single_data()\n #test_2tier_net(res=32, block_size=block_size)\n test_2tier_net(res=64, block_size=block_size)\n test_simple_split(res=64, block_size=block_size)\n import ipdb; ipdb.set_trace()\n test_2tier_net(res=128, block_size=block_size)\n" ]
[ [ "torch.all", "numpy.sqrt", "torch.nn.ReplicationPad3d", "torch.zeros", "torch.load", "torch.utils.data.DataLoader", "numpy.concatenate", "numpy.zeros_like", "torch.save", "torch.ones", "torch.from_numpy", "torch.isfinite", "numpy.diff", "torch.rand", "numpy.count_nonzero", "torch.ones_like", "torch.zeros_like", "torch.nn.Conv3d", "numpy.random.rand", "numpy.array", "numpy.abs", "torch.nn.ConvTranspose3d", "torch.nn.ReLU", "torch.nn.BatchNorm3d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
soumitrasamanta/FragGenie
[ "9ce493d88e3479a286ce88dc0c5b199ea7c7e441" ]
[ "fragment.py" ]
[ "\"\"\"\n-----------------------------------------------------------------------------\nAUTHOR: Soumitra Samanta ([email protected])\n-----------------------------------------------------------------------------\n\"\"\"\n\nimport subprocess\nimport os\nimport numpy as np\nfrom datetime import datetime\nimport pandas as pd\n\nfrom rdkit import Chem\nfrom rdkit.Chem import Descriptors\n\n__all__ = [\n 'FragGenie'\n]\n\nclass FragGenie():\n \n def __init__(self, dir_fraggenie=''):\n \n self.dir_fraggenie = dir_fraggenie\n \n def to_numpy(self, array_str, sep=','):\n\n return np.fromstring(array_str[1:-1], sep=sep)\n\n def create_folder(self, folder_name):\n if len(folder_name):\n if not os.path.isdir(folder_name):\n os.makedirs(folder_name)\n\n return folder_name\n\n def mol_prop_mass(self, smiles):\n \"\"\"\n Molecular mass\n \"\"\"\n\n return [Descriptors.ExactMolWt(Chem.MolFromSmiles(sm)) for sm in smiles]\n \n def smiles2fraggenie_csv(\n self, \n input_path='', \n input_filename='test_input.csv', \n smiles_col='smiles',\n output_path='', \n output_filename='',\n num_bonds_to_break=3, \n min_fragment_mass=50,\n max_smiles_len=250, \n max_num_smiles=1000000000, \n flag_display='true',\n masses_option='METFRAG_MZ'\n ):\n \"\"\"Calculate FragGenie from csv file\"\"\"\n\n if(len(output_path)==0):\n output_path = input_path\n if(len(output_filename)==0):\n output_filename = ''.join([\n 'fraggenie_', datetime.today().strftime('%d%m%Y%H%M%S'), \n '_', str(np.random.random(1)[0])[2:], \n '_nbonds_', str(num_bonds_to_break), \n '_frgms_', str(min_fragment_mass), \n '_smlen_', str(max_smiles_len),\n '_', input_filename\n ])\n bash_cmd = ''.join([\n 'bash ', self.dir_fraggenie, \n 'fragment.sh ', \n input_path, \n input_filename, \n ' ', output_path, \n output_filename, \n ' ', smiles_col, \n ' ', str(num_bonds_to_break), \n ' ', str(min_fragment_mass), \n ' ', str(max_smiles_len), \n ' ', str(max_num_smiles), \n ' ', flag_display, \n ' ', masses_option\n ])\n\n subprocess.call(bash_cmd, shell=True)\n\n return output_path, output_filename, bash_cmd\n\n def smiles2fraggenie(\n self, \n smiles, \n num_bonds_to_break=3, \n min_fragment_mass=50, \n max_smiles_len=250, \n max_num_smiles=1000000000, \n flag_display='true',\n masses_option='METFRAG_MZ',\n input_path='dump/', \n input_filename='', \n massspec_sep=',', \n fill_non_break_mol=1, \n flag_del_temp_file=1,\n verbose=0\n ):\n \"\"\"Calculate FragGenie from smiles\"\"\"\n\n input_path = self.create_folder(input_path)\n if len(input_filename)==0:\n input_filename = ''.join(['smiles_', datetime.today().strftime('%d%m%Y%H%M%S'), \n '_', str(np.random.random(1)[0])[2:], \n '.csv'\n ])\n\n pd.DataFrame.from_dict({'smiles':smiles}).to_csv(''.join([input_path, input_filename]), index=False)\n\n output_path, output_filename, bash_cmd = self.smiles2fraggenie_csv(\n input_path=input_path, \n input_filename=input_filename, \n num_bonds_to_break=num_bonds_to_break, \n min_fragment_mass=min_fragment_mass, \n max_smiles_len=max_smiles_len,\n max_num_smiles=max_num_smiles,\n flag_display=flag_display, \n masses_option=masses_option\n )\n\n\n df_smiles = pd.read_csv(output_path+output_filename)\n\n # handle very small molecules which is unable to break into fraggenie (fill with mol mass) or unbreakable molecules\n if fill_non_break_mol:\n fraggenie = [None]*len(smiles)\n fraggenie_smiles = df_smiles['smiles'].tolist()\n count1 = 0\n count2 = 0\n for i, sm in enumerate(smiles):\n try:\n fraggenie[i] = self.to_numpy(df_smiles[masses_option][fraggenie_smiles.index(sm)], sep=massspec_sep)\n if len(fraggenie[i])==0:\n if verbose:\n print('Unable to break molecules: {}-{}' .format(i, smiles[i]))\n fraggenie[i] = np.asarray([self.mol_prop_mass([smiles[i]])[0]])\n count1 += 1\n except:\n if verbose:\n print('Unable to break molecules: {}-{}' .format(i, smiles[i]))\n fraggenie[i] = np.asarray([self.mol_prop_mass([smiles[i]])[0]])\n count2 += 1\n print('Total number of unbreakable molecules: {} (empty-{}, not all-{})' .format(count1+count2, count1, count2))\n else:\n fraggenie = df_smiles[masses_option].apply(self.to_numpy, sep=massspec_sep).tolist()\n \n\n if flag_del_temp_file:\n filename = ''.join([input_path, input_filename])\n if os.path.isfile(filename):\n if verbose:\n print('Removing \"{}\"' .format(filename))\n os.remove(filename)\n filename = ''.join([output_path, output_filename])\n if os.path.isfile(filename):\n if verbose:\n print('Removing \"{}\"' .format(filename))\n os.remove(filename)\n\n\n return fraggenie\n \nif __name__ == '__main__':\n \n fraggenie = FragGenie()\n \n output_path, output_filename, bash_cmd = fraggenie.smiles2fraggenie_csv(output_filename='fraggenie_test_input.csv')\n \n \n smiles = ['Cn1cnc2n(C)c(=O)n(C)c(=O)c12', \n 'BrC1CCCCc1CC', \n 'C#1C#CC1', \n 'C#1C#CCcCCCc1', \n 'C#1CCCCCCC=1', \n 'C#1CCcNccccccccc1', \n 'Cn1cnc2n(C)c(=O)n(C)c(=O)c12']\n \n fragment = fraggenie.smiles2fraggenie(smiles, fill_non_break_mol=1)\n \n for i in range(len(smiles)):\n print('smiles: {}\\nfragment: {}' .format(smiles[i], fragment[i]))\n \n " ]
[ [ "numpy.fromstring", "numpy.random.random", "pandas.read_csv", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
BioGeek/annotated_deep_learning_paper_implementations
[ "e2516cc3063cdfdf11cda05f22a10082297aa33e", "e2516cc3063cdfdf11cda05f22a10082297aa33e", "e2516cc3063cdfdf11cda05f22a10082297aa33e", "e2516cc3063cdfdf11cda05f22a10082297aa33e", "e2516cc3063cdfdf11cda05f22a10082297aa33e", "e2516cc3063cdfdf11cda05f22a10082297aa33e" ]
[ "labml_nn/normalization/group_norm/experiment.py", "labml_nn/transformers/compressive/experiment.py", "labml_nn/transformers/gmlp/__init__.py", "labml_nn/transformers/knn/eval_knn.py", "labml_nn/transformers/xl/relative_mha.py", "labml_nn/capsule_networks/__init__.py" ]
[ "\"\"\"\n---\ntitle: CIFAR10 Experiment to try Group Normalization\nsummary: >\n This trains is a simple convolutional neural network that uses group normalization\n to classify CIFAR10 images.\n---\n\n# CIFAR10 Experiment for Group Normalization\n\"\"\"\n\nimport torch.nn as nn\n\nfrom labml import experiment\nfrom labml.configs import option\nfrom labml_helpers.module import Module\nfrom labml_nn.experiments.cifar10 import CIFAR10Configs\nfrom labml_nn.normalization.group_norm import GroupNorm\n\n\nclass Model(Module):\n \"\"\"\n ### VGG model for CIFAR-10 classification\n \"\"\"\n\n def __init__(self, groups: int = 32):\n super().__init__()\n layers = []\n # RGB channels\n in_channels = 3\n # Number of channels in each layer in each block\n for block in [[64, 64], [128, 128], [256, 256, 256], [512, 512, 512], [512, 512, 512]]:\n # Convolution, Normalization and Activation layers\n for channels in block:\n layers += [nn.Conv2d(in_channels, channels, kernel_size=3, padding=1),\n GroupNorm(groups, channels),\n nn.ReLU(inplace=True)]\n in_channels = channels\n # Max pooling at end of each block\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n\n # Create a sequential model with the layers\n self.layers = nn.Sequential(*layers)\n # Final logits layer\n self.fc = nn.Linear(512, 10)\n\n def forward(self, x):\n # The VGG layers\n x = self.layers(x)\n # Reshape for classification layer\n x = x.view(x.shape[0], -1)\n # Final linear layer\n return self.fc(x)\n\n\nclass Configs(CIFAR10Configs):\n # Number of groups\n groups: int = 16\n\n\n@option(Configs.model)\ndef model(c: Configs):\n \"\"\"\n ### Create model\n \"\"\"\n return Model(c.groups).to(c.device)\n\n\ndef main():\n # Create experiment\n experiment.create(name='cifar10', comment='group norm')\n # Create configurations\n conf = Configs()\n # Load configurations\n experiment.configs(conf, {\n 'optimizer.optimizer': 'Adam',\n 'optimizer.learning_rate': 2.5e-4,\n })\n # Start the experiment and run the training loop\n with experiment.start():\n conf.run()\n\n\n#\nif __name__ == '__main__':\n main()\n", "\"\"\"\n---\ntitle: Compressive Transformer Experiment\nsummary: This experiment trains a compressive transformer model on tiny Shakespeare dataset.\n---\n\n# Compressive Transformer Experiment\n\nThis is an annotated PyTorch experiment to train a compressive transformer model.\n\"\"\"\nfrom typing import List, Tuple, NamedTuple\n\nimport torch\nimport torch.nn as nn\n\nfrom labml import experiment, tracker, monit, logger\nfrom labml.configs import option\nfrom labml.logger import Text\nfrom labml_helpers.metrics.simple_state import SimpleStateModule\nfrom labml_helpers.module import Module\nfrom labml_helpers.train_valid import BatchIndex, hook_model_outputs\nfrom labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs\nfrom labml_nn.transformers.compressive import CompressiveTransformer, AttentionReconstructionLoss, \\\n CompressiveTransformerLayer, Conv1dCompression\n\n\nclass CompressedMemory(NamedTuple):\n mem: List[torch.Tensor]\n c_mem: List[torch.Tensor]\n\n\nclass AutoregressiveModel(Module):\n \"\"\"\n ## Auto regressive model\n \"\"\"\n\n def __init__(self, n_vocab: int, d_model: int, transformer: CompressiveTransformer):\n super().__init__()\n # Token embedding module\n self.src_embed = nn.Embedding(n_vocab, d_model)\n # Transformer\n self.transformer = transformer\n # Final layer\n self.generator = nn.Linear(d_model, n_vocab)\n # Masks\n self.mask_x = None\n self.mask_mem = None\n\n def forward(self, x: torch.Tensor, mem: CompressedMemory):\n # Get memory and compressed memory\n if mem is not None:\n mem, c_mem = mem.mem, mem.c_mem\n else:\n mem = []\n c_mem = []\n\n # Total length of the memory and compressed memory (for masks)\n m_len = len(mem[0]) if mem else 0\n if c_mem:\n m_len += len(c_mem[0])\n\n # Create a subsequent mask for tokens\n if self.mask_x is None or self.mask_x.shape[0] < len(x):\n from labml_nn.transformers.utils import subsequent_mask\n self.mask_x = subsequent_mask(len(x)).to(x.device)\n # Create an all ones (full visibility) mask for memory\n if self.mask_mem is None or self.mask_mem.shape[1] < m_len or self.mask_mem.shape[0] < len(x):\n self.mask_mem = self.mask_x.new_ones(len(x), m_len, 1)\n\n # Concatenate the masks if there is memory\n if m_len:\n mask = torch.cat((self.mask_mem[:len(x), :m_len], self.mask_x[:len(x), :len(x)]), dim=1)\n # Use only the subsequent mask otherwise\n else:\n mask = self.mask_x[:len(x), :len(x)]\n\n # Token embeddings\n x = self.src_embed(x)\n # Run it through the transformer\n res, mem = self.transformer(x, mem, c_mem, mask)\n # Generate logits of the next token\n res = self.generator(res)\n #\n return res, mem\n\n\nclass Configs(NLPAutoRegressionConfigs):\n \"\"\"\n ## Configurations\n\n The default configurations can and will be overridden when we start the experiment.\n \"\"\"\n\n model: AutoregressiveModel\n\n # Token embedding size\n d_model: int = 128\n # Number of attention heads\n heads: int = 4\n # Dropout probability\n dropout: float = 0.0\n # Number of features in FFN hidden layer\n d_ff: int = 256\n # Number of transformer layers\n n_layers: int = 6\n # Number of memories to keep\n mem_len: int = 8\n # State module to maintain memories when switching between training and validation\n memory = SimpleStateModule()\n # Attention Reconstruction Loss\n attention_reconstruction_loss: AttentionReconstructionLoss\n # Compression rate\n compression_rate: int = 4\n # Compressed memory length\n c_mem_len: int = 128\n\n def init(self):\n # Set tracker configurations\n tracker.set_scalar(\"accuracy.*\", True)\n tracker.set_scalar(\"loss.*\", True)\n # Do not print the attention reconstruction loss in the terminal\n tracker.set_scalar(\"ar_loss.*\", False)\n # Add a hook to log module outputs\n hook_model_outputs(self.mode, self.model, 'model')\n # This will keep the accuracy metric stats and memories separate for training and validation.\n self.state_modules = [self.accuracy, self.memory]\n\n @torch.no_grad()\n def merge_compress_memory(self, mem: CompressedMemory, new_mem: List[torch.Tensor]) \\\n -> Tuple[CompressedMemory, List[torch.Tensor]]:\n \"\"\"\n Concatenate new memories and compress the oldest memories.\n \"\"\"\n\n # If the configurations specify not to use memory\n if self.mem_len == 0 and self.c_mem_len == 0:\n return CompressedMemory([], []), []\n\n # Get memory and compressed memory\n if mem is not None:\n mem, c_mem = mem.mem, mem.c_mem\n else:\n mem, c_mem = [], []\n\n # Concatenate new memories with old memory\n if mem:\n mem = [torch.cat((m, x), dim=0) for m, x in zip(mem, new_mem)]\n else:\n mem = new_mem\n\n # Compress the oldest memories if there are more memories than `mem_len`\n if len(mem[0]) > self.mem_len:\n # Calculate the number of compressed memories to make $n_{cm} = \\bigg\\lceil\\frac{n'_m - N_m}{c}\\bigg\\rceil$,\n # where $n'_m$ is the number of memories we have\n # and $N_m$ is the maximum number of memories we maintain (`mem_len`).\n n_c_mem = (len(mem[0]) - self.mem_len + self.compression_rate - 1) // self.compression_rate\n # Number of memories to compress $c n_{cm}$\n n_old = n_c_mem * self.compression_rate\n # A list to keep memories that need to be compressed for each layer.\n mem_to_compress = []\n # A list to keep the memories that do not get compressed for each layer.\n uncompressed_mem = []\n # Iterate through memories of each layer.\n for m in mem:\n # Split the memories at $c n_{cm}$\n cm, m = torch.split(m, [n_old, len(m) - n_old])\n # Collect memories to compress\n mem_to_compress.append(cm)\n # Collect remaining memories\n uncompressed_mem.append(m)\n # Update the memories\n mem = uncompressed_mem\n\n # Compress the memories\n new_c_mem = []\n for i, layer in enumerate(self.model.transformer.layers):\n new_c_mem.append(layer.compress(mem_to_compress[i]))\n\n # Concatenate newly compressed memories with old compressed memories\n if c_mem:\n c_mem = [torch.cat((m, nm), dim=0) for m, nm in zip(c_mem, new_c_mem)]\n # If there are no old compressed memories\n else:\n c_mem = new_c_mem\n\n # Truncate old memories\n if len(c_mem[0]) > self.c_mem_len:\n c_mem = [m[-self.c_mem_len:] for m in c_mem]\n # No memories are compressed if the number of memories is less than `mem_len`\n else:\n mem_to_compress = []\n\n # Return memories and the memories that were compressed.\n # Memories that were compressed are needed for the reconstruction loss computation.\n return CompressedMemory(mem, c_mem), mem_to_compress\n\n def step(self, batch: any, batch_idx: BatchIndex):\n \"\"\"\n ### Training/validation step\n \"\"\"\n\n # Move data to the device\n data, target = batch[0].to(self.device), batch[1].to(self.device)\n\n # Update global step (number of tokens processed) when in training mode\n if self.mode.is_train:\n tracker.add_global_step(data.shape[0] * data.shape[1])\n\n # Whether to capture model outputs\n with self.mode.update(is_log_activations=batch_idx.is_last):\n # Get memories\n mem = self.memory.get()\n # Run the model\n output, new_mem = self.model(data, mem)\n # Merge and compress memory\n mem, mem_to_compress = self.merge_compress_memory(mem, new_mem)\n # Update memories\n self.memory.set(mem)\n\n # Calculate and log cross entropy loss\n loss = self.loss_func(output, target)\n tracker.add(\"loss.\", loss)\n\n # Calculate attention reconstruction loss if memories were compressed in this step\n if mem_to_compress:\n # Get attention reconstruction loss\n ar_loss = self.attention_reconstruction_loss(new_mem, mem_to_compress)\n # Track attention reconstruction loss\n tracker.add(\"ar_loss.\", ar_loss)\n # Add attention reconstruction loss to loss\n loss = loss + ar_loss\n\n # Calculate and log accuracy\n self.accuracy(output, target)\n self.accuracy.track()\n\n # Train the model\n if self.mode.is_train:\n # Calculate gradients\n loss.backward()\n # Clip gradients\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=self.grad_norm_clip)\n # Take optimizer step\n self.optimizer.step()\n # Log the model parameters and gradients on last batch of every epoch\n if batch_idx.is_last:\n tracker.add('model', self.model)\n # Clear the gradients\n self.optimizer.zero_grad()\n\n # Save the tracked metrics\n tracker.save()\n\n def sample(self):\n \"\"\"\n ### Sampling function to generate samples periodically while training\n \"\"\"\n\n # Starting prompt\n prompt = self.prompt\n # Collect output for printing\n log = [(prompt, Text.subtle)]\n # memory\n mem = CompressedMemory([], [])\n # Sample 25 tokens\n for i in monit.iterate('Sample', 25):\n # Tokenize the prompt\n data = self.text.text_to_i(prompt).unsqueeze(-1)\n # Move to device\n data = data.to(self.device)\n # Get the model output\n output, new_mem = self.model(data, mem)\n # Get the model prediction (greedy)\n output = output.argmax(dim=-1).squeeze(1)\n # Add the prediction to prompt\n prompt += self.prompt_separator + self.text.itos[output[-1]]\n # Only feed the last character to model in next iteration, rest will go in as memories\n prompt = prompt[-1:]\n # Add the prediction for logging\n log += [(self.prompt_separator + self.text.itos[output[-1]], Text.value)]\n # Update and compress memory\n mem, _ = self.merge_compress_memory(mem, new_mem)\n\n # Print the sampled output\n logger.log(log)\n\n\n@option(Configs.model)\ndef autoregressive_model(c: Configs):\n \"\"\"\n ### Initialize the auto-regressive model\n \"\"\"\n from labml_nn.transformers.xl import RelativeMultiHeadAttention\n from labml_nn.transformers.feed_forward import FeedForward\n m = AutoregressiveModel(c.n_tokens, c.d_model, CompressiveTransformer(\n CompressiveTransformerLayer(d_model=c.d_model,\n self_attn=RelativeMultiHeadAttention(c.heads, c.d_model, c.dropout),\n feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout),\n dropout_prob=c.dropout,\n compress=Conv1dCompression(c.compression_rate, c.d_model)), c.n_layers))\n return m.to(c.device)\n\n\n@option(Configs.attention_reconstruction_loss)\ndef attention_reconstruction_loss(c: Configs):\n \"\"\"\n ### Initialize the attention reconstruction loss\n \"\"\"\n return AttentionReconstructionLoss(c.model.transformer.layers)\n\n\ndef main():\n \"\"\"\n ### Run the experiment\n \"\"\"\n # Create experiment\n experiment.create(name=\"compressive_transformer\", comment='')\n # Create configs\n conf = Configs()\n # Load configurations\n experiment.configs(conf,\n # A dictionary of configurations to override\n {'tokenizer': 'character',\n 'text': 'tiny_shakespeare',\n 'optimizer.learning_rate': 2.5e-4,\n 'optimizer.optimizer': 'AdamW',\n 'prompt': 'It is',\n 'prompt_separator': '',\n\n 'train_loader': 'sequential_train_loader',\n 'valid_loader': 'sequential_valid_loader',\n\n 'seq_len': 8,\n 'mem_len': 8,\n 'epochs': 128,\n 'batch_size': 32,\n 'inner_iterations': 25,\n 'compression_rate': 2,\n })\n\n # Set models for saving and loading\n experiment.add_pytorch_models({'model': conf.model})\n\n # Start the experiment\n with experiment.start():\n # `TrainValidConfigs.run`\n conf.run()\n\n\n#\nif __name__ == '__main__':\n main()\n", "\"\"\"\n---\ntitle: Pay Attention to MLPs (gMLP)\nsummary: >\n This is an annotated implementation/tutorial of Pay Attention to MLPs (gMLP) in PyTorch.\n---\n\n# Pay Attention to MLPs (gMLP)\n\nThis is a [PyTorch](https://pytorch.org) implementation of the paper\n[Pay Attention to MLPs](https://papers.labml.ai/paper/2105.08050).\n\nThis paper introduces a Multilayer Perceptron (MLP) based architecture with gating,\nwhich they name **gMLP**. It consists of a stack of $L$ *gMLP* blocks.\n\nHere is [the training code](experiment.html) for a gMLP model based autoregressive model.\n\n[![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://app.labml.ai/run/01bd941ac74c11eb890c1d9196651a4a)\n\"\"\"\n\nfrom typing import Optional\n\nimport torch\nfrom torch import nn\n\n\nclass GMLPBlock(nn.Module):\n \"\"\"\n ## gMLP Block\n\n Each block does the following transformations to input embeddings\n $X \\in \\mathbb{R}^{n \\times d}$ where $n$ is the sequence length\n and $d$ is the dimensionality of the embeddings:\n\n \\begin{align}\n Z &= \\sigma(XU) \\\\\n \\tilde{Z} &= s(Z) \\\\\n Y &= \\tilde{Z}V \\\\\n \\end{align}\n\n where $V$ and $U$ are learnable projection weights.\n $s(\\cdot)$ is the Spacial Gating Unit defined below.\n Output dimensionality of $s(\\cdot)$ will be half of $Z$.\n $\\sigma$ is an activation function such as\n [GeLU](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html).\n \"\"\"\n\n def __init__(self, d_model: int, d_ffn: int, seq_len: int):\n \"\"\"\n `d_model` is the dimensionality ($d$) of $X$\n `d_ffn` is the dimensionality of $Z$\n `seq_len` is the length of the token sequence ($n$)\n \"\"\"\n super().__init__()\n # Normalization layer fro Pre-Norm\n self.norm = nn.LayerNorm([d_model])\n # Activation function $\\sigma$\n self.activation = nn.GELU()\n # Projection layer for $Z = \\sigma(XU)$\n self.proj1 = nn.Linear(d_model, d_ffn)\n # Spacial Gating Unit $s(\\cdot)$\n self.sgu = SpacialGatingUnit(d_ffn, seq_len)\n # Projection layer for $Y = \\tilde{Z}V$\n self.proj2 = nn.Linear(d_ffn // 2, d_model)\n # Embedding size (required by [Encoder](../models.html#Encoder).\n # We use the encoder module from transformer architecture and plug\n # *gMLP* block as a replacement for the [Transformer Layer](../models.html#Encoder).\n self.size = d_model\n\n def forward(self, *, x: torch.Tensor, mask: Optional[torch.Tensor] = None):\n \"\"\"\n * `x` is the input embedding tensor $X$ of shape `[seq_len, batch_size, d_model]`\n * `mask` is a boolean mask of shape `[seq_len, seq_len, 1]` that controls the visibility of tokens\n among each other.\n \"\"\"\n # Keep a copy for shortcut connection\n shortcut = x\n # Normalize $X$\n x = self.norm(x)\n # Projection and activation $Z = \\sigma(XU)$\n z = self.activation(self.proj1(x))\n # Spacial Gating Unit $\\tilde{Z} = s(Z)$\n z = self.sgu(z, mask)\n # Final projection $Y = \\tilde{Z}V$\n z = self.proj2(z)\n\n # Add the shortcut connection\n return z + shortcut\n\n\nclass SpacialGatingUnit(nn.Module):\n \"\"\"\n ## Spatial Gating Unit\n\n $$s(Z) = Z_1 \\odot f_{W,b}(Z_2)$$\n\n where $f_{W,b}(Z) = W Z + b$ is a linear transformation along the sequence dimension,\n and $\\odot$ is element-wise multiplication.\n $Z$ is split into to parts of equal size $Z_1$ and $Z_2$ along the channel dimension (embedding dimension).\n \"\"\"\n def __init__(self, d_z: int, seq_len: int):\n \"\"\"\n * `d_z` is the dimensionality of $Z$\n * `seq_len` is the sequence length\n \"\"\"\n super().__init__()\n # Normalization layer before applying $f_{W,b}(\\cdot)$\n self.norm = nn.LayerNorm([d_z // 2])\n # Weight $W$ in $f_{W,b}(\\cdot)$.\n #\n # The paper notes that it's important to initialize weights to small values and the bias to $1$,\n # so that during the initial training $s(\\cdot)$ is close to identity (apart from the split).\n self.weight = nn.Parameter(torch.zeros(seq_len, seq_len).uniform_(-0.01, 0.01), requires_grad=True)\n # Weight $b$ in $f_{W,b}(\\cdot)$\n #\n # The paper notes that it's important to initialize bias to $1$.\n self.bias = nn.Parameter(torch.ones(seq_len), requires_grad=True)\n\n def forward(self, z: torch.Tensor, mask: Optional[torch.Tensor] = None):\n \"\"\"\n * `z` is the input $Z$ of shape `[seq_len, batch_size, d_z]`\n * `mask` is is a boolean mask of shape `[seq_len, seq_len, 1]` that controls the visibility of tokens\n among each other. The last dimension of size `1` is the batch, which we have in other transformer\n implementations and was left for compatibility.\n \"\"\"\n\n # Get sequence length\n seq_len = z.shape[0]\n # Split $Z$ into $Z_1$ and $Z_2$\n z1, z2 = torch.chunk(z, 2, dim=-1)\n\n # Check mask\n if mask is not None:\n # `mask` has shape `[seq_len_q, seq_len_k, batch_size]`.\n # The batch dimension should be of size `1` because this implementation supports\n # only same mask for all samples in the batch.\n assert mask.shape[0] == 1 or mask.shape[0] == seq_len\n assert mask.shape[1] == seq_len\n # Here we only support the same mask for all samples\n assert mask.shape[2] == 1\n # Remove the batch dimension\n mask = mask[:, :, 0]\n\n # Normalize $Z_2$ before $f_{W,b}(\\cdot)$\n z2 = self.norm(z2)\n # Get the weight matrix; truncate if larger than `seq_len`\n weight = self.weight[:seq_len, :seq_len]\n # Apply mask to the weights.\n #\n # If $W_{i,j}$ is $0$ then $f_{W,b}(Z_2)_i$ will not get any information\n # from token $j$.\n if mask is not None:\n weight = weight * mask\n\n # $f_{W,b}(Z_2) = W Z_2 + b$\n z2 = torch.einsum('ij,jbd->ibd', weight, z2) + self.bias[:seq_len, None, None]\n\n # $Z_1 \\odot f_{W,b}(Z_2)$\n return z1 * z2\n", "\"\"\"\n---\ntitle: Evaluate k-nearest neighbor language model\nsummary: >\n This runs the kNN model and merges the kNN results with transformer output to\n achieve better results than just using the transformer.\n---\n\n# Evaluate k-nearest neighbor language model\n\"\"\"\nfrom typing import Optional, List\n\nimport faiss\nimport numpy as np\nimport torch\n\nfrom labml import monit, lab\nfrom labml.logger import inspect\nfrom labml_nn.transformers.knn.train_model import Configs\n\n\ndef knn(queries: torch.Tensor, index: faiss.IndexFlatL2, keys_store: np.ndarray, vals_store: np.ndarray, n_tokens: int):\n \"\"\"\n ## $k$-NN to get $p(w_t, c_t)$\n\n Here we refer to $f(\\color{yellowgreen}{c_t})$ as queries,\n $f(c_i)$ as keys and $w_i$ as values.\n \"\"\"\n\n # Save shape of queries to reshape results\n queries_shape = queries.shape\n\n # Flatten the `batch` and `sequence` dimensions of queries\n queries = queries.view(-1, queries_shape[-1])\n\n # Find 10 nearest neighbors of $f(\\color{yellowgreen}{c_t})$ among $f(c_i)$.\n # `distance` is the distance given by FAISS and `idx`, $i$ is the index of it in `keys_store`.\n distance, idx = index.search(queries.numpy(), 10)\n\n # Get $f(c_i)$\n keys_found = queries.new_tensor(keys_store[idx])\n # Get $w_i$\n vals_found = torch.tensor(vals_store[idx]).squeeze(-1)\n\n # We are going to calculate the cosine similarity between normalized vectors\n\n # Normalize $f(c_i)$\n keys_found_n = keys_found / torch.sqrt((keys_found ** 2).sum(-1, keepdims=True) + 1e-10)\n # Normalize $f($\\color{yellowgreen}{c_t})$\n queries_n = queries / torch.sqrt((queries ** 2).sum(-1, keepdims=True) + 1e-10)\n\n # Get the dot-product, or cosine similarity\n dot_prod = (keys_found_n * queries_n.unsqueeze(1)).sum(-1)\n\n # Token-wise logits\n logits_token = dot_prod.new_zeros(queries.shape[0], n_tokens)\n # Scatter and accumulate token logits based on the nearest neighbors\n _ = logits_token.scatter_(dim=1, index=vals_found, src=dot_prod, reduce='add')\n\n # Reshape the logits\n logits_token = logits_token.reshape(queries_shape[0], queries_shape[1], -1)\n\n return logits_token\n\n\ndef validation_loss(knn_weights: List[float], last_n: Optional[int], conf: Configs, index: faiss.IndexFlatL2,\n keys_store: np.ndarray, vals_store: np.ndarray):\n \"\"\"\n ## Calculate validation loss\n\n We calculate the validation loss of the combined on $k$-NN prediction and transformer prediction.\n The weight given to the $k$-NN model is given by `knn_weight`.\n It's a list of weights and we calculate the validation loss for each.\n \"\"\"\n\n # List of losses for each `knn_weights`\n losses = [[] for _ in knn_weights]\n # Number of samples in each batch\n n_samples = []\n with torch.no_grad():\n # Iterate through validation data\n for i, batch in monit.enum(\"Validation\", conf.validator.data_loader, is_children_silent=True):\n # Get data and target labels\n data, target = batch[0].to(conf.device), batch[1].to(conf.device)\n # Run the model and get predictions $p(w_t, c_t)$\n res = conf.model(data)\n # Get $k$-NN predictions\n res_knn = knn(conf.model.ff_input.cpu(), index, keys_store, vals_store, conf.n_tokens)\n res_knn = res_knn.to(conf.device)\n\n # This is to calculate only the loss for `last_n` tokens.\n # This is important because the first predictions (along the sequence)\n # of transformer model has very few past tokens to look at.\n if last_n:\n res = res[-last_n:]\n res_knn = res_knn[-last_n:]\n target = target[-last_n:]\n\n # Number of samples\n n_s = res.shape[0] * data.shape[1]\n n_samples.append(n_s)\n\n # Calculate scores for each of `knn_weights`.\n for i, c in enumerate(knn_weights):\n # Calculate the loss\n loss = conf.loss_func(res_knn * c + (1 - c) * res, target)\n losses[i].append(loss * n_s)\n\n return losses, n_samples\n\n\ndef load_index(conf: Configs, n_probe: int = 8):\n \"\"\"\n ## Load the index\n \"\"\"\n # Dimensions of $f(c_i)$\n d_model = conf.transformer.d_model\n # Training data loader\n data_loader = conf.trainer.data_loader\n # Number of contexts; i.e. number of tokens in the training data minus one.\n # $\\big(f(c_i), w_i\\big)$ for $i \\in [2, T]$\n n_keys = data_loader.data.shape[0] * data_loader.data.shape[1] - 1\n\n # Load FAISS index\n with monit.section('Load index'):\n index = faiss.read_index(str(lab.get_data_path() / 'faiss.index'))\n # Set number of cells to probe\n index.nprobe = n_probe\n\n # Load memory mapped numpy arrays\n keys_store = np.memmap(str(lab.get_data_path() / 'keys.npy'), dtype=np.float32, mode='r', shape=(n_keys, d_model))\n vals_store = np.memmap(str(lab.get_data_path() / 'vals.npy'), dtype=np.int, mode='r', shape=(n_keys, 1))\n\n return index, keys_store, vals_store\n\n\ndef main():\n from labml_nn.transformers.knn.build_index import load_experiment\n # Load the experiment. Replace the run uuid with you run uuid from\n # [training the model](train_model.html).\n conf = load_experiment('4984b85c20bf11eb877a69c1a03717cd')\n # Set model to evaluation mode\n conf.model.eval()\n\n # Load index\n index, keys_store, vals_store = load_index(conf)\n # List of weights given to $k$-NN prediction. We will evaluate the validation loss for\n # each of the weights\n knn_weights = [i / 20 for i in range(10)]\n # Evaluate validation loss\n losses, n_samples = validation_loss(knn_weights, None, conf, index, keys_store, vals_store)\n # Output the losses for each of `knn_weights`.\n inspect({c: np.sum(losses[i]) / np.sum(n_samples) for i, c in enumerate(knn_weights)})\n\n\nif __name__ == '__main__':\n main()\n", "\"\"\"\n---\ntitle: Relative Multi-Headed Attention\nsummary: >\n Documented implementation with explanations of\n Relative Multi-Headed Attention from paper Transformer-XL.\n---\n\n# Relative Multi-Headed Attention\n\nThis is an implementation of relative multi-headed attention from paper\n[Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://papers.labml.ai/paper/1901.02860)\nin [PyTorch](https://pytorch.org).\n\"\"\"\n\nimport torch\nfrom torch import nn\n\nfrom labml.logger import inspect\nfrom labml_nn.transformers.mha import MultiHeadAttention\n\n\ndef shift_right(x: torch.Tensor):\n \"\"\"\n This method shifts $i^{th}$ row of a matrix by $i$ columns.\n\n If the input is `[[1, 2 ,3], [4, 5 ,6], [7, 8, 9]]`, the shifted\n result would be `[[1, 2 ,3], [0, 4, 5], [9, 0, 7]]`.\n *Ideally we should mask out the lower triangle but it's ok for our purpose*.\n \"\"\"\n\n # Concatenate a column of zeros\n zero_pad = x.new_zeros(x.shape[0], 1, *x.shape[2:])\n x_padded = torch.cat([x, zero_pad], dim=1)\n\n # Reshape and remove excess elements from the end\n x_padded = x_padded.view(x.shape[1] + 1, x.shape[0], *x.shape[2:])\n x = x_padded[:-1].view_as(x)\n\n #\n return x\n\n\nclass RelativeMultiHeadAttention(MultiHeadAttention):\n \"\"\"\n ## Relative Multi-Head Attention Module\n\n We override [Multi-Head Attention](mha.html) module so we only need to \n write the `get_scores` method.\n \"\"\"\n\n def __init__(self, heads: int, d_model: int, dropout_prob: float = 0.1):\n # The linear transformations do not need a bias since we\n # explicitly include it when calculating scores.\n # However having a bias for `value` might make sense.\n super().__init__(heads, d_model, dropout_prob, bias=False)\n\n # Number of relative positions\n self.P = 2 ** 12\n\n # Relative positional embeddings for key relative to the query.\n # We need $2P$ embeddings because the keys can be before or after the query.\n self.key_pos_embeddings = nn.Parameter(torch.zeros((self.P * 2, heads, self.d_k)), requires_grad=True)\n # Relative positional embedding bias for key relative to the query.\n self.key_pos_bias = nn.Parameter(torch.zeros((self.P * 2, heads)), requires_grad=True)\n # Positional embeddings for the query is independent of the position of the query\n self.query_pos_bias = nn.Parameter(torch.zeros((heads, self.d_k)), requires_grad=True)\n\n def get_scores(self, query: torch.Tensor, key: torch.Tensor):\n r\"\"\"\n ### Get relative attention scores\n\n With absolute attention\n\n \\begin{align}\n A^{abs}_{j} &= lin_q(X^q_i + P_i)^\\top lin_k(X^k_j + P_j) \\\\\n &= \\underset{\\color{lightgreen}{A}}{Q_i^\\top K_j} +\n \\underset{\\color{lightgreen}{B}}{Q_i^\\top U^K_j} +\n \\underset{\\color{lightgreen}{C}}{{U^Q_i}^\\top K_j} +\n \\underset{\\color{lightgreen}{D}}{{U^Q_i}^\\top U^K_j}\n \\end{align}\n\n where $Q_i, K_j$, are linear transformations of\n original embeddings $X^q_i, X^k_j$\n and $U^Q_i, U^K_j$ are linear transformations of\n absolute positional encodings $P_i, P_j$.\n\n They reason out that the attention to a given key should be the same regardless of\n the position of query.\n Hence replace $\\underset{\\color{lightgreen}{C}}{{U^Q_i}^\\top K_j}$\n with a constant $\\underset{\\color{lightgreen}{C}}{\\color{orange}{v^\\top} K_j}$.\n\n For the second and third terms relative positional encodings are introduced.\n So $\\underset{\\color{lightgreen}{B}}{Q_i^\\top U^K_j}$ is\n replaced with $\\underset{\\color{lightgreen}{B}}{Q_i^\\top \\color{orange}{R_{i - j}}}$\n and $\\underset{\\color{lightgreen}{D}}{{U^Q_i}^\\top U^K_j}$\n with $\\underset{\\color{lightgreen}{D}}{\\color{orange}{S_{i-j}}}$.\n\n \\begin{align}\n A^{rel}_{i,j} &= \\underset{\\mathbf{\\color{lightgreen}{A}}}{Q_i^\\top K_j} +\n \\underset{\\mathbf{\\color{lightgreen}{B}}}{Q_i^\\top \\color{orange}{R_{i - j}}} +\n \\underset{\\mathbf{\\color{lightgreen}{C}}}{\\color{orange}{v^\\top} K_j} +\n \\underset{\\mathbf{\\color{lightgreen}{D}}}{\\color{orange}{S_{i-j}}}\n \\end{align}\n \"\"\"\n\n # $\\color{orange}{R_k}$\n key_pos_emb = self.key_pos_embeddings[self.P - key.shape[0]:self.P + query.shape[0]]\n # $\\color{orange}{S_k}$\n key_pos_bias = self.key_pos_bias[self.P - key.shape[0]:self.P + query.shape[0]]\n # $\\color{orange}{v^\\top}$\n query_pos_bias = self.query_pos_bias[None, None, :, :]\n\n # ${(\\color{lightgreen}{\\mathbf{A + C}})}_{i,j} =\n # Q_i^\\top K_j +\n # \\color{orange}{v^\\top} K_jZ$\n ac = torch.einsum('ibhd,jbhd->ijbh', query + query_pos_bias, key)\n # $\\color{lightgreen}{\\mathbf{B'}_{i,k}} = Q_i^\\top \\color{orange}{R_k}$\n b = torch.einsum('ibhd,jhd->ijbh', query, key_pos_emb)\n # $\\color{lightgreen}{\\mathbf{D'}_{i,k}} = \\color{orange}{S_k}$\n d = key_pos_bias[None, :, None, :]\n # Shift the rows of $\\color{lightgreen}{\\mathbf{(B' + D')}_{i,k}}$\n # to get $$\\color{lightgreen}{\\mathbf{(B + D)}_{i,j} = \\mathbf{(B' + D')}_{i,i - j}}$$\n bd = shift_right(b + d)\n # Remove extra positions\n bd = bd[:, -key.shape[0]:]\n\n # Return the sum $$\n # \\underset{\\mathbf{\\color{lightgreen}{A}}}{Q_i^\\top K_j} +\n # \\underset{\\mathbf{\\color{lightgreen}{B}}}{Q_i^\\top \\color{orange}{R_{i - j}}} +\n # \\underset{\\mathbf{\\color{lightgreen}{C}}}{\\color{orange}{v^\\top} K_j} +\n # \\underset{\\mathbf{\\color{lightgreen}{D}}}{\\color{orange}{S_{i-j}}}\n # $$\n return ac + bd\n\n\ndef _test_shift_right():\n x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n inspect(x)\n inspect(shift_right(x))\n\n x = torch.arange(1, 6)[None, :, None, None].repeat(5, 1, 1, 1)\n inspect(x[:, :, 0, 0])\n inspect(shift_right(x)[:, :, 0, 0])\n\n x = torch.arange(1, 6)[None, :, None, None].repeat(3, 1, 1, 1)\n inspect(x[:, :, 0, 0])\n inspect(shift_right(x)[:, :, 0, 0])\n\n\nif __name__ == '__main__':\n _test_shift_right()\n", "\"\"\"\n---\ntitle: Capsule Networks\nsummary: >\n PyTorch implementation and tutorial of Capsule Networks.\n Capsule network is a neural network architecture that embeds features\n as capsules and routes them with a voting mechanism to next layer of capsules.\n---\n\n# Capsule Networks\n\nThis is a [PyTorch](https://pytorch.org) implementation/tutorial of\n[Dynamic Routing Between Capsules](https://papers.labml.ai/paper/1710.09829).\n\nCapsule network is a neural network architecture that embeds features\nas capsules and routes them with a voting mechanism to next layer of capsules.\n\nUnlike in other implementations of models, we've included a sample, because\nit is difficult to understand some concepts with just the modules.\n[This is the annotated code for a model that uses capsules to classify MNIST dataset](mnist.html)\n\nThis file holds the implementations of the core modules of Capsule Networks.\n\nI used [jindongwang/Pytorch-CapsuleNet](https://github.com/jindongwang/Pytorch-CapsuleNet) to clarify some\nconfusions I had with the paper.\n\nHere's a notebook for training a Capsule Network on MNIST dataset.\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/capsule_networks/mnist.ipynb)\n[![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://app.labml.ai/run/e7c08e08586711ebb3e30242ac1c0002)\n\"\"\"\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\n\nfrom labml_helpers.module import Module\n\n\nclass Squash(Module):\n \"\"\"\n ## Squash\n\n This is **squashing** function from paper, given by equation $(1)$.\n\n $$\\mathbf{v}_j = \\frac{{\\lVert \\mathbf{s}_j \\rVert}^2}{1 + {\\lVert \\mathbf{s}_j \\rVert}^2}\n \\frac{\\mathbf{s}_j}{\\lVert \\mathbf{s}_j \\rVert}$$\n\n $\\frac{\\mathbf{s}_j}{\\lVert \\mathbf{s}_j \\rVert}$\n normalizes the length of all the capsules, whilst\n $\\frac{{\\lVert \\mathbf{s}_j \\rVert}^2}{1 + {\\lVert \\mathbf{s}_j \\rVert}^2}$\n shrinks the capsules that have a length smaller than one .\n \"\"\"\n\n def __init__(self, epsilon=1e-8):\n super().__init__()\n self.epsilon = epsilon\n\n def forward(self, s: torch.Tensor):\n \"\"\"\n The shape of `s` is `[batch_size, n_capsules, n_features]`\n \"\"\"\n\n # ${\\lVert \\mathbf{s}_j \\rVert}^2$\n s2 = (s ** 2).sum(dim=-1, keepdims=True)\n\n # We add an epsilon when calculating $\\lVert \\mathbf{s}_j \\rVert$ to make sure it doesn't become zero.\n # If this becomes zero it starts giving out `nan` values and training fails.\n # $$\\mathbf{v}_j = \\frac{{\\lVert \\mathbf{s}_j \\rVert}^2}{1 + {\\lVert \\mathbf{s}_j \\rVert}^2}\n # \\frac{\\mathbf{s}_j}{\\sqrt{{\\lVert \\mathbf{s}_j \\rVert}^2 + \\epsilon}}$$\n return (s2 / (1 + s2)) * (s / torch.sqrt(s2 + self.epsilon))\n\n\nclass Router(Module):\n \"\"\"\n ## Routing Algorithm\n\n This is the routing mechanism described in the paper.\n You can use multiple routing layers in your models.\n\n This combines calculating $\\mathbf{s}_j$ for this layer and\n the routing algorithm described in *Procedure 1*.\n \"\"\"\n\n def __init__(self, in_caps: int, out_caps: int, in_d: int, out_d: int, iterations: int):\n \"\"\"\n `in_caps` is the number of capsules, and `in_d` is the number of features per capsule from the layer below.\n `out_caps` and `out_d` are the same for this layer.\n\n `iterations` is the number of routing iterations, symbolized by $r$ in the paper.\n \"\"\"\n super().__init__()\n self.in_caps = in_caps\n self.out_caps = out_caps\n self.iterations = iterations\n self.softmax = nn.Softmax(dim=1)\n self.squash = Squash()\n\n # This is the weight matrix $\\mathbf{W}_{ij}$. It maps each capsule in the\n # lower layer to each capsule in this layer\n self.weight = nn.Parameter(torch.randn(in_caps, out_caps, in_d, out_d), requires_grad=True)\n\n def forward(self, u: torch.Tensor):\n \"\"\"\n The shape of `u` is `[batch_size, n_capsules, n_features]`.\n These are the capsules from the lower layer.\n \"\"\"\n\n # $$\\hat{\\mathbf{u}}_{j|i} = \\mathbf{W}_{ij} \\mathbf{u}_i$$\n # Here $j$ is used to index capsules in this layer, whilst $i$ is\n # used to index capsules in the layer below (previous).\n u_hat = torch.einsum('ijnm,bin->bijm', self.weight, u)\n\n # Initial logits $b_{ij}$ are the log prior probabilities that capsule $i$\n # should be coupled with $j$.\n # We initialize these at zero\n b = u.new_zeros(u.shape[0], self.in_caps, self.out_caps)\n\n v = None\n\n # Iterate\n for i in range(self.iterations):\n # routing softmax $$c_{ij} = \\frac{\\exp({b_{ij}})}{\\sum_k\\exp({b_{ik}})}$$\n c = self.softmax(b)\n # $$\\mathbf{s}_j = \\sum_i{c_{ij} \\hat{\\mathbf{u}}_{j|i}}$$\n s = torch.einsum('bij,bijm->bjm', c, u_hat)\n # $$\\mathbf{v}_j = squash(\\mathbf{s}_j)$$\n v = self.squash(s)\n # $$a_{ij} = \\mathbf{v}_j \\cdot \\hat{\\mathbf{u}}_{j|i}$$\n a = torch.einsum('bjm,bijm->bij', v, u_hat)\n # $$b_{ij} \\gets b_{ij} + \\mathbf{v}_j \\cdot \\hat{\\mathbf{u}}_{j|i}$$\n b = b + a\n\n return v\n\n\nclass MarginLoss(Module):\n \"\"\"\n ## Margin loss for class existence\n\n A separate margin loss is used for each output capsule and the total loss is the sum of them.\n The length of each output capsule is the probability that class is present in the input.\n\n Loss for each output capsule or class $k$ is,\n $$\\mathcal{L}_k = T_k \\max(0, m^{+} - \\lVert\\mathbf{v}_k\\rVert)^2 +\n \\lambda (1 - T_k) \\max(0, \\lVert\\mathbf{v}_k\\rVert - m^{-})^2$$\n\n $T_k$ is $1$ if the class $k$ is present and $0$ otherwise.\n The first component of the loss is $0$ when the class is not present,\n and the second component is $0$ if the class is present.\n The $\\max(0, x)$ is used to avoid predictions going to extremes.\n $m^{+}$ is set to be $0.9$ and $m^{-}$ to be $0.1$ in the paper.\n\n The $\\lambda$ down-weighting is used to stop the length of all capsules from\n falling during the initial phase of training.\n \"\"\"\n def __init__(self, *, n_labels: int, lambda_: float = 0.5, m_positive: float = 0.9, m_negative: float = 0.1):\n super().__init__()\n\n self.m_negative = m_negative\n self.m_positive = m_positive\n self.lambda_ = lambda_\n self.n_labels = n_labels\n\n def forward(self, v: torch.Tensor, labels: torch.Tensor):\n \"\"\"\n `v`, $\\mathbf{v}_j$ are the squashed output capsules.\n This has shape `[batch_size, n_labels, n_features]`; that is, there is a capsule for each label.\n\n `labels` are the labels, and has shape `[batch_size]`.\n \"\"\"\n # $$\\lVert \\mathbf{v}_j \\rVert$$\n v_norm = torch.sqrt((v ** 2).sum(dim=-1))\n\n # $$\\mathcal{L}$$\n # `labels` is one-hot encoded labels of shape `[batch_size, n_labels]`\n labels = torch.eye(self.n_labels, device=labels.device)[labels]\n\n # $$\\mathcal{L}_k = T_k \\max(0, m^{+} - \\lVert\\mathbf{v}_k\\rVert)^2 +\n # \\lambda (1 - T_k) \\max(0, \\lVert\\mathbf{v}_k\\rVert - m^{-})^2$$\n # `loss` has shape `[batch_size, n_labels]`. We have parallelized the computation\n # of $\\mathcal{L}_k$ for for all $k$.\n loss = labels * F.relu(self.m_positive - v_norm) + \\\n self.lambda_ * (1.0 - labels) * F.relu(v_norm - self.m_negative)\n\n # $$\\sum_k \\mathcal{L}_k$$\n return loss.sum(dim=-1).mean()\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.ReLU" ], [ "torch.nn.Linear", "torch.no_grad", "torch.nn.Embedding", "torch.cat" ], [ "torch.nn.GELU", "torch.ones", "torch.zeros", "torch.einsum", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.chunk" ], [ "torch.no_grad", "numpy.sum", "torch.tensor" ], [ "torch.zeros", "torch.cat", "torch.einsum", "torch.tensor", "torch.arange" ], [ "torch.nn.Softmax", "torch.nn.functional.relu" ] ]
[ { "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": [] } ]
kdeweese/DualRandomizedKaczmarz
[ "3d339e893fe1dcb91677f3240047801ca3c43162" ]
[ "drkcode/python/kktmat.py" ]
[ "#!/usr/bin/env python\n# kktmat.py -- KKT matrix from Laplacian matrix\n#\n# Copyright (C) <2016> <Kevin Deweese>\n# All rights reserved.\n#\n# This software may be modified and distributed under the terms\n# of the BSD license. See the LICENSE file for details.\n\nimport scipy\n\ndef kktmat(L):\n mat=scipy.sparse.coo_matrix(scipy.sparse.tril(L,-1))\n row=mat.row\n m=len(row)\n n=L.shape[0]\n col=mat.col\n val=mat.data\n \n #R=scipy.sparse.diags(-1/val,0)\n R=scipy.array(-1/val)\n i=scipy.concatenate([scipy.arange(0,m),scipy.arange(0,m)])\n j=scipy.concatenate([row,col])\n data=scipy.concatenate([scipy.ones(m),-scipy.ones(m)])\n B=scipy.sparse.coo_matrix((data,(i,j)))\n return {'R':R,'B':B} \n" ]
[ [ "scipy.sparse.coo_matrix", "scipy.sparse.tril", "scipy.ones", "scipy.arange", "scipy.concatenate", "scipy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
serre-lab/brownUnconference
[ "c51758f0bf695648832448c5c166e2a8dea14268" ]
[ "scripts/embeddings.py" ]
[ "import argparse\nimport csv\n\nimport torch\nimport transformers\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description=\"MiniConf Portal Command Line\")\n\n parser.add_argument(\"papers\", default=False, help=\"papers file to parse\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n tokenizer = transformers.AutoTokenizer.from_pretrained(\"deepset/sentence_bert\")\n\n model = transformers.AutoModel.from_pretrained(\"deepset/sentence_bert\")\n model.eval()\n\n with open(args.papers, \"r\",encoding='utf-8') as f:\n abstracts = list(csv.DictReader(f))\n all_abstracts = torch.zeros(len(abstracts), 768)\n with torch.no_grad():\n for i, row in enumerate(abstracts):\n\n input_ids = torch.tensor([tokenizer.encode(row[\"abstract\"])][:512])\n all_hidden_states, _ = model(input_ids)[-2:]\n all_abstracts[i] = all_hidden_states.mean(0).mean(0)\n print(i)\n print(row['author'])\n torch.save(all_abstracts, \"embeddings.torch\")\n" ]
[ [ "torch.no_grad", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KeAWang/wilds
[ "3b808a84bd477d7877b77675eec2953128a87033" ]
[ "examples/algorithms/groupDRO.py" ]
[ "import torch\nfrom algorithms.single_model_algorithm import SingleModelAlgorithm\nfrom models.initializer import initialize_model\n\nclass GroupDRO(SingleModelAlgorithm):\n \"\"\"\n Group distributionally robust optimization.\n\n Original paper:\n @inproceedings{sagawa2019distributionally,\n title={Distributionally robust neural networks for group shifts: On the importance of regularization for worst-case generalization},\n author={Sagawa, Shiori and Koh, Pang Wei and Hashimoto, Tatsunori B and Liang, Percy},\n booktitle={International Conference on Learning Representations},\n year={2019}\n } \n \"\"\"\n def __init__(self, config, d_out, grouper, loss, metric, n_train_steps, is_group_in_train):\n # check config\n assert config.uniform_over_groups\n # initialize model\n model = initialize_model(config, d_out).to(config.device)\n # initialize module\n super().__init__(\n config=config,\n model=model,\n grouper=grouper,\n loss=loss,\n metric=metric,\n n_train_steps=n_train_steps,\n )\n # additional logging\n self.logged_fields.append('group_weight')\n # step size\n self.group_weights_step_size = config.group_dro_step_size\n # initialize adversarial weights\n self.group_weights = torch.zeros(grouper.n_groups)\n self.group_weights[is_group_in_train] = 1\n self.group_weights = self.group_weights/self.group_weights.sum()\n self.group_weights = self.group_weights.to(self.device)\n\n def process_batch(self, batch):\n \"\"\"\n A helper function for update() and evaluate() that processes the batch\n Args:\n - batch (tuple of Tensors): a batch of data yielded by data loaders\n Output:\n - results (dictionary): information about the batch\n - g (Tensor)\n - y_true (Tensor)\n - metadata (Tensor)\n - loss (Tensor)\n - metrics (Tensor)\n all Tensors are of size (batch_size,)\n \"\"\"\n results = super().process_batch(batch)\n results['group_weight'] = self.group_weights\n return results\n\n def objective(self, results):\n \"\"\"\n Takes an output of SingleModelAlgorithm.process_batch() and computes the\n optimized objective. For group DRO, the objective is the weighted average\n of losses, where groups have weights groupDRO.group_weights.\n Args:\n - results (dictionary): output of SingleModelAlgorithm.process_batch()\n Output:\n - objective (Tensor): optimized objective; size (1,).\n \"\"\"\n group_losses, _, _ = self.loss.compute_group_wise(\n results['y_pred'],\n results['y_true'],\n results['g'],\n self.grouper.n_groups,\n return_dict=False)\n return group_losses @ self.group_weights\n\n def _update(self, results):\n \"\"\"\n Process the batch, update the log, and update the model, group weights, and scheduler.\n Args:\n - batch (tuple of Tensors): a batch of data yielded by data loaders\n Output:\n - results (dictionary): information about the batch, such as:\n - g (Tensor)\n - y_true (Tensor)\n - metadata (Tensor)\n - loss (Tensor)\n - metrics (Tensor)\n - objective (float)\n \"\"\"\n # compute group losses\n group_losses, _, _ = self.loss.compute_group_wise(\n results['y_pred'],\n results['y_true'],\n results['g'],\n self.grouper.n_groups,\n return_dict=False)\n # update group weights\n self.group_weights = self.group_weights * torch.exp(self.group_weights_step_size*group_losses.data)\n self.group_weights = (self.group_weights/(self.group_weights.sum()))\n # save updated group weights\n results['group_weight'] = self.group_weights\n # update model\n super()._update(results)\n" ]
[ [ "torch.exp", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IewNixIl/graduation_project_under
[ "67d0345208511bb06c35c3453227b2fa4ebef4a3" ]
[ "DATA/Labeling.py" ]
[ "import numpy\nfrom matplotlib import pyplot\nimport gdal\nfrom skimage import io,exposure\nfrom skimage.segmentation import slic,mark_boundaries\nimport os\nfrom PIL import Image\nimport shelve\nimport sys\nsys.path.append('..')\nfrom Config import config\n\n\n\n\ndef seg(path,n_segments=500, compactness=20):\n i=io.imread(path)[:,:,[3,2,1,7]]\n img=i[:,:,:3]\n img=(img-img.min())/(img.max()-img.min())\n img=img*255\n img=img.astype(numpy.uint8)\n\n img=exposure.adjust_gamma(img,0.5)\n segment=slic(img,n_segments=n_segments, compactness=compactness,enforce_connectivity=True)\n out=mark_boundaries(img,segment,color=[0,0,0.2])\n \n #img=exposure.adjust_gamma(img,0.5)\n #out=exposure.adjust_gamma(out,0.5)\n \n wdi=(i[:,:,3]-i[:,:,1])/(i[:,:,3]+i[:,:,1])\n \n wdi=(wdi/wdi.max())*255\n \n return segment,out,img,wdi\n \n\ndef getname(path,namelist):\n if namelist[0]==0:\n season='ROIs1158_spring'\n elif namelist[0]==1:\n season='ROIs1868_summer'\n elif namelist[0]==2:\n season='ROIs1970_fall'\n elif namelist[0]==3:\n season='ROIs2017_winter'\n \n path_s2=path+'\\\\'+season+'\\\\s2_'+str(namelist[1])+'\\\\'+season+'_s2_'+str(namelist[1])+'_p'+str(namelist[2])+'.tif'\n \n return path_s2\n \ndef transform(name):\n if 'spring' in name:\n season=0\n elif 'summer' in name:\n season=1\n elif 'fall' in name:\n season=2\n elif 'winter' in name:\n season=3\n \n l=[]\n l.append(season)\n l.append(int(name.split('_')[3]))\n l.append(int(name.split('_')[4].split('.')[0][1:]))\n \n return l\n \n\nclass UI:\n def __init__(self,mode='normal',init=0):\n '''mode = normal 正常\n mode=review 仅仅显示已经标记的 \n '''\n self.mode=mode\n self.path_label=config.path_labels\n if self.mode=='normal':\n with shelve.open(config.path_devision) as f:\n self.imglist=f['test']\n else:\n self.imglist=os.listdir(config.path_labels)\n\n self.n=init\n \n \n self.ifpress=False\n self.ifloadlabel=False\n \n fig=pyplot.figure()\n fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)\n fig.canvas.mpl_connect('key_press_event',self.on_key_press)\n fig.canvas.mpl_connect('button_press_event',self.on_button_press)\n fig.canvas.mpl_connect('motion_notify_event',self.on_button_move)\n fig.canvas.mpl_connect('button_release_event',self.on_button_release)\n \n self.fig=fig\n self.ax1=fig.add_subplot(3,2,1)\n self.ax2=fig.add_subplot(3,2,3)\n self.ax4=fig.add_subplot(3,2,5)\n self.ax3=fig.add_subplot(1,2,2)\n pyplot.get_current_fig_manager().window.state('zoomed')\n #self.ax2=fig.add_subplot(1,2,2)\n \n \n \n self.valuelist=[]\n self.label=numpy.zeros((256,256))\n self.ifloadlabel=True\n self.draw()\n \n \n \n pyplot.show()\n \n def on_key_press(self,event):\n if event.key=='a' or event.key=='left':\n self.n-=1\n print(self.n)\n self.valuelist=[]\n self.label=numpy.zeros(self.segment.shape)\n self.ifloadlabel=True\n self.draw()\n\n if event.key=='d' or event.key=='right':\n if self.n+1>=len(self.imglist):\n return\n self.n+=1\n print(self.n)\n self.valuelist=[]\n self.label=numpy.zeros(self.segment.shape)\n self.ifloadlabel=True\n self.draw()\n\n if event.key=='e' or event.key=='enter':\n self.save_label()\n \n if event.key=='Q':\n f=numpy.unique(self.segment).tolist()\n for i in f:\n if i not in self.valuelist:\n self.valuelist.append(i)\n for i in range(len(self.valuelist)):\n if i==0:\n flag=(self.segment==self.valuelist[i])\n else:\n flag=flag+(self.segment==self.valuelist[i])\n self.label=numpy.where(flag,1.0,0)\n \n self.draw()\n \n \n def on_button_press(self,event):\n \n try:\n r=int(event.ydata)\n c=int(event.xdata)\n except TypeError:\n return\n value=self.segment[r,c]\n if event.button==1:\n if value not in self.valuelist:\n self.ifpress=True\n self.valuelist.append(value)\n elif event.button==3:\n if value in self.valuelist:\n self.ifpress=True\n self.valuelist.remove(value)\n \n \n def on_button_move(self,event):\n if not self.ifpress:\n return\n \n try:\n r=int(event.ydata)\n c=int(event.xdata)\n except TypeError:\n return\n value=self.segment[r,c]\n if event.button==1:\n if value not in self.valuelist:\n self.valuelist.append(value)\n elif event.button==3:\n if value in self.valuelist:\n self.valuelist.remove(value)\n \n def on_button_release(self,event):\n if not self.ifpress:\n return\n self.ifpress=False\n for i in range(len(self.valuelist)):\n if i==0:\n flag=(self.segment==self.valuelist[i])\n else:\n flag=flag+(self.segment==self.valuelist[i])\n self.label=numpy.where(flag,1,0).astype(int)\n self.draw()\n \n \n def draw(self):\n \n if self.mode=='normal':\n segment,out,img,wdi=seg(getname(config.path,self.imglist[self.n]))\n else:\n \n segment,out,img,wdi=seg(getname(config.path,transform(self.imglist[self.n])))\n self.segment=segment\n if self.ifloadlabel:\n self.read_label()\n self.ifloadlabel=False\n #self.ax1.imshow(out)\n t=numpy.where(self.label==1,0.5,out[:,:,2])\n out[:,:,2]=t\n self.ax1.cla()\n self.ax2.cla()\n self.ax3.cla()\n self.ax4.cla()\n self.ax1.imshow(img)\n self.ax2.imshow(wdi,cmap='gray')\n self.ax3.imshow(out)\n self.ax4.imshow(self.label,cmap='gray')\n \n d=os.listdir(config.path_labels)\n self.ax3.set_title(str(len(d))+'/'+str(self.n+1))\n self.fig.canvas.draw_idle()\n \n def save_label(self):\n \n \n \n label=self.label*255\n label=label.astype(numpy.uint8)\n label=Image.fromarray(label)\n if self.mode=='normal':\n name=getname(config.path,self.imglist[self.n]).split('\\\\')[-1]\n name=name.split('_')\n name[2]='label'\n name='_'.join(name)\n else:\n name=self.imglist[self.n]\n label.save(self.path_label+'\\\\'+name)\n \n def read_label(self):\n \n dirlist=os.listdir(self.path_label)\n if self.mode=='normal':\n name=getname(config.path,self.imglist[self.n]).split('\\\\')[-1]\n name=name.split('_')\n name[2]='label'\n name='_'.join(name)\n else:\n name=self.imglist[self.n]\n if name in dirlist:\n self.label=numpy.array(Image.open(self.path_label+'\\\\'+name))/255\n self.label=self.label.astype(int)\n self.valuelist=list(numpy.unique(numpy.where(self.label==1,self.segment,-2)))\n self.valuelist.remove(-2)\n \n \ndef statistic():\n d=os.listdir(config.path_labels)\n n=numpy.array([0,0,0,0])\n for i in d:\n if 'spring' in i:\n n[0]=n[0]+1\n if 'summer' in i:\n n[1]=n[1]+1\n if 'fall' in i:\n n[2]=n[2]+1\n if 'winter' in i:\n n[3]=n[3]+1\n \n print(n)\n n=n/len(d)\n print(n) \n\nif __name__=='__main__':\n test=UI(mode='normal',init=100)\n #statistic()\n " ]
[ [ "numpy.unique", "matplotlib.pyplot.get_current_fig_manager", "numpy.array", "numpy.zeros", "numpy.where", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chenzhengda/tensorflow
[ "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53", "8debb698097670458b5f21d728bc6f734a7b5a53" ]
[ "tensorflow/python/ipu/keras/layers/recomputation.py", "tensorflow/python/ipu/tests/keras/keras_functional_model_test.py", "tensorflow/python/ipu/tests/assume_equal_test.py", "tensorflow/compiler/plugin/poplar/tests/while_loop_perf_test.py", "tensorflow/python/ipu/tests/replicated_reduce_scatter_test.py", "tensorflow/python/ipu/horovod/popdist_strategy_test.py", "tensorflow/python/tpu/tpu_test.py", "tensorflow/python/ipu/ops/statistics_ops.py", "tensorflow/python/ipu/tests/pipelining_grouped_recomputation_test.py", "tensorflow/python/ipu/ops/op_util.py", "tensorflow/python/ipu/tests/keras/keras_embedding_lookup_test.py", "tensorflow/python/ipu/tests/keras/keras_synthetic_data_test.py" ]
[ "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nRecomputation IPU Keras layers\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\n\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.ipu.ops import pipelining_ops\n\n\nclass RecomputationCheckpoint(Layer):\n \"\"\"\n Layer for checkpointing values in a computational pipeline stage.\n When recomputation is enabled, these values will not be recomputed and they\n will be stored in memory instead.\n\n This layer can reduce memory liveness peaks when using recomputation if\n there are too many activations which need to be recomputed before the\n backpropagation operations can be executed.\n\n This layer should be used with the\n `RecomputationMode.RecomputeAndBackpropagateInterleaved` pipelining\n recomputation mode.\n\n Note that this layer has no effect when used with the\n `RecomputationMode.RecomputeThenBackpropagate` pipelining\n recomputation mode.\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def call(self, inputs, **kwargs):\n \"\"\"\n Checkpoint the input tensors.\n\n Args:\n inputs: A tensor or a structure of tensors which should be checkpointed.\n\n Returns:\n A tensor or a structure of tensors which matches shape and type of\n `inputs`.\n \"\"\"\n return pipelining_ops.recomputation_checkpoint(inputs, name=self.name)\n\n def get_config(self):\n return {}\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for IPU Keras Model\"\"\"\n\nimport numpy as np\nimport pva\n\nfrom tensorflow.python.ipu.config import IPUConfig\nfrom tensorflow.compiler.plugin.poplar.driver.trace_pb2 import IpuTraceEvent\nfrom tensorflow.compiler.plugin.poplar.tests import test_utils as tu\nfrom tensorflow.python import ipu\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.engine import base_layer_utils\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import gradient_descent\n\n\ndef test_dataset(length=None, batch_size=1, x_val=1.0, y_val=0.2):\n constant_d = constant_op.constant(x_val, shape=[32])\n constant_l = constant_op.constant(y_val, shape=[2])\n\n ds = dataset_ops.Dataset.from_tensors((constant_d, constant_l))\n ds = ds.repeat(length)\n ds = ds.batch(batch_size, drop_remainder=True)\n\n return ds\n\n\ndef test_inference_dataset(length=None, batch_size=1, x_val=1.0):\n constant_d = constant_op.constant(x_val, shape=[32])\n\n ds = dataset_ops.Dataset.from_tensors(constant_d)\n ds = ds.repeat(length)\n ds = ds.batch(batch_size, drop_remainder=True)\n\n return ds\n\n\ndef test_dataset_two_input_output(length=None,\n batch_size=1,\n x_val=1.0,\n y_val=0.2,\n input_names=None,\n target_names=None):\n ds = dataset_ops.Dataset.from_tensors(({\n input_names[0]:\n constant_op.constant(x_val, shape=[32]),\n input_names[1]:\n constant_op.constant(x_val, shape=[16])\n }, {\n target_names[0]:\n constant_op.constant(y_val, shape=[2]),\n target_names[1]:\n constant_op.constant(y_val, shape=[1])\n }))\n ds = ds.repeat(length)\n ds = ds.batch(batch_size, drop_remainder=True)\n\n return ds\n\n\ndef test_dataset_two_input_output_np(length=96,\n x_val=1.0,\n y_val=0.2,\n input_names=None,\n target_names=None):\n inputs = {\n input_names[0]: np.ones((length, 32), dtype=np.float32) * x_val,\n input_names[1]: np.ones((length, 16), dtype=np.float32) * x_val\n }\n targets = {\n target_names[0]: np.ones((length, 2), dtype=np.float32) * y_val,\n target_names[1]: np.ones((length, 1), dtype=np.float32) * y_val\n }\n\n return (inputs, targets)\n\n\ndef simple_model(x, layer_sizes, w=None):\n assert layer_sizes\n\n init = 'glorot_uniform'\n if w:\n assert w > 0\n init = keras.initializers.Constant(w)\n\n y = keras.layers.Dense(layer_sizes[0],\n activation=keras.activations.relu,\n kernel_initializer=init)(x)\n\n for n in layer_sizes[1:]:\n y = keras.layers.Dense(n,\n activation=keras.activations.relu,\n kernel_initializer=init)(y)\n return y\n\n\nclass BatchCallbackCounter(keras.callbacks.Callback):\n def __init__(self):\n super(BatchCallbackCounter, self).__init__()\n self._count = 0\n self._logs = []\n\n def on_batch_end(self, batch, logs=None):\n self._logs.append(logs)\n self._count = self._count + 1\n\n def count(self):\n return self._count\n\n def logs(self):\n return self._logs\n\n\nclass IPUModelModelTest(test.TestCase):\n @test_util.run_v2_only\n def testModelCreation(self):\n # Simple single input, single output model.\n input_layer = keras.layers.Input(shape=(2))\n x = simple_model(input_layer, [2, 4])\n y = keras.layers.Activation(keras.activations.relu)(x)\n m = keras.Model(inputs=input_layer, outputs=y)\n\n # Verify dims.\n self.assertEqual(\n m._input_layers[0].get_output_at(0).get_shape().as_list(), # pylint: disable=protected-access\n [None, 2])\n self.assertEqual(\n m._output_layers[0].get_output_at(0).get_shape().as_list(), [None, 4]) # pylint: disable=protected-access\n\n @test_util.run_v2_only\n def testModelCreationMultipleInput(self):\n # Simple two input, one output model.\n input_layer = keras.layers.Input(shape=(2))\n input_layer_two = keras.layers.Input(shape=(2))\n\n x = simple_model(input_layer, [2, 4])\n xx = simple_model(input_layer_two, [2, 4])\n\n x_con = keras.layers.concatenate([x, xx])\n y = keras.layers.Activation(keras.activations.relu)(x_con)\n\n m = keras.Model(inputs=[input_layer, input_layer_two], outputs=y)\n\n # Verify dims.\n self.assertEqual(len(m._input_layers), 2) # pylint: disable=protected-access\n for d in m._input_layers: # pylint: disable=protected-access\n self.assertEqual(d.get_output_at(0).get_shape().as_list(), [None, 2])\n self.assertEqual(\n m._output_layers[0].get_output_at(0).get_shape().as_list(), [None, 8]) # pylint: disable=protected-access\n\n @test_util.run_v2_only\n def testModelCreationMultipleOutput(self):\n # Simple one input, two output model.\n input_layer = keras.layers.Input(shape=(2))\n x = simple_model(input_layer, [2, 4])\n\n y = keras.layers.Activation(keras.activations.tanh)(x)\n yy = keras.layers.Activation(keras.activations.sigmoid)(x)\n\n m = keras.Model(inputs=input_layer, outputs=[y, yy])\n\n self.assertEqual(\n m._input_layers[0].get_output_at(0).get_shape().as_list(), # pylint: disable=protected-access\n [None, 2])\n self.assertEqual(len(m._output_layers), 2) # pylint: disable=protected-access\n for d in m._output_layers: # pylint: disable=protected-access\n self.assertEqual(d.get_output_at(0).get_shape().as_list(), [None, 4])\n\n @test_util.run_v2_only\n def testMustCallCompileFit(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n with self.assertRaisesRegex(\n RuntimeError, \"You must compile your model before training/testing\"):\n m.fit(test_dataset())\n\n @test_util.run_v2_only\n def testMustCallCompileEvaluate(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n with self.assertRaisesRegex(\n RuntimeError, \"You must compile your model before training/testing\"):\n m.evaluate(test_dataset())\n\n @test_util.run_v2_only\n def testNeedTupleDatasetFit(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8])\n m = keras.Model(inputs=input_layer, outputs=x)\n m.compile('sgd', loss='mse')\n\n with self.assertRaisesRegex(ValueError,\n r\"When providing an infinite dataset\"):\n m.fit(test_inference_dataset())\n\n @test_util.run_v2_only\n def testNeedTupleDatasetEvaluate(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8])\n m = keras.Model(inputs=input_layer, outputs=x)\n m.compile('sgd', loss='mse')\n\n with self.assertRaisesRegex(ValueError,\n r\"When providing an infinite dataset\"):\n m.evaluate(test_inference_dataset())\n\n # @test_util.run_v2_only\n def testNeedNonTupleDatasetPredict(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n with self.assertRaisesRegex(ValueError,\n r\"When providing an infinite dataset\"):\n m.predict(test_dataset())\n\n @test_util.run_v2_only\n def testUnlimitedDatasetHasNoStepsPerEpoch(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n m.compile('sgd', loss='mse')\n\n with self.assertRaisesRegex(ValueError,\n r\"When providing an infinite dataset\"):\n m.fit(test_dataset(), epochs=2)\n\n @test_util.run_v2_only\n def testResultsOneEpochWithTfOptimizerNoAccumulation_CpuMatch(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = gradient_descent.GradientDescentOptimizer(0.001)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n history = m.fit(test_dataset(length=96))\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 1)\n\n # Run the CPU equivalent.\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m_cpu = keras.Model(inputs=input_layer, outputs=x)\n opt_cpu = gradient_descent.GradientDescentOptimizer(0.001)\n m_cpu.compile(opt_cpu, loss='mse')\n\n # Fit the weights to the dataset\n cpu_loss = m_cpu.fit(test_dataset(length=96)).history['loss'][0]\n\n # history['loss'] is one loss value per epoch (of which there is 1)\n ipu_loss = history.history['loss'][0]\n\n self.assertAllClose(ipu_loss, cpu_loss)\n\n @test_util.run_v2_only\n def testFitWithTensorData(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Input data\n input_x = constant_op.constant(1.0, shape=[72, 32])\n input_y = constant_op.constant(0.2, shape=[72, 2])\n\n # Fit the weights to the dataset\n history = m.fit(input_x, input_y, batch_size=1)\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 1)\n self.assertEqual(type(history.history['loss'][0]), float)\n\n @test_util.run_v2_only\n def testFitWithNumpyData(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Input data\n input_x = np.full([72, 32], 1.0, dtype=np.single)\n input_y = np.full([72, 2], 0.2, dtype=np.single)\n\n # Fit the weights to the dataset\n history = m.fit(input_x, input_y, batch_size=1)\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 1)\n self.assertEqual(type(history.history['loss'][0]), float)\n\n @test_util.run_v2_only\n def testEvalWithNumpyData(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Input data\n input_x = np.full([72, 32], 1.0, dtype=np.single)\n input_y = np.full([72, 2], 0.2, dtype=np.single)\n\n # Fit the weights to the dataset\n result = m.evaluate(input_x, input_y, batch_size=1)\n self.assertEqual(type(result), float)\n\n @test_util.run_v2_only\n def testPredictWithNumpyDataBs1(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse', steps_per_execution=8)\n\n # Input data\n input_x = np.full([96, 32], 1.0, dtype=np.single)\n\n # Generate predictions\n result = m.predict(input_x, batch_size=1)\n\n self.assertEqual(type(result), np.ndarray)\n self.assertEqual(result.shape[0], 96)\n for i, r in enumerate(result):\n self.assertAllEqual(r, result[i - 1])\n\n # Compare with CPU\n m = keras.Model(inputs=input_layer, outputs=x)\n cpu_result = m.predict(input_x, batch_size=1)\n\n self.assertEqual(cpu_result.shape, result.shape)\n\n @test_util.run_v2_only\n def testFitHistoryWithKerasOptimizer(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n history = m.fit(test_dataset(length=72))\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 1)\n self.assertEqual(type(history.history['loss'][0]), float)\n\n @test_util.run_v2_only\n def testFitHistoryTwoEpochs(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n history = m.fit(test_dataset(length=72), epochs=2)\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 2)\n self.assertEqual(type(history.history['loss'][0]), float)\n self.assertEqual(type(history.history['loss'][1]), float)\n\n @test_util.run_v2_only\n def testFitHistoryStepsPerExecution(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse', steps_per_execution=2)\n\n # Check that the callback is called for every two steps due to\n # `steps_per_execution`.\n cb = BatchCallbackCounter()\n m.fit(test_dataset(length=96), callbacks=[cb])\n self.assertEqual(cb.count(), 48)\n\n @test_util.run_v2_only\n def testFitTwice(self):\n cfg = IPUConfig()\n report_helper = tu.ReportHelper()\n report_helper.set_autoreport_options(cfg, output_execution_profile=True)\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n ds = test_dataset()\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [16, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n history = m.fit(ds, steps_per_epoch=1)\n l = history.history['loss'][0]\n\n # # Record weights\n w_1 = [w.numpy() for w in m.weights]\n\n # Fit the weights to the dataset\n history = m.fit(ds, steps_per_epoch=1)\n\n # Loss should be different after second training.\n self.assertTrue(l > history.history['loss'][0])\n\n w_2 = [w.numpy() for w in m.weights]\n\n # Weights should be different too.\n for w1, w2 in zip(w_1, w_2):\n self.assertFalse(np.all(w1 == w2))\n\n # Should have compiled the graph once, and executed twice.\n self.assert_num_reports(report_helper, 1)\n report = pva.openReport(report_helper.find_report())\n self.assert_number_of_executions(report, 2)\n report_helper.clear_reports()\n\n # Fit the weights with a new dataset\n history = m.fit(test_dataset(), steps_per_epoch=1)\n\n # Loss should be different after second training.\n self.assertTrue(l > history.history['loss'][0])\n\n w_3 = [w.numpy() for w in m.weights]\n\n # Weights should be different too.\n for w2, w3 in zip(w_2, w_3):\n self.assertFalse(np.all(w2 == w3))\n\n # Don't need to compile the graph again.\n self.assert_num_reports(report_helper, 0)\n\n @test_util.run_v2_only\n def testFitHistoryStepsPerEpochTwoEpochs(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n history = m.fit(test_dataset(), steps_per_epoch=144, epochs=2)\n\n # Should be only a loss stored in the history, and it should contain\n # only the single epochs value\n self.assertEqual(list(history.history.keys()), ['loss'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(len(history.history['loss']), 2)\n self.assertEqual(type(history.history['loss'][0]), float)\n self.assertEqual(type(history.history['loss'][1]), float)\n\n @test_util.run_v2_only\n def testFitWithLearningRateDecay(self):\n cfg = IPUConfig()\n cfg.ipu_model.compile_ipu_code = False\n tu.enable_ipu_events(cfg)\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n report_json = tu.ReportJSON(self, eager_mode=True)\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n # Clear old reports\n report_json.reset()\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001,\n decay=0.1)\n m.compile(opt, loss='mse', steps_per_execution=8)\n\n # Fit the weights to the dataset\n m.fit(test_dataset(length=72), epochs=4)\n\n # Ensure that we are only downloading the weights at the end of each\n # epoch.\n report_json.parse_log()\n report_json.assert_num_host_to_device_transfer_events(4)\n\n @test_util.run_v2_only\n def testFitWithExponentialDecayLearningRateSchedule(self):\n cfg = IPUConfig()\n cfg.ipu_model.compile_ipu_code = False\n tu.enable_ipu_events(cfg)\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n report_json = tu.ReportJSON(self, eager_mode=True)\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n # Clear old reports\n report_json.reset()\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n lrs = keras.optimizer_v2.learning_rate_schedule.ExponentialDecay(\n 0.001, 4, 0.1, staircase=True)\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=lrs)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n m.fit(test_dataset(length=72), epochs=4)\n\n # Ensure that we are only downloading the weights at the end of each\n # epoch.\n report_json.parse_log()\n report_json.assert_num_host_to_device_transfer_events(4)\n\n @test_util.run_v2_only\n def testFitWithPiecewiseConstantDecayLearningRateSchedule(self):\n cfg = IPUConfig()\n cfg.ipu_model.compile_ipu_code = False\n tu.enable_ipu_events(cfg)\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n report_json = tu.ReportJSON(self, eager_mode=True)\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n # Clear old reports\n report_json.reset()\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n lrs = keras.optimizer_v2.learning_rate_schedule.PiecewiseConstantDecay(\n boundaries=[8, 16], values=[0.001, 0.0005, 0.0001])\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=lrs)\n m.compile(opt, loss='mse')\n\n # Fit the weights to the dataset\n m.fit(test_dataset(length=72), epochs=4)\n\n # Ensure that we are only downloading the weights at the end of each\n # epoch.\n report_json.parse_log()\n report_json.assert_num_host_to_device_transfer_events(4)\n\n @test_util.run_v2_only\n def testFitWithMetrics(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2])\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.0001)\n m.compile(opt, loss='mse', metrics=['accuracy'], steps_per_execution=2)\n\n # Fit the weights to the dataset\n history = m.fit(test_dataset(), steps_per_epoch=2, epochs=2)\n\n self.assertEqual(list(history.history.keys()), ['loss', 'accuracy'])\n self.assertEqual(type(history.history['loss']), list)\n self.assertEqual(type(history.history['accuracy']), list)\n self.assertEqual(len(history.history['loss']), 2)\n self.assertEqual(type(history.history['loss'][0]), float)\n self.assertEqual(len(history.history['accuracy']), 2)\n self.assertEqual(type(history.history['loss'][1]), float)\n self.assertEqual(type(history.history['accuracy'][0]), float)\n self.assertEqual(type(history.history['accuracy'][1]), float)\n\n @test_util.run_v2_only\n def testEval_CpuMatch(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n m.compile(\"sgd\", loss='mse')\n\n # Fit the weights to the dataset\n result = m.evaluate(test_dataset(length=96))\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m_cpu = keras.Model(inputs=input_layer, outputs=x)\n m_cpu.compile(\"sgd\", loss='mse')\n cpu_result = m.evaluate(test_dataset(length=96))\n\n self.assertAllClose(result, cpu_result)\n\n @test_util.run_v2_only\n def testCallOrder(self):\n # Test which verifies that we can call evaluate/predict before fit.\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n m.compile(optimizer=\"rmsprop\", loss='mse')\n\n # Fit the weights to the dataset\n m.evaluate(test_dataset(length=96))\n m.predict(test_inference_dataset(length=96))\n m.fit(test_dataset(length=96))\n # No exception.\n\n @test_util.run_v2_only\n def testPredict_CpuMatch(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n # Generate predictions\n ipu_out = m.predict(test_inference_dataset(length=96))\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [8, 8, 2], w=0.4)\n m_cpu = keras.Model(inputs=input_layer, outputs=x)\n cpu_out = m_cpu.predict(test_inference_dataset(length=96))\n\n self.assertAllClose(cpu_out, ipu_out)\n\n @test_util.run_v2_only\n def testTrainMultipleInput(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_a = keras.layers.Input(shape=(32))\n input_b = keras.layers.Input(shape=(16))\n\n block_a = simple_model(input_a, [8, 8], w=0.4)\n block_b = simple_model(input_b, [8, 8], w=0.4)\n\n concat_ab = keras.layers.concatenate([block_a, block_b])\n\n block_c = simple_model(concat_ab, [32, 2])\n block_d = simple_model(concat_ab, [32, 1])\n\n m = keras.Model(inputs=[input_a, input_b], outputs=[block_c, block_d])\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n m.compile(\"sgd\", loss=['mse', 'mse'], steps_per_execution=2)\n\n ds = test_dataset_two_input_output(\n length=96,\n batch_size=4,\n input_names=[input_a.name, input_b.name],\n target_names=[\n block_c.name.partition(\"/\")[0],\n block_d.name.partition(\"/\")[0]\n ])\n\n m.fit(ds)\n\n @test_util.run_v2_only\n def testTrainMultipleInputMap(self):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_a = keras.layers.Input(shape=(32))\n input_b = keras.layers.Input(shape=(16))\n\n block_a = simple_model(input_a, [8, 8], w=0.4)\n block_b = simple_model(input_b, [8, 8], w=0.4)\n\n concat_ab = keras.layers.concatenate([block_a, block_b])\n\n block_c = simple_model(concat_ab, [32, 2])\n block_d = simple_model(concat_ab, [32, 1])\n\n m = keras.Model(inputs=[input_a, input_b], outputs=[block_c, block_d])\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n m.compile(\"sgd\", loss=['mse', 'mse'], metrics=['accuracy'])\n\n ds = test_dataset_two_input_output_np(\n length=96,\n input_names=[input_a.name, input_b.name],\n target_names=[\n block_c.name.partition(\"/\")[0],\n block_d.name.partition(\"/\")[0]\n ])\n m.fit(*ds, batch_size=4)\n\n @test_util.run_v2_only\n def testPredictNumpyData(self):\n xs = np.stack([np.ones(32, dtype=np.float32) * i for i in range(48)])\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n ipu_out = m.predict(xs, batch_size=2)\n\n # CPU\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=x)\n cpu_out = m.predict(xs, batch_size=2)\n\n self.assertEqual(cpu_out.shape, ipu_out.shape)\n self.assertAllClose(cpu_out, ipu_out)\n\n @test_util.run_v2_only\n def testPredictNumpyDataTwoOutput(self):\n xs = np.stack([np.ones(32, dtype=np.float32) * i for i in range(48)])\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=[x, x])\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n ipu_out = m.predict(xs, batch_size=2)\n\n # CPU\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=[x, x])\n cpu_out = m.predict(xs, batch_size=2)\n\n for t_cpu, t_ipu in zip(cpu_out, ipu_out):\n self.assertAllClose(t_cpu, t_ipu)\n\n @test_util.run_v2_only\n def testPredictNumpyData3D(self):\n xs = np.stack([np.ones(32, dtype=np.float32) * i for i in range(48)])\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 48], w=1)\n x = keras.layers.Reshape((4, 4, 3))(x)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n ipu_out = m.predict(xs, batch_size=2)\n\n # CPU\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 48], w=1)\n x = keras.layers.Reshape((4, 4, 3))(x)\n m = keras.Model(inputs=input_layer, outputs=x)\n cpu_out = m.predict(xs, batch_size=2)\n\n self.assertEqual(cpu_out.shape, ipu_out.shape)\n self.assertAllClose(cpu_out, ipu_out)\n\n @test_util.run_v2_only\n def testPredictNumpyDataTwoOutput3D(self):\n xs = np.stack([np.ones(32, dtype=np.float32) * i for i in range(48)])\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 48], w=1)\n x = keras.layers.Reshape((4, 4, 3))(x)\n m = keras.Model(inputs=input_layer, outputs=[x, x])\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n ipu_out = m.predict(xs, batch_size=2)\n\n # CPU\n xs = np.stack([np.ones(32, dtype=np.float32) * i for i in range(48)])\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 48], w=1)\n x = keras.layers.Reshape((4, 4, 3))(x)\n m = keras.Model(inputs=input_layer, outputs=[x, x])\n cpu_out = m.predict(xs, batch_size=2)\n\n self.assertEqual(np.shape(cpu_out), np.shape(ipu_out))\n for t_cpu, t_ipu in zip(cpu_out, ipu_out):\n self.assertAllClose(t_cpu, t_ipu)\n\n @test_util.run_v2_only\n def testFitVanillaKerasMatch(self):\n # IPU Model.\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n m.compile('sgd', 'mse')\n ipu_out = m.fit(test_dataset(length=96), epochs=2)\n\n # CPU Model.\n input_layer = keras.layers.Input(shape=(32))\n x = simple_model(input_layer, [32, 32, 1], w=1)\n m = keras.Model(inputs=input_layer, outputs=x)\n\n m.compile('sgd', 'mse')\n cpu_out = m.fit(test_dataset(length=96), epochs=2)\n\n # Compare.\n self.assertAllClose(ipu_out.history['loss'], cpu_out.history['loss'])\n\n @test_util.run_v2_only\n def testTrainMultipleInputMultipleOutput(self):\n # 3 inputs, 2 outputs.\n def data_fn():\n x1 = np.ones((32), dtype=np.float64)\n x2 = np.ones((32), dtype=np.float64)\n x3 = np.ones((32), dtype=np.float64)\n y1 = np.ones((1), dtype=np.float64)\n y2 = np.ones((1), dtype=np.float64)\n ds_x = dataset_ops.Dataset.from_tensors((x1, x2, x3))\n ds_y = dataset_ops.Dataset.from_tensors((y1, y2))\n ds_xy = dataset_ops.Dataset.zip(\n (ds_x, ds_y)).repeat(32).batch(4, drop_remainder=True)\n return ds_xy\n\n # Intentional skip from input to middle of model.\n def model_fn():\n input_1 = keras.Input(32)\n input_2 = keras.Input(32)\n input_3 = keras.Input(32)\n\n init = keras.initializers.Constant(1)\n\n dense_1 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_1)\n dense_2 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_2)\n\n cat = keras.layers.Concatenate()([dense_1, dense_2, input_3])\n\n dense_3 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu,\n name=\"output1\")(cat)\n dense_4 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu,\n name=\"output2\")(cat)\n\n return ((input_1, input_2, input_3), (dense_3, dense_4))\n\n # IPU Test.\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n out = model.fit(data_fn(), steps_per_epoch=1, epochs=2)\n\n # CPU Test.\n cpu_model = keras.Model(*model_fn())\n cpu_model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n cpu_out = cpu_model.fit(data_fn(), steps_per_epoch=1, epochs=2)\n\n # Comparison.\n self.assertEqual(len(out.history), len(cpu_out.history))\n\n # Check per output loss and metrics exist.\n self.assertTrue(\"output1_loss\" in out.history)\n self.assertTrue(\"output2_loss\" in out.history)\n self.assertTrue(\"output1_accuracy\" in out.history)\n self.assertTrue(\"output2_accuracy\" in out.history)\n\n for key in out.history:\n self.assertAllClose(out.history[key], cpu_out.history[key])\n\n @test_util.run_v2_only\n def testNestedClasses(self):\n init = keras.initializers.Constant(1)\n\n # 3 inputs, 2 outputs.\n def data_fn():\n x1 = np.ones((64, 32), dtype=np.float32)\n x2 = np.ones((64, 32), dtype=np.float32)\n x3 = np.ones((64, 32), dtype=np.float32)\n\n y1 = np.ones((64, 1), dtype=np.float32)\n y2 = np.ones((64, 3), dtype=np.float32)\n\n return (x1, x2, x3), (y1, y2)\n\n # pylint: disable=abstract-method\n class MyDenseModel(keras.Model):\n def __init__(self, units):\n super().__init__()\n self.dense1 = keras.layers.Dense(units,\n kernel_initializer=init,\n activation=keras.activations.relu)\n self.dense2 = keras.layers.Dense(units,\n kernel_initializer=init,\n activation=keras.activations.softmax)\n\n # pylint: disable=arguments-differ\n def call(self, in0, in1):\n x = self.dense1(in0)\n return x, self.dense2(in1)\n\n class MyLayer(keras.layers.Layer):\n def __init__(self):\n super().__init__()\n self.concat = keras.layers.Concatenate()\n self.dense1 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)\n self.dense2 = keras.layers.Dense(3,\n kernel_initializer=init,\n activation=keras.activations.softmax)\n\n # pylint: disable=arguments-differ\n def call(self, inputs):\n cat = self.concat(inputs)\n return ((self.dense1(cat),), self.dense2(cat))\n\n def model_fn():\n input_1 = keras.Input(32)\n input_2 = keras.Input(32)\n input_3 = keras.Input(32)\n\n dense_1, dense_2 = MyDenseModel(16)(input_1, input_2)\n output = MyLayer()([dense_1, dense_2, input_3])\n\n return ((input_1, input_2, input_3), ((output[0][0], output[1])))\n\n # IPU Test.\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'])\n\n out = model.fit(*data_fn(), batch_size=4)\n\n # CPU Test.\n cpu_model = keras.Model(*model_fn())\n cpu_model.compile('sgd', ['mse', 'mse'])\n\n cpu_out = cpu_model.fit(*data_fn(), batch_size=4)\n\n # Comparison.\n self.assertEqual(np.shape(cpu_out), np.shape(out))\n self.assertAllClose(out.history['loss'], cpu_out.history['loss'])\n\n @test_util.run_v2_only\n def testPredictMultipleOutput(self):\n def predict_input_fn():\n x1 = np.ones((64, 32), dtype=np.float32)\n x2 = np.ones((64, 32), dtype=np.float32)\n x3 = np.ones((64, 32), dtype=np.float32)\n\n return (x1, x2, x3)\n\n # Intentional skip from input to middle of model.\n def model_fn():\n input_1 = keras.Input(32)\n input_2 = keras.Input(32)\n input_3 = keras.Input(32)\n\n init = keras.initializers.Constant(1)\n\n dense_1 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_1)\n dense_2 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_2)\n\n cat = keras.layers.Concatenate()([dense_1, dense_2, input_3])\n\n dense_3 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n dense_4 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n\n return ((input_1, input_2, input_3), ((dense_3, dense_4)))\n\n # IPU Test.\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'])\n\n ipu_predict_out = model.predict(predict_input_fn(), batch_size=4)\n\n # CPU Test.\n cpu_model = keras.Model(*model_fn())\n cpu_model.compile('sgd', ['mse', 'mse'])\n\n cpu_predict_out = cpu_model.predict(predict_input_fn(), batch_size=4)\n\n # Comparison.\n self.assertAllClose(cpu_predict_out, ipu_predict_out)\n\n @test_util.run_v2_only\n def testPredictMultipleOutputDifferentShapes(self):\n def predict_input_fn():\n x1 = np.ones((64, 32), dtype=np.float32)\n x2 = np.ones((64, 32), dtype=np.float32)\n x3 = np.ones((64, 32), dtype=np.float32)\n\n return (x1, x2, x3)\n\n # Intentional skip from input to middle of model.\n def model_fn():\n input_1 = keras.Input(32)\n input_2 = keras.Input(32)\n input_3 = keras.Input(32)\n\n init = keras.initializers.Constant(1)\n\n dense_1 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_1)\n dense_2 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_2)\n\n cat = keras.layers.Concatenate()([dense_1, dense_2, input_3])\n\n dense_3 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n dense_4 = keras.layers.Dense(2,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n dense_5 = keras.layers.Dense(2,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n\n return ((input_1, input_2, input_3), (dense_3, (dense_4, dense_5)))\n\n # CPU Test.\n cpu_model = keras.Model(*model_fn())\n cpu_model.compile('sgd', ['mse', 'mse', 'mse'])\n\n cpu_predict_out = cpu_model.predict(predict_input_fn(), batch_size=4)\n\n # IPU Test.\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse', 'mse'])\n\n ipu_predict_out = model.predict(predict_input_fn(), batch_size=4)\n\n self.assertAllClose(cpu_predict_out, ipu_predict_out)\n\n @test_util.run_v2_only\n def testAutocast_ComplexDatasetStructure(self):\n base_layer_utils.enable_v2_dtype_behavior()\n\n def f():\n input_1 = keras.Input(32)\n input_2 = keras.Input(32)\n input_3 = keras.Input(32)\n\n init = keras.initializers.Constant(1)\n\n dense_1 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_1)\n dense_2 = keras.layers.Dense(16,\n kernel_initializer=init,\n activation=keras.activations.relu)(input_2)\n\n cat = keras.layers.Concatenate()([dense_1, dense_2, input_3])\n\n dense_3 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n dense_4 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu)(cat)\n\n return ((input_1, input_2, input_3), (dense_3, dense_4))\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n m = keras.Model(*f())\n\n opt = keras.optimizer_v2.gradient_descent.SGD(learning_rate=0.001)\n m.compile(opt, loss='mse')\n\n # Input data\n x1 = np.ones((32), dtype=np.float64)\n x2 = np.ones((32), dtype=np.float64)\n x3 = np.ones((32), dtype=np.float64)\n y1 = np.ones((1), dtype=np.float64)\n y2 = np.ones((1), dtype=np.float64)\n ds_x = dataset_ops.Dataset.from_tensors((x1, x2, x3))\n ds_y = dataset_ops.Dataset.from_tensors((y1, y2))\n ds_xy = dataset_ops.Dataset.zip(\n (ds_x, ds_y)).repeat(32).batch(4, drop_remainder=True)\n ds_x_tuple = dataset_ops.Dataset.zip(\n (ds_x,)).repeat(32).batch(4, drop_remainder=True)\n\n m.fit(ds_xy)\n m.predict(ds_x_tuple)\n m.evaluate(ds_xy)\n\n # No exceptions thrown\n\n @test_util.run_v2_only\n def testUint8(self):\n dataset = dataset_ops.Dataset.from_tensor_slices(np.array(range(30)))\n dataset = dataset.map(lambda x: math_ops.cast(x, dtype=np.uint8)).batch(\n 1, drop_remainder=True).batch(1, drop_remainder=True)\n\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n i = keras.layers.Input(shape=[1])\n ci = keras.layers.Lambda(lambda x: math_ops.cast(x, dtype=np.float16))(i)\n o = keras.layers.Dense(1, kernel_initializer='ones')(ci)\n m = keras.Model(i, o)\n\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n m.compile(steps_per_execution=10)\n output = m.predict(dataset)\n self.assertAllClose(output.flatten(), range(30))\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nfrom unittest import mock\n\nimport numpy as np\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.ipu.config import IPUConfig\n\nfrom tensorflow.compiler.plugin.poplar.tests import test_utils as tu\nfrom tensorflow.python import ipu\nfrom tensorflow.python.client import session as sl\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\n\nfrom tensorflow.python import keras\n\n\ndef create_n_replica_ipu_config(ipu_count):\n cfg = IPUConfig()\n cfg.optimizations.maximum_cross_replica_sum_buffer_size = 10000\n cfg.auto_select_ipus = ipu_count\n tu.add_hw_ci_connection_options(cfg)\n\n return cfg\n\n\ndef create_constant_repeating_dataset(value, shape):\n dataset = dataset_ops.Dataset.from_tensors(\n constant_op.constant(value, shape=shape))\n return dataset.repeat()\n\n\ndef run_body_repeatedly(body, inputs, infeed, iterations, config):\n def my_net():\n r = ipu.loops.repeat(iterations, body, inputs, infeed)\n return r\n\n with ipu.scopes.ipu_scope(\"/device:IPU:0\"):\n res = ipu.ipu_compiler.compile(my_net, inputs=[])\n\n config.configure_ipu_system()\n\n with sl.Session() as sess:\n sess.run(infeed.initializer)\n result = sess.run(res)\n return result\n\n\n@test_util.deprecated_graph_mode_only\nclass TestAssumeEqual(test_util.TensorFlowTestCase, parameterized.TestCase):\n # assume_equal_across_replicas supports copying or inplace operation depending\n # on the value of the inplace argument\n inplace_or_copy = [True, False]\n\n # the issue in this test can't be reproduces with 2 ipus.\n @tu.test_uses_ipus(num_ipus=4)\n # v2 only since TF 1.15 cant handle the non-compile time slicing\n # of replica_dependent_value\n @test_util.run_v2_only\n def testNoDivergenceWithSlicedTensor(self):\n input_shape = [10]\n dataset = create_constant_repeating_dataset(1.0, input_shape)\n\n infeed_queue = ipu.ipu_infeed_queue.IPUInfeedQueue(dataset)\n outfeed_queue = ipu.ipu_outfeed_queue.IPUOutfeedQueue()\n\n def no_divergence_with_sliced_tensor(index, total,\n replica_dependent_value):\n def _enq_fn(to_enq):\n return outfeed_queue.enqueue(to_enq)\n\n # This test cant be inplace since we're using tensor slices.\n inplace = False\n safe_value = ipu.cross_replica_ops.assume_equal_across_replicas(\n replica_dependent_value[index], inplace)\n intermediate = ipu.ops.cross_replica_ops.cross_replica_sum(safe_value)\n maybe_enqueue_op = control_flow_ops.cond(\n math_ops.greater(intermediate, 0), lambda: _enq_fn(intermediate),\n lambda: control_flow_ops.no_op()) # pylint: disable=W0108\n\n with ops.control_dependencies([maybe_enqueue_op]):\n itermediate = array_ops.identity(intermediate)\n\n return index + 1, total + itermediate, replica_dependent_value\n\n def body(total, replica_dependent_value):\n start = constant_op.constant(0)\n _, total, _ = control_flow_ops.while_loop(\n cond=lambda i, *_: math_ops.less(i, 4),\n body=no_divergence_with_sliced_tensor,\n loop_vars=[start, total, replica_dependent_value])\n return total\n\n total = constant_op.constant(0, shape=input_shape, dtype=np.float32)\n iterations = 1 # we want to provide data from an infeed, not run 'body' repeatedly.\n result = run_body_repeatedly(body, [total], infeed_queue, iterations,\n create_n_replica_ipu_config(4))\n\n # 1(infeed value)*4(replicas)*4(repeats) = 16\n self.assertAllClose(result[0], np.broadcast_to(16.0, input_shape))\n\n @parameterized.parameters(inplace_or_copy)\n @tu.test_uses_ipus(num_ipus=2)\n def testNoDivergenceWithSingleTensor(self, inplace):\n\n input_shape = [2, 4]\n dataset = create_constant_repeating_dataset(1.0, input_shape)\n infeed_queue = ipu.ipu_infeed_queue.IPUInfeedQueue(dataset)\n\n def no_divergence_with_single_tensor(total, replica_dependent_value):\n y = constant_op.constant(2.0, shape=input_shape, dtype=np.float32)\n divergent_true_condition = math_ops.reduce_all(\n math_ops.not_equal(replica_dependent_value, y))\n safe_true_condition = \\\n ipu.ops.cross_replica_ops.assume_equal_across_replicas(\n divergent_true_condition, inplace)\n\n total = control_flow_ops.cond(\n safe_true_condition, lambda: ipu.ops.cross_replica_ops.\n cross_replica_sum(total + replica_dependent_value), lambda:\n constant_op.constant(0.0, shape=input_shape, dtype=np.float32))\n return total\n\n iterations = 2\n total = constant_op.constant(0.0, shape=input_shape, dtype=np.float32)\n result = run_body_repeatedly(no_divergence_with_single_tensor, [total],\n infeed_queue, iterations,\n create_n_replica_ipu_config(2))\n\n # 1(infeed value)*2(replicas) = 2\n # 2+1(infeed value)*2(replicas) = 6\n self.assertAllClose(result[0], np.broadcast_to(6.0, input_shape))\n\n @parameterized.parameters(inplace_or_copy)\n @tu.test_uses_ipus(num_ipus=2)\n def testNoDivergenceWithNestedTensors(self, inplace):\n\n input_shape = [2, 4]\n dataset = create_constant_repeating_dataset(1.0, input_shape)\n infeed_queue = ipu.ipu_infeed_queue.IPUInfeedQueue(dataset)\n\n def no_divergence_with_multiple_tensors(total, x):\n y1 = constant_op.constant(2.0, shape=input_shape, dtype=np.float32)\n y2 = constant_op.constant(3.0, shape=input_shape, dtype=np.float32)\n y3 = constant_op.constant(4.0, shape=input_shape, dtype=np.float32)\n\n divergent_condition1 = math_ops.not_equal(x, y1)\n divergent_condition2 = math_ops.not_equal(x, y2)\n divergent_condition3 = math_ops.not_equal(x, y3)\n divergent_conditions = [\n divergent_condition1, divergent_condition2, divergent_condition3\n ]\n\n safe_conditions = ipu.ops.cross_replica_ops.assume_equal_across_replicas(\n divergent_conditions, inplace)\n safe_condition1, safe_condition2, safe_condition3 = safe_conditions\n\n true_condition = math_ops.reduce_all(\n math_ops.logical_and(\n math_ops.logical_and(safe_condition1, safe_condition2),\n safe_condition3))\n\n total = control_flow_ops.cond(\n true_condition,\n lambda: ipu.ops.cross_replica_ops.cross_replica_sum(total + x),\n lambda: constant_op.constant(\n 0.0, shape=input_shape, dtype=np.float32))\n return total\n\n iterations = 2\n total = constant_op.constant(0.0, shape=input_shape, dtype=np.float32)\n result = run_body_repeatedly(no_divergence_with_multiple_tensors, [total],\n infeed_queue, iterations,\n create_n_replica_ipu_config(2))\n\n # 1(infeed value)*2(replicas) = 2\n # 2+1(infeed value)*2(replicas) = 6\n self.assertAllClose(result[0], np.broadcast_to(6.0, input_shape))\n\n\nclass ConditionalLayer(keras.layers.Layer):\n def call(self, inputs, **kwargs):\n c = constant_op.constant(0, shape=inputs.shape, dtype=inputs.dtype)\n x = math_ops.reduce_all(math_ops.greater(inputs, c))\n y = control_flow_ops.cond(\n x, lambda: ipu.cross_replica_ops.cross_replica_sum(inputs),\n lambda: constant_op.constant(0, shape=(2, 4), dtype=inputs.dtype))\n return y\n\n\nclass TestKerasAssumeEqual(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n @tu.test_uses_ipus(num_ipus=2)\n @test_util.run_v2_only\n def testNoDivergenceWithAssumeEqualLayer(self):\n\n cfg = create_n_replica_ipu_config(2)\n cfg.configure_ipu_system()\n\n strategy = ipu.ipu_strategy.IPUStrategy()\n with strategy.scope():\n\n input_layer = keras.layers.Input(shape=(32),\n dtype=np.single,\n batch_size=2)\n init = keras.initializers.Constant(0.1)\n\n dense_layer = keras.layers.Dense(4,\n name=\"layer0\",\n kernel_initializer=init)(input_layer)\n\n assume_equals_layer = ipu.keras.layers.AssumeEqualAcrossReplicas()(\n dense_layer)\n conditional_layer = ConditionalLayer()(assume_equals_layer)\n\n # Without the AssumeEqualAcrossReplicas layer we should get a Divergent\n # control flow compilation error coming from ConditionalLayer.\n m = keras.Model(input_layer, conditional_layer)\n m.compile('sgd', loss='mse', steps_per_execution=12)\n\n input_x = np.full([96, 32], 1.0, dtype=np.single)\n m.predict(input_x, batch_size=2)\n\n @parameterized.parameters(TestAssumeEqual.inplace_or_copy)\n @test_util.deprecated_graph_mode_only\n @mock.patch.object(ipu.ops.cross_replica_ops, \"assume_equal_across_replicas\")\n def testLayerUsesAssumeEqualOp(self, inplace, mock_op):\n placeholder = array_ops.placeholder(np.single, 32)\n ipu.keras.layers.AssumeEqualAcrossReplicas(inplace)(placeholder)\n\n mock_op.assert_called_with(placeholder, inplace)\n\n @parameterized.parameters(TestAssumeEqual.inplace_or_copy)\n @tu.skip_on_hw\n @test_util.run_v2_only\n def testGetConfig(self, inplace):\n layer = ipu.keras.layers.AssumeEqualAcrossReplicas(inplace)\n self.assertEqual(layer.get_config()[\"inplace\"], inplace)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport pva\nimport numpy as np\nimport test_utils as tu\n\nfrom tensorflow.compiler.tests import xla_test\nfrom tensorflow.python import ipu\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import googletest\n\n\nclass WhileLoopPerfTest(xla_test.XLATestCase):\n def testIpuWhilePerfTest(self):\n cfg = ipu.config.IPUConfig()\n report_helper = tu.ReportHelper()\n report_helper.set_autoreport_options(cfg, output_execution_profile=True)\n cfg.ipu_model.compile_ipu_code = False\n cfg.configure_ipu_system()\n\n with self.session() as sess:\n\n def cond(i, v):\n del v\n return math_ops.less(i, 15)\n\n def body(i, v):\n v = v + i\n i = i + 1\n return (i, v)\n\n def my_net(v):\n i = constant_op.constant(0)\n r = control_flow_ops.while_loop(cond,\n body, (i, v),\n maximum_iterations=10)\n return [r[1]]\n\n with ops.device('cpu'):\n v = array_ops.placeholder(np.int32, [500])\n\n with ipu.scopes.ipu_scope(\"/device:IPU:0\"):\n r = ipu.ipu_compiler.compile(my_net, inputs=[v])\n\n result = sess.run(r, {v: np.zeros([500], np.int32)})\n self.assertAllClose(result[0], np.broadcast_to(45, [500]))\n\n # Check that there is only one real compile\n self.assert_num_reports(report_helper, 1)\n report = pva.openReport(report_helper.find_report())\n # Check that there is only one execute\n self.assert_number_of_executions(report, 1)\n\n\nif __name__ == \"__main__\":\n os.environ['TF_XLA_FLAGS'] = ('--tf_xla_min_cluster_size=1 ' +\n os.environ.get('TF_XLA_FLAGS', ''))\n googletest.main()\n", "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nimport numpy as np\nfrom absl.testing import parameterized\n\nfrom tensorflow.compiler.plugin.poplar.tests import test_utils as tu\nfrom tensorflow.python import ipu\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.ops import array_ops\n\n\nclass TestReplicatedReduceScatter(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n @parameterized.named_parameters(\n ('reduce_add', 'COLLECTIVE_OP_ADD', 4),\n ('reduce_mean', 'COLLECTIVE_OP_MEAN', 1),\n )\n @tu.test_uses_ipus(num_ipus=4)\n @test_util.deprecated_graph_mode_only\n def test_reduce_scatter(self, op, scale):\n with session_lib.Session() as sess:\n num_replicas = 4\n\n outfeed_queue = ipu.ipu_outfeed_queue.IPUOutfeedQueue()\n\n def my_net(*xs):\n y = [\n ipu.ops.reduce_scatter_op.reduce_scatter(\n x, replication_factor=num_replicas, op=op) for x in xs\n ]\n return outfeed_queue.enqueue(y)\n\n inputs = [i * np.arange(i, dtype=np.float32) for i in range(1, 6)]\n with ipu.scopes.ipu_scope(\"/device:IPU:0\"):\n compiled_net = ipu.ipu_compiler.compile(my_net, inputs=inputs)\n\n gathered = []\n with ops.device(\"/device:CPU:0\"):\n dequeued = outfeed_queue.dequeue()\n for scattered in dequeued:\n gathered.append(array_ops.reshape(scattered, shape=[-1]))\n\n cfg = ipu.config.IPUConfig()\n cfg.optimizations.maximum_reduce_scatter_buffer_size = 10000\n cfg.auto_select_ipus = num_replicas\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n sess.run(compiled_net)\n out = sess.run(gathered)\n\n # Check padded lengths.\n self.assertEqual(len(out[0]), np.ceil(1 / num_replicas) * num_replicas)\n self.assertEqual(len(out[1]), np.ceil(2 / num_replicas) * num_replicas)\n self.assertEqual(len(out[2]), np.ceil(3 / num_replicas) * num_replicas)\n self.assertEqual(len(out[3]), np.ceil(4 / num_replicas) * num_replicas)\n self.assertEqual(len(out[4]), np.ceil(5 / num_replicas) * num_replicas)\n\n # Check payloads.\n self.assertAllEqual(1.0 * scale * np.arange(1), out[0][:1])\n self.assertAllEqual(2.0 * scale * np.arange(2), out[1][:2])\n self.assertAllEqual(3.0 * scale * np.arange(3), out[2][:3])\n self.assertAllEqual(4.0 * scale * np.arange(4), out[3][:4])\n self.assertAllEqual(5.0 * scale * np.arange(5), out[4][:5])\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport numpy as np\n\nfrom tensorflow import debugging\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute.reduce_util import ReduceOp\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ipu.config import IPUConfig\nfrom tensorflow.python.ipu import horovod as hvd\nfrom tensorflow.python.ipu.horovod import popdist_strategy\nfrom tensorflow.python.ipu.ipu_multi_worker_strategy import IPUSyncOnReadVariable\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.variable_scope import VariableAggregation, VariableSynchronization\nfrom tensorflow.python.platform import test\n\n\nclass PopDistStrategyTest(test_util.TensorFlowTestCase): # pylint: disable=abstract-method\n @classmethod\n def setUpClass(cls):\n hvd.init()\n\n @classmethod\n def tearDownClass(cls):\n hvd.shutdown()\n\n def test_update_ipu_config(self):\n strategy = popdist_strategy.PopDistStrategy()\n config = IPUConfig()\n strategy.update_ipu_config(config)\n self.assertEqual(\n config.experimental.multi_replica_distribution.process_count,\n hvd.size())\n self.assertEqual(\n config.experimental.multi_replica_distribution.process_index,\n hvd.rank())\n\n def test_strategy(self):\n config = IPUConfig()\n config.auto_select_ipus = 1\n config.configure_ipu_system()\n\n hvd.init()\n\n strategy = popdist_strategy.PopDistStrategy()\n\n with strategy.scope():\n v = variables.Variable(initial_value=hvd.rank() + 1, dtype=np.float32)\n self.assertEndsWith(v.device, \"/device:IPU:0\")\n\n @def_function.function\n def per_replica_fn(x):\n y = v * x\n\n replica_context = distribution_strategy_context.get_replica_context()\n\n # This reduction is done on IPU, and hence uses GCL. In this case,\n # since there is no replication in this test, it is an identity op.\n # We cannot explicitly check for the device of the result, as the\n # @tf.function decorator does not specify this anymore.\n y_all_reduced = replica_context.all_reduce(ReduceOp.SUM, y)\n\n return y_all_reduced\n\n per_replica_value = strategy.run(per_replica_fn,\n args=[constant_op.constant(2.0)])\n\n # This reduction is performed on CPU, and hence uses Horovod.\n value_all_reduced = strategy.reduce(ReduceOp.SUM, per_replica_value)\n\n # The initial value should be broadcast from rank 0.\n self.assertEqual(v, 1.0)\n\n # There should be one allreduce sum of the values.\n self.assertEqual(value_all_reduced, hvd.size() * 2.0)\n\n def test_strategy_without_ipu_reduction(self):\n config = IPUConfig()\n config.auto_select_ipus = 1\n config.configure_ipu_system()\n\n hvd.init()\n\n strategy = popdist_strategy.PopDistStrategy(\n add_ipu_cross_replica_reductions=False)\n\n with strategy.scope():\n v = variables.Variable(initial_value=1.0, dtype=np.float32)\n\n @def_function.function\n def per_replica_fn(x):\n y = v * x\n replica_context = distribution_strategy_context.get_replica_context()\n\n # Since IPU reductions are disabled, this should be an identity op.\n y_out = replica_context.all_reduce(ReduceOp.SUM, y)\n debugging.assert_equal(y_out.op.type, \"IdentityN\")\n debugging.assert_equal(y_out.op.inputs[0], y)\n return y_out\n\n # It is sufficient to test the TF graph construction.\n strategy.run(per_replica_fn, args=[constant_op.constant(2.0)])\n\n def test_strategy_with_sync_on_read_variable(self):\n config = IPUConfig()\n config.auto_select_ipus = 1\n config.configure_ipu_system()\n\n hvd.init()\n\n strategy = popdist_strategy.PopDistStrategy()\n\n with strategy.scope():\n w = variables.Variable(initial_value=float(hvd.rank() + 1),\n dtype=np.float32,\n synchronization=VariableSynchronization.ON_READ,\n aggregation=VariableAggregation.MEAN)\n\n @def_function.function\n def per_replica_fn(x):\n self.assertIsInstance(w, IPUSyncOnReadVariable)\n w.assign(x + w)\n\n return w\n\n # Both should have initial value from first worker\n debugging.assert_equal([1.0], w)\n strategy.run(per_replica_fn,\n args=[constant_op.constant(hvd.rank() + 1.0)])\n debugging.assert_equal([2.5], w.read_value())\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\"Tests for tpu_function helpers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.layers import convolutional\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import special_math_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.tpu import tpu\nfrom tensorflow.python.tpu import tpu_feed\nfrom tensorflow.python.tpu import training_loop\nfrom tensorflow.python.tpu.ops import tpu_ops\n\n\nclass TPUContextTest(test.TestCase):\n\n def testIsInContext(self):\n \"\"\"Test that control_flow_util can check that we're in a TPU context.\"\"\"\n with ops.Graph().as_default():\n z1 = array_ops.identity(1)\n pivot = control_flow_ops.no_op()\n context = tpu.TPUReplicateContext(b\"context\", 1, pivot=pivot)\n context.Enter()\n z2 = array_ops.identity(1)\n context.Exit()\n self.assertFalse(control_flow_util.IsInXLAContext(z1.op))\n self.assertTrue(control_flow_util.IsInXLAContext(z2.op))\n\n def testHandlesNameCollision(self):\n \"\"\"Test AddValue handles name collisions for ops from different graphs.\"\"\"\n with ops.Graph().as_default():\n z = array_ops.zeros([2, 3], name=\"a\")\n assert z.name == \"a:0\", \"Expected: a:0, Found: %s\" % z.name\n\n @def_function.function\n def f():\n pivot = control_flow_ops.no_op()\n context = tpu.TPUReplicateContext(b\"context\", 1, pivot=pivot)\n context.Enter()\n array_ops.identity(z) # Capture z.\n z1 = array_ops.zeros([3, 2], name=\"a\")\n assert z1.name == \"a:0\", \"Expected: a:0, Found: %s\" % z1.name\n z2 = array_ops.zeros([3, 2], name=\"a\")\n # Prior to fixing b/166794533 this would fail with a shape mismatch\n # because context.AddValue would have cached `z` by its name which\n # collides with z1's name.\n result = z1 + z2\n context.Exit()\n return result\n\n f.get_concrete_function()\n\n\nclass TPULayerRewriteTest(test.TestCase):\n\n def testUsingInfeedQueueWithRegularizer(self):\n \"\"\"Test that Layer regularizers can reference data created in loops.\"\"\"\n\n with ops.Graph().as_default():\n\n def make_regularizer(scale):\n def regularizer(inputs):\n return scale * math_ops.reduce_sum(math_ops.square(inputs))\n return regularizer\n\n def training_step(inputs, scale):\n outputs = convolutional.conv2d(\n inputs,\n filters=16,\n kernel_size=(3, 3),\n data_format=\"channels_first\",\n kernel_regularizer=make_regularizer(scale))\n loss = math_ops.reduce_mean(math_ops.square(outputs))\n return loss.op\n\n inputs = array_ops.zeros(shape=(128, 32, 32, 16))\n scale = array_ops.ones(shape=())\n infeed = tpu_feed.InfeedQueue(\n tuple_types=[dtypes.float32, dtypes.float32],\n tuple_shapes=[inputs.shape, scale.shape])\n\n def loop():\n return training_loop.repeat(5, training_step, infeed_queue=infeed)\n\n # This should not throw an error.\n tpu.rewrite(loop)\n\n\nclass TPUGraphPruneTest(test.TestCase):\n\n def test_prune_unconnected_ops(self):\n with ops.Graph().as_default():\n a = array_ops.placeholder(dtype=dtypes.float32, name=\"a\")\n b = array_ops.placeholder(dtype=dtypes.float32, name=\"b\")\n constant_op.constant(1.0, name=\"constant\")\n x = variable_scope.get_variable(\n name=\"x\",\n dtype=dtypes.float32,\n shape=[],\n use_resource=True,\n initializer=init_ops.constant_initializer(2.0))\n y = variable_scope.get_variable(\n name=\"y\",\n dtype=dtypes.float32,\n shape=[],\n use_resource=True,\n initializer=init_ops.constant_initializer(3.0))\n math_ops.add(a, b)\n math_ops.add(x, y)\n graph_def = ops.get_default_graph().as_graph_def()\n\n for node in graph_def.node:\n # Attach a TPU_REPLICATE_ATTR to each node.\n node.attr[tpu._TPU_REPLICATE_ATTR].s = b\"0\"\n # Rewire placeholder \"a\" and variable \"y\" leaving them unconnected.\n for (input_index, node_input) in enumerate(node.input):\n if node_input == \"b\":\n node.input[input_index] = \"constant\"\n if node_input == \"y\":\n node.input[input_index] = \"x\"\n\n with ops.Graph().as_default() as graph:\n # Reimport the graph and prune unconnected ops.\n importer.import_graph_def(graph_def)\n tpu.prune_unconnected_ops_from_xla(ops.get_default_graph())\n\n # Verify that ops \"a\" and \"x\" still have TPU_REPLICATE_ATTR.\n a = graph.get_operation_by_name(\"import/a\").get_attr(\n tpu._TPU_REPLICATE_ATTR)\n self.assertEqual(b\"0\", a)\n x = graph.get_operation_by_name(\"import/x\").get_attr(\n tpu._TPU_REPLICATE_ATTR)\n self.assertEqual(b\"0\", x)\n # Verify that ops \"b\" and \"y\" have TPU_REPLICATE_ATTR removed.\n with self.assertRaisesRegex(\n ValueError,\n \"Operation \\'import/b\\' has no attr named \\'_tpu_replicate\\'\"):\n graph.get_operation_by_name(\"import/b\").get_attr(\n tpu._TPU_REPLICATE_ATTR)\n with self.assertRaisesRegex(\n ValueError,\n \"Operation \\'import/y\\' has no attr named \\'_tpu_replicate\\'\"):\n graph.get_operation_by_name(\"import/y\").get_attr(\n tpu._TPU_REPLICATE_ATTR)\n\n\nclass TPUOpsTest(test.TestCase):\n\n def test_all_to_all_zero_split_count(self):\n with self.assertRaisesRegex(\n ValueError, \"split_count 0 must at least be one\"):\n tpu_ops.all_to_all(\n x=[0.0, 0.1652, 0.6543],\n group_assignment=[1, -1],\n concat_dimension=0,\n split_dimension=0,\n split_count=0)\n\n def test_all_to_all_group_assignment_wrong_shape(self):\n with self.assertRaisesRegex(\n ValueError, \"group_assignment must have rank 2\"):\n tpu_ops.all_to_all(\n x=[0.0, 0.1652, 0.6543],\n group_assignment=[1, -1],\n concat_dimension=0,\n split_dimension=0,\n split_count=2)\n\n def test_all_to_all_split_count_not_equal_to_group_assignment_shape(self):\n with self.assertRaisesRegex(\n ValueError, \"split_count 1 must equal the size of the second dimension \"\n \"of group_assignment 2\"):\n tpu_ops.all_to_all(\n x=[0.0, 0.1652, 0.6543],\n group_assignment=[[0, 1], [2, 3]],\n concat_dimension=0,\n split_dimension=0,\n split_count=1)\n\n def test_all_to_all_split_count_not_divide_input_shape(self):\n with self.assertRaisesRegex(\n ValueError, \"input dimension 3 not divisible by split_count 2\"):\n tpu_ops.all_to_all(\n x=[[0.0], [0.1652], [0.6543]],\n group_assignment=[[0, 1], [2, 3]],\n concat_dimension=1,\n split_dimension=0,\n split_count=2)\n\n\ndef do_einsum():\n a = array_ops.placeholder(dtype=dtypes.float32, name=\"a\", shape=[2, 3, 4])\n b = array_ops.placeholder(dtype=dtypes.float32, name=\"b\", shape=[2, 4, 5])\n return special_math_ops.einsum(\"abc,acd->abd\", a, b)\n\n\ndef find_einsum(g):\n graph_def = g.as_graph_def()\n for node in graph_def.node:\n if node.op == \"Einsum\":\n return True\n return False\n\n\ndef find_xla_einsum(g):\n graph_def = g.as_graph_def()\n for node in graph_def.node:\n if node.op == \"XlaEinsum\":\n return True\n return False\n\n\nclass TPUXlaEinsumTest(test.TestCase):\n\n def test_tpu_rewrite_uses_xla_einsum(self):\n with ops.Graph().as_default() as g:\n tpu.rewrite(do_einsum)\n self.assertTrue(find_einsum(g) or find_xla_einsum(g))\n\n def test_default_does_not_use_xla_einsum(self):\n with ops.Graph().as_default() as g:\n do_einsum()\n self.assertFalse(find_xla_einsum(g))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nStatistics operators\n~~~~~~~~~~~~~~~~~~~~\n\"\"\"\n\nfrom tensorflow.compiler.plugin.poplar.ops import gen_popops_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import math_ops\n\n\ndef fixed_width_bins(inputs, n_bins):\n \"\"\"This op generates evenly spaced levels for histogram binning derived\n from the value range of `inputs`.\n\n Args:\n inputs: A rank-1 tensor of values over which to compute binning levels.\n n_bins: The number of bins required.\n\n Returns:\n A rank-1 tensor of binning values.\n \"\"\"\n min_level = math_ops.reduce_min(inputs)\n max_level = math_ops.reduce_max(inputs)\n return math_ops.linspace(min_level, max_level, n_bins)\n\n\ndef histogram_normalize(hist):\n \"\"\"This op normalizes a histogram.\n\n Args:\n hist: The histogram to be normalized.\n\n Returns:\n The normalized histogram.\n \"\"\"\n return hist / math_ops.reduce_sum(hist, axis=0)\n\n\ndef histogram(inputs, levels, absolute_of_input=False):\n \"\"\"This op generates a histogram of `inputs` over the fixed width bins\n defined by `levels`.\n\n Args:\n inputs: A rank-1 tensor of values over which to compute binning levels.\n n_bins: The number of bins required.\n absolute_of_input: If True, bin on input magnitude (absolute value).\n Default is False.\n\n Returns:\n A rank-1 histogram tensor.\n \"\"\"\n inputs = ops.convert_to_tensor(inputs)\n levels = ops.convert_to_tensor(levels)\n\n # Check dtypes.\n type_check = lambda x: x.dtype in (dtypes.float16, dtypes.float32)\n if not type_check(inputs) or not type_check(levels):\n raise ValueError(\"Only float16 and float32 types are supported for \"\n \"histogram computation.\")\n\n # Check ranks.\n if len(inputs.shape) != 1 or len(levels.shape) != 1:\n raise ValueError(\"histogram expects rank-1 tensor inputs.\")\n\n return gen_popops_ops.ipu_histogram(inputs,\n levels,\n absolute_of_input=absolute_of_input)\n\n\ndef histogram_update(hist, inputs, levels, absolute_of_input=False):\n \"\"\"This op updates the histogram `hist` over the fixed width bins\n defined by `levels` for new `inputs`.\n\n Args:\n inputs: A rank-1 tensor of values over which to compute binning levels.\n n_bins: The number of bins required.\n absolute_of_input: If True, bin on input magnitude (absolute value).\n Default is False.\n\n Returns:\n The updated rank-1 histogram tensor, `hist`.\n \"\"\"\n hist = ops.convert_to_tensor(hist)\n inputs = ops.convert_to_tensor(inputs)\n levels = ops.convert_to_tensor(levels)\n\n # Check dtypes.\n if hist.dtype != dtypes.float32:\n raise ValueError(\"hist must be of float32 type\")\n\n type_check = lambda x: x.dtype in (dtypes.float16, dtypes.float32)\n if not type_check(hist) or not type_check(inputs) or not type_check(levels):\n raise ValueError(\n \"Only float16 and float32 types are supported for histogram update.\")\n\n # Check ranks.\n if len(hist.shape) != 1 or len(inputs.shape) != 1 or len(levels.shape) != 1:\n raise ValueError(\"histogram_update expects rank-1 tensor inputs.\")\n\n # Check hist and levels shapes.\n if hist.shape[0] != levels.shape[0] + 1:\n raise ValueError(\"hist and levels shapes are incompatible. \"\n \"For n levels, hist must have n+1 elements.\")\n\n return gen_popops_ops.ipu_histogram_update(\n hist, inputs, levels, absolute_of_input=absolute_of_input)\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\nimport os\nimport pva\nimport numpy as np\nfrom absl.testing import parameterized\n\nfrom tensorflow.keras import layers\nfrom tensorflow.compiler.plugin.poplar.tests import test_utils as tu\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.training import gradient_descent\nfrom tensorflow.python.training import momentum\nfrom tensorflow.python.ipu import custom_ops\nfrom tensorflow.python.ipu import embedding_ops\nfrom tensorflow.python.ipu import internal_ops\nfrom tensorflow.python.ipu import pipelining_ops\nfrom tensorflow.python.ipu import rand_ops\nfrom tensorflow.python.ipu import utils\nfrom tensorflow.python.ipu.tests import pipelining_test_util\nfrom tensorflow.compat.v1 import disable_v2_behavior\n\ndisable_v2_behavior()\n\n\nclass PipeliningGroupedRecomputationTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n @parameterized.parameters([0, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare1(self, number_of_io_tiles):\n if utils.running_on_ipu_model():\n self.skipTest(\"Replicated top level graphs are not supported on the \"\n \"IPU_MODEL target\")\n\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4, 2])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n def dataset_parser(value):\n img = value / 7\n label = value[0][0][0][0]\n return img, label\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 16\n repeat_count = 1\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def stage1(c, img, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n y = layers.Conv2D(\n 2,\n 1,\n use_bias=True,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5),\n name='conv1')(img)\n return y, c, label\n\n def stage2(x, c, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n return x * 20, c, label\n\n def stage3(x, c, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n return layers.Dense(\n 2,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5))(x), c, label\n\n def stage4(x, c, label):\n with variable_scope.variable_scope(\"stage4\", use_resource=True):\n return math_ops.reduce_sum(\n layers.Dense(2,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5))\n (x)) + c + label\n\n def inputs_fn():\n with ops.device('cpu'):\n return [array_ops.placeholder(np.float32, shape=[])]\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 14770,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare2(self, number_of_io_tiles):\n # Resnet like network.\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(100, shape=[4])\n dataset = dataset.batch(batch_size=32, drop_remainder=True)\n dataset = dataset.batch(batch_size=32, drop_remainder=True)\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n def dataset_parser(value):\n img = value\n label = math_ops.reduce_mean(img, axis=[1, 2, 3])\n return img, math_ops.cast(label, np.int32)\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 18\n repeat_count = 1\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def fixed_padding(inputs, kernel_size):\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n padded_inputs = array_ops.pad(\n inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])\n return padded_inputs\n\n def block(name, first_stride, out_filters, count, x):\n\n for i in range(count):\n shape_in = x.shape\n stride = first_stride if (i == 0) else 1\n if stride > 1:\n x = fixed_padding(x, 3)\n sc = x\n\n with variable_scope.variable_scope(name + \"/\" + str(i) + \"/1\"):\n x = conv(x, 3, stride, out_filters)\n x = nn.relu(x)\n\n with variable_scope.variable_scope(name + \"/\" + str(i) + \"/2\"):\n x = conv(x, 3, 1, out_filters)\n\n # shortcut\n if stride != 1:\n sc = array_ops.strided_slice(sc, [0, 0, 0, 0],\n sc.shape,\n strides=[1, stride, stride, 1])\n pad = int(x.shape[3] - shape_in[3])\n if pad != 0:\n sc = array_ops.pad(sc, paddings=[[0, 0], [0, 0], [0, 0], [0, pad]])\n\n x = nn.relu(x + sc)\n\n return x\n\n def fc(x, num_units_out):\n return layers.Dense(\n num_units_out,\n kernel_initializer=init_ops.constant_initializer(0.1),\n bias_initializer=init_ops.constant_initializer(0.0))(x)\n\n def max_pool(x, ksize=3, stride=2):\n return layers.MaxPooling2D(ksize, stride, padding='SAME')(x)\n\n def conv(x, ksize, stride, filters_out):\n return layers.Conv2D(\n filters_out,\n ksize,\n stride,\n 'SAME',\n kernel_initializer=init_ops.constant_initializer(0.1),\n bias_initializer=init_ops.constant_initializer(0.0))(x)\n\n def stage1(img, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n x = conv(img, 7, 2, 16)\n x = nn.relu(x)\n x = max_pool(x, ksize=3, stride=2)\n return x, label\n\n def stage2(x, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n x = block(\"b\", 2, 64, 1, x)\n return x, label\n\n def stage3(x, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n x = math_ops.reduce_mean(x, axis=[1, 2])\n x = fc(x, 100)\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=x,\n labels=label))\n return loss\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3],\n lambda: [], [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 40549,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare3(self, number_of_io_tiles):\n if utils.running_on_ipu_model():\n self.skipTest(\"Replicated top level graphs are not supported on the \"\n \"IPU_MODEL target\")\n\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(10, shape=[4])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n def dataset_parser(value):\n label = math_ops.reduce_mean(value, axis=[1])\n return math_ops.cast(value,\n np.int32), math_ops.cast(label / 10, np.int32)\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 16\n repeat_count = 1\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def stage1(idx, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n embedding = variable_scope.get_variable(\n \"c\",\n shape=[10, 1216],\n dtype=np.float32,\n initializer=init_ops.constant_initializer(10.01),\n trainable=True)\n x = embedding_ops.embedding_lookup(embedding, idx)\n return x, label\n\n def stage2(x, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n return x, label\n\n def stage3(x, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n return x, label\n\n def stage4(x, label):\n with variable_scope.variable_scope(\"stage4\", use_resource=True):\n logits = math_ops.reduce_sum(x, axis=[-1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n lambda: [], [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 13681,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare4(self, number_of_io_tiles):\n if utils.running_on_ipu_model():\n self.skipTest(\"Replicated top level graphs are not supported on the \"\n \"IPU_MODEL target\")\n # Stage3 has a stateful op there it cannot be recomputed.\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4, 2])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n def dataset_parser(value):\n img = value / 7\n label = value[0][0][0][0]\n return img, label\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 16\n repeat_count = 1\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def stage1(c, img, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n y = layers.Conv2D(\n 2,\n 1,\n use_bias=True,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5),\n name='conv1')(img)\n return y, c, label\n\n def stage2(x, c, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n with ops.control_dependencies([internal_ops.print_tensor(x)]):\n return x * 20, c, label\n\n def stage3(x, c, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n return layers.Dense(\n 2,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5))(x), c, label\n\n def stage4(x, c, label):\n with variable_scope.variable_scope(\"stage4\", use_resource=True):\n return math_ops.reduce_sum(\n layers.Dense(2,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5))\n (x)) + c + label\n\n def inputs_fn():\n with ops.device('cpu'):\n return [array_ops.placeholder(np.float32, shape=[])]\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 20354,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare5(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(128, shape=[1, 1, 1])\n dataset = dataset.batch(batch_size=1, drop_remainder=True)\n\n def dataset_parser(value):\n img = value\n label = value[0][0][0][0]\n return img, label\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 16\n repeat_count = 1\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def stage1(c, img, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n y = layers.Conv2D(\n 2,\n 1,\n use_bias=True,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5),\n name='conv1')(img)\n return y, c, label\n\n def stage2(x, c, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n return x, c, label\n\n def stage3(x, c, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n return x, c, label\n\n def stage4(x, c, label):\n with variable_scope.variable_scope(\"stage4\", use_resource=True):\n return math_ops.reduce_sum(x) + c + label\n\n def inputs_fn():\n with ops.device('cpu'):\n return [array_ops.placeholder(np.float32, shape=[])]\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 9174,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare6(self, number_of_io_tiles):\n # Stage2 has a stateful op whose state will be stored and the rest of the\n # stage should be recomputed.\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[1, 10])\n return dataset.repeat().batch(4, drop_remainder=True)\n\n gradient_accumulation_count = 12\n repeat_count = 2\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n cwd = os.getcwd()\n lib_path = os.path.join(\n cwd, \"tensorflow/python/ipu/libpipelining_stateful_op.so\")\n\n def stage1(x):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n weight = variable_scope.get_variable(\n 'weight',\n shape=(x.shape[-1],),\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n activations = weight * (x + x)\n outputs = {\n \"output_types\": [np.float32],\n \"output_shapes\": [activations.shape],\n }\n activations, = custom_ops.precompiled_user_op([activations],\n lib_path,\n separate_gradients=True,\n outs=outputs)\n return activations * 2\n\n def stage2(activations):\n return activations * 2\n\n def stage3(activations):\n return math_ops.reduce_sum(math_ops.reduce_mean(activations**2, -1))\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_sharding(\n [stage1, stage2, stage3],\n lambda: [], [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 12609,\n True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompare7(self, number_of_io_tiles):\n if utils.running_on_ipu_model():\n self.skipTest(\"Replicated top level graphs are not supported on the \"\n \"IPU_MODEL target\")\n # Stage 1 and 2 don't have a backward stage.\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4, 2])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n def dataset_parser(value):\n img = value / 7\n label = value[0][0][0][0]\n return img, label\n\n return dataset.map(dataset_parser)\n\n gradient_accumulation_count = 16\n repeat_count = 2\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.01)\n\n def stage1(c, img, label):\n with variable_scope.variable_scope(\"stage1\", use_resource=True):\n return img, c, label\n\n def stage2(x, c, label):\n with variable_scope.variable_scope(\"stage2\", use_resource=True):\n with ops.control_dependencies([internal_ops.print_tensor(x)]):\n return x * 20, c, label\n\n def stage3(x, c, label):\n with variable_scope.variable_scope(\"stage3\", use_resource=True):\n return layers.Dense(\n 2,\n kernel_initializer=init_ops.constant_initializer(0.5),\n bias_initializer=init_ops.constant_initializer(0.5))(x), c, label\n\n def stage4(x, c, label):\n with variable_scope.variable_scope(\"stage4\", use_resource=True):\n return math_ops.reduce_sum(x) + c + label\n\n def inputs_fn():\n with ops.device('cpu'):\n return [array_ops.placeholder(np.float32, shape=[])]\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 14502,\n True,\n pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompareSharedWeights(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0] % 4\n return img, math_ops.cast(label, np.int32)\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def stage1(x, label):\n with variable_scope.variable_scope(\"vs\", use_resource=True):\n weight = variable_scope.get_variable(\n \"w0\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n x = array_ops.pad(x, [[0, 0], [0, 0], [1, 1]])\n return x, label\n\n def stage2(x, label):\n with variable_scope.variable_scope(\"vs2\", use_resource=True):\n weight = variable_scope.get_variable(\n \"w1\",\n shape=[6, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n weight = variable_scope.get_variable(\n \"w2\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n return x, label\n\n def stage3(x, label):\n x = x + 1\n return x, label\n\n def stage4(x, label):\n # Ruse the weight here.\n with variable_scope.variable_scope(\"vs\", use_resource=True, reuse=True):\n weight = variable_scope.get_variable(\n \"w0\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n logits = math_ops.reduce_mean(x, axis=[1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 21458,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n recomputation_mode=pipelining_ops.RecomputationMode.\n RecomputeAndBackpropagateInterleaved,\n device_mapping=[0, 1, 2, 0],\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompareSharedWeights2(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0] % 4\n return img, math_ops.cast(label, np.int32)\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def stage1(x, label):\n with variable_scope.variable_scope(\"vs\", use_resource=True):\n weight = variable_scope.get_variable(\n \"w0\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n return x, label\n\n def stage2(x, label):\n internal_ops.print_tensor(x)\n return x, label\n\n def stage3(x, label):\n with variable_scope.variable_scope(\"vs\", use_resource=True, reuse=True):\n weight = variable_scope.get_variable(\n \"w0\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n return x, label\n\n def stage4(x, label):\n logits = math_ops.reduce_sum(x, axis=[1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3, stage4],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 21458,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n device_mapping=[0, 1, 0, 2],\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineCompareRecomputeDropout(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0] % 4\n return img, math_ops.cast(label, np.int32)\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def stage(x, name):\n with variable_scope.variable_scope(name, use_resource=True):\n weight = variable_scope.get_variable(\n \"w\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n x = math_ops.matmul(x, weight)\n x = rand_ops.dropout(x, seed=[10, 10])\n return x\n\n def stage1(x, label):\n return stage(x, \"s1\"), label\n\n def stage2(x, label):\n return stage(x, \"s2\"), label\n\n def stage3(x, label):\n x = stage(x, \"s3\")\n logits = math_ops.reduce_sum(x, axis=[1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_sharding(\n [stage1, stage2, stage3],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 21458,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testUnmodifiedInput(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(8, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0]\n return img, math_ops.cast(label, np.int32)\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return gradient_descent.GradientDescentOptimizer(0.1)\n\n def stage1(x, label):\n with variable_scope.variable_scope(\"s1\", use_resource=True):\n weight = variable_scope.get_variable(\n \"w\",\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n return weight + x, label\n\n def stage2(x, label):\n x = math_ops.reduce_sum(x, axis=[2])\n with variable_scope.variable_scope(\"s2\", use_resource=True):\n weight = variable_scope.get_variable(\n \"w\",\n shape=[4, 8],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n logits = math_ops.matmul(x, weight)\n return logits, label\n\n def stage3(logits, label):\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3],\n inputs_fn, [10.01],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 10153,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineRecomputationCheckpoint(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0] % 4\n return img, math_ops.cast(label, np.int32)\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def get_weight(name):\n return variable_scope.get_variable(\n name,\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n\n def get_stage(x):\n w0 = get_weight(\"w0\")\n w1 = get_weight(\"w1\")\n x = math_ops.matmul(x, w0)\n x = nn.relu(x)\n x = pipelining_ops.recomputation_checkpoint(x)\n x = math_ops.matmul(x, w1)\n x = nn.relu(x)\n return x\n\n def stage1(x, label):\n with variable_scope.variable_scope(\"s1\", use_resource=True):\n return get_stage(x), label\n\n def stage2(x, label):\n with variable_scope.variable_scope(\"s2\", use_resource=True):\n return get_stage(x), label\n\n def stage3(x, label):\n logits = math_ops.reduce_mean(x, axis=[1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3],\n inputs_fn, [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 21458,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n recomputation_mode=pipelining_ops.RecomputationMode.\n RecomputeAndBackpropagateInterleaved,\n number_of_io_tiles=number_of_io_tiles)\n\n @test_util.deprecated_graph_mode_only\n def testPipelineRecomputationCheckpointInFinalStage(self):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n return img, img\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def get_weight(name):\n return variable_scope.get_variable(\n name,\n shape=[2, 4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n\n def stage1(x, label):\n return x, label\n\n def stage2(x, label):\n return x, label\n\n def stage3(x, label):\n # Create a chain of multiplies that we split in half with a checkpoint.\n # We expect only the first half to be recomputed in the bwd stage.\n with variable_scope.variable_scope(\"s3\", use_resource=True):\n w0 = get_weight(\"w0\")\n x = x * w0\n w1 = get_weight(\"w1\")\n x = x * w1\n x = pipelining_ops.recomputation_checkpoint(x)\n w2 = get_weight(\"w2\")\n x = x * w2\n w3 = get_weight(\"w3\")\n x = x * w3\n return x + label\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n _, report_helper = \\\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3],\n inputs_fn, [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 10535,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n recomputation_mode=pipelining_ops.RecomputationMode.\n RecomputeAndBackpropagateInterleaved,\n return_report=True)\n\n # With recomputation, we expect the following final forward stage\n #\n # inp0 inp1 inp2 ckpt inp3 out\n # ---> mul ---> mul1 ---> ckpt ---> mul2 ---> mul3 --->\n # ^ ^ ^ ^\n # | | | |\n # w0 w1 w2 w3\n #\n # to be split at the checkpoint, and only the first half to be recomputed in\n # the backward stage.\n # This is because:\n # 1. There is no point recomputing the second half, since we're about to use\n # the computed activations in the backward pass immediately.\n # 2. Therefore anything past the last checkpoint should not be recomputed.\n # 3. We then don't need to store inp0 and inp1 in live memory while the\n # rest of the forward pass and the second half of backprop is calculated.\n # Under normal recomputation (without the checkpoint), we'd expect to see\n # three extra multiplies in the backward pass to recompute inp3, inp2 and\n # inp1. With the checkpoint, we expect to not do the third multiply, mul2,\n # to recompute inp3, since it's after the last checkpoint.\n # The forward stage multiplies are called:\n # - s3/mul/multiply.*/Op/Multiply\n # - s3/mul_1/multiply.*/Op/Multiply\n # - s3/mul_2/multiply.*/Op/Multiply\n # - s3/mul_3/multiply.*/Op/Multiply\n # When we recompute, the scopes are copied with a different ID, so we can\n # make sure the multiply s3/mul_2/multiply.*/Op/Multiply isn't there twice.\n report = pva.openReport(report_helper.find_report())\n self.assert_compute_sets_matches(report, \"s3/mul_2/multiply.*/Op/Multiply\",\n 1)\n\n @parameterized.parameters([0, 32])\n @test_util.deprecated_graph_mode_only\n def testPipelineRecomputationThreeInput(self, number_of_io_tiles):\n def dataset_fn():\n dataset = tu.create_single_increasing_dataset(7, shape=[4, 4])\n\n def dataset_parser(value):\n img = value\n label = value[0][0] % 4\n return img, math_ops.cast(label, np.int32), value[1][1]\n\n dataset = dataset.map(dataset_parser)\n\n return dataset.batch(batch_size=2, drop_remainder=True)\n\n gradient_accumulation_count = 24\n repeat_count = 2\n\n def optimizer_fn():\n return momentum.MomentumOptimizer(0.01, 0.98)\n\n def get_weight(name):\n return variable_scope.get_variable(\n name,\n shape=[4, 4],\n dtype=np.float32,\n initializer=init_ops.ones_initializer())\n\n def get_stage(x):\n w0 = get_weight(\"w0\")\n w1 = get_weight(\"w1\")\n x = math_ops.matmul(x, w0)\n x = nn.relu(x)\n x = math_ops.matmul(x, w1)\n x = nn.relu(x)\n return x\n\n def stage1(x, label, scale):\n with variable_scope.variable_scope(\"s1\", use_resource=True):\n return get_stage(x) * scale[0], label\n\n def stage2(x, label):\n with variable_scope.variable_scope(\"s2\", use_resource=True):\n return get_stage(x), label\n\n def stage3(x, label):\n logits = math_ops.reduce_mean(x, axis=[1])\n loss = math_ops.reduce_mean(\n nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label))\n return loss\n\n def inputs_fn():\n with ops.device('cpu'):\n return []\n\n pipelining_test_util.PipelineTester.compare_pipeline_to_cpu(\n [stage1, stage2, stage3],\n inputs_fn, [],\n repeat_count,\n gradient_accumulation_count,\n dataset_fn,\n optimizer_fn,\n self,\n 21458,\n recomp=True,\n schedule=pipelining_ops.PipelineSchedule.Grouped,\n number_of_io_tiles=number_of_io_tiles)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nUtilities for IPU ops\n~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\nimport six\n\nfrom tensorflow.compiler.plugin.poplar.driver import backend_config_pb2\nfrom tensorflow.compiler.plugin.poplar.driver import threestate_pb2\nfrom tensorflow.compiler.plugin.poplar.ops import gen_functional_ops\nfrom tensorflow.compiler.plugin.poplar.ops import gen_poputil_ops\nfrom tensorflow.compiler.xla import xla_data_pb2\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ipu import functional_ops\nfrom tensorflow.python.ipu import scopes\nfrom tensorflow.python.ops import control_flow_util_v2 as util\nfrom tensorflow.python.ops import math_grad\nfrom tensorflow.python.ops import nn_grad\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.util import tf_contextlib\n\n\ndef SetMlType(op, ml_type):\n if context.executing_eagerly():\n return op\n if ml_type:\n operation = op if isinstance(op, ops.Operation) else op.op\n attrs = xla_data_pb2.FrontendAttributes()\n attr_name = backend_config_pb2.FrontendAttributeId.Name(\n backend_config_pb2.FrontendAttributeId.ML_TYPE)\n attrs.map[attr_name] = backend_config_pb2.MLType.Name(ml_type)\n serial_attrs = attrs.SerializeToString()\n operation._set_attr( # pylint: disable=protected-access\n scopes.FRONTEND_ATTRIBUTES_NAME,\n attr_value_pb2.AttrValue(s=serial_attrs))\n return op\n\n\ndef SetOpAsFwd(op):\n return SetMlType(op, backend_config_pb2.TRAINING_FWD)\n\n\ndef SetOpAsBwd(op):\n return SetMlType(op, backend_config_pb2.TRAINING_BWD)\n\n\ndef SetOpAsWU(op):\n return SetMlType(op, backend_config_pb2.TRAINING_WU)\n\n\n# Override all the convolution operation gradients so that they can be annotated\n# with the \"ML type\".\[email protected](\"CustomConv2D\")\ndef _CustomConv2DGrad(op, grad):\n grads = nn_grad._Conv2DGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 2\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[1])\n return grads\n\n\[email protected](\"CustomConv2DBackpropInput\")\ndef _CustomConv2DBackpropInputGrad(op, grad):\n grads = nn_grad._Conv2DBackpropInputGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[1])\n SetOpAsWU(grads[2])\n return grads\n\n\[email protected](\"CustomConv2DBackpropFilter\")\ndef _CustomConv2DBackpropFilterGrad(op, grad):\n grads = nn_grad._Conv2DBackpropFilterGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[2])\n return grads\n\n\[email protected](\"CustomDepthwiseConv2dNative\")\ndef _CustomDepthwiseConv2dNativeGrad(op, grad):\n grads = nn_grad._DepthwiseConv2dNativeGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 2\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[1])\n return grads\n\n\[email protected](\"CustomDepthwiseConv2dNativeBackpropInput\")\ndef _CustomDepthwiseConv2dNativeBackpropInputGrad(op, grad):\n grads = nn_grad._DepthwiseConv2dNativeBackpropInputGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[1])\n SetOpAsWU(grads[2])\n return grads\n\n\[email protected](\"CustomDepthwiseConv2dNativeBackpropFilter\")\ndef _CustomDepthwiseConv2dNativeBackpropFilterGrad(op, grad):\n grads = nn_grad._DepthwiseConv2dNativeBackpropFilterGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[2])\n return grads\n\n\[email protected](\"CustomConv3D\")\ndef _CustomConv3DGrad(op, grad):\n grads = nn_grad._Conv3DGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 2\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[1])\n return grads\n\n\[email protected](\"CustomConv3DBackpropInputV2\")\ndef _CustomConv3DBackpropInputGrad(op, grad):\n grads = nn_grad._Conv3DBackpropInputGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[1])\n SetOpAsWU(grads[2])\n return grads\n\n\[email protected](\"CustomConv3DBackpropFilterV2\")\ndef _CustomConv3DBackpropFilterGrad(op, grad):\n grads = nn_grad._Conv3DBackpropFilterGrad(op, grad) # pylint: disable=protected-access\n assert len(grads) == 3\n SetOpAsFwd(op)\n SetOpAsBwd(grads[0])\n SetOpAsWU(grads[2])\n return grads\n\n\ndef conv_gradients_override_map():\n return {\n \"Conv2D\":\n \"CustomConv2D\",\n \"Conv2DBackpropInput\":\n \"CustomConv2DBackpropInput\",\n \"Conv2DBackpropFilter\":\n \"CustomConv2DBackpropFilter\",\n \"Conv3D\":\n \"CustomConv3D\",\n \"Conv3DBackpropInputV2\":\n \"CustomConv3DBackpropInputV2\",\n \"Conv3DBackpropFilterV2\":\n \"CustomConv3DBackpropFilterV2\",\n \"DepthwiseConv2dNative\":\n \"CustomDepthwiseConv2dNative\",\n \"DepthwiseConv2dNativeBackpropInput\":\n \"CustomDepthwiseConv2dNativeBackpropInput\",\n \"DepthwiseConv2dNativeBackpropFilter\":\n \"CustomDepthwiseConv2dNativeBackpropFilter\"\n }\n\n\ndef HandleMatMulGrads(grads):\n assert len(grads) == 2\n\n # Batched matmul might have batch dimension reductions.\n def look_through_reshape_reduce(output):\n if output.op.type == \"Reshape\":\n output = output.op.inputs[0]\n if output.op.type == \"Sum\":\n output = output.op.inputs[0]\n return output\n\n SetOpAsBwd(look_through_reshape_reduce(grads[0]))\n SetOpAsWU(look_through_reshape_reduce(grads[1]))\n return grads\n\n\[email protected](\"CustomMatMul\")\ndef _CustomMatMulGrad(op, grad):\n grads = math_grad._MatMulGrad(op, grad) # pylint: disable=protected-access\n SetOpAsFwd(op)\n return HandleMatMulGrads(grads)\n\n\[email protected](\"CustomBatchMatMul\")\ndef _CustomBatchMatMulGrad(op, grad):\n grads = math_grad._BatchMatMul(op, grad) # pylint: disable=protected-access\n SetOpAsFwd(op)\n return HandleMatMulGrads(grads)\n\n\[email protected](\"CustomBatchMatMulV2\")\ndef _CustomBatchMatMulV2Grad(op, grad):\n grads = math_grad._BatchMatMulV2(op, grad) # pylint: disable=protected-access\n SetOpAsFwd(op)\n return HandleMatMulGrads(grads)\n\n\ndef matmul_gradients_override_map():\n return {\n \"MatMul\": \"CustomMatMul\",\n \"BatchMatMul\": \"CustomBatchMatMul\",\n \"BatchMatMulV2\": \"CustomBatchMatMulV2\",\n }\n\n\ndef gradients_override_map():\n return {**conv_gradients_override_map(), **matmul_gradients_override_map()}\n\n\n@tf_contextlib.contextmanager\ndef gradient_override_scope(training):\n \"\"\"Scope which configures any operations which need to be aware of whether\n they are an operation in forward or backward propagation, and if the latter,\n make sure that the gradient operations are annotated as a gradient with\n respect to activations or as a gradient with respect to the weights.\n\n Args:\n training: whether this is a training graph.\n\n Returns:\n A context\n \"\"\"\n with scopes.frontend_attribute(\n backend_config_pb2.FrontendAttributeId.Name(backend_config_pb2.ML_TYPE),\n backend_config_pb2.MLType.Name(\n backend_config_pb2.TRAINING_FWD if training else backend_config_pb2.\n INFERENCE_FWD)):\n with ops.get_default_graph().as_default() as g:\n with g.gradient_override_map(gradients_override_map()):\n yield\n\n\ndef get_accumulator_dtype(variable, dtype_override):\n \"\"\"Get the accumulator dtype for the given variable.\"\"\"\n if dtype_override is None:\n return variable.dtype\n\n # Note that a `DType` is callable, so only try to call it if validation fails.\n try:\n return dtypes.as_dtype(dtype_override)\n except TypeError:\n if callable(dtype_override):\n return dtypes.as_dtype(dtype_override(variable))\n else:\n raise\n\n\n_activation_modules = set(\n ['tensorflow.python.keras.activations', 'tensorflow.python.ops.math_ops'])\n\n\ndef get_activation_name(identifier):\n \"Get activation name from string or activation function object\"\n if isinstance(identifier, six.string_types):\n return identifier\n elif callable(identifier):\n if identifier.__module__ not in _activation_modules:\n raise TypeError('Unrecognized function : '\n f'{identifier.__module__}.{identifier.__name__}')\n return identifier.__name__\n\n raise TypeError(\n f'Could not interpret activation function identifier: {repr(identifier)}'\n )\n\n\ndef bool_to_three_state(value, default=None):\n if value is None:\n return default if default else threestate_pb2.ThreeState.Name(\n threestate_pb2.THREESTATE_UNDEFINED)\n elif value:\n return threestate_pb2.ThreeState.Name(threestate_pb2.THREESTATE_ON)\n return threestate_pb2.ThreeState.Name(threestate_pb2.THREESTATE_OFF)\n\n\ndef accumulate_gradients(grads_and_vars, gradient_accumulation_dtype):\n \"\"\"\n Create ops that accumulate the gradients in `grads_and_vars`.\n Returns gradient accumulation ops which, when executed, accumulate gradients\n onto their gradient accumulation buffers.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs as returned by\n an optimizer's compute_gradients() function.\n gradient_accumulation_dtype: The data type used for the gradient\n accumulation buffer. One of:\n\n - `None`: Use an accumulator of the same type as the variable type.\n - A `DType`: Use this type for all the accumulators.\n - A callable that takes the variable and returns a `DType`: Allows\n specifying the accumulator type on a per-variable basis.\n \"\"\"\n accumulated_grads_and_vars = []\n for grad, var in grads_and_vars:\n if grad is not None:\n with ops.colocate_with(grad):\n # Find the data type for the accumulator.\n dtype = get_accumulator_dtype(var, gradient_accumulation_dtype)\n # Create an accumulator - variable is used as reference for shape/layout.\n accumulator = gen_poputil_ops.gradient_accumulator_create(\n var, output_type=dtype)\n # Add the gradients to the accumulator.\n accumulator = gen_poputil_ops.gradient_accumulator_add_with_scale(\n accumulator, grad, math_ops.cast(1.0, dtype))\n # Sink the accumulators.\n grad = gen_poputil_ops.gradient_accumulator_sink(accumulator)\n # Use the accumulated gradients.\n accumulated_grads_and_vars.append((grad, var))\n return accumulated_grads_and_vars\n\n\ndef create_resource_update(fn, name, control_outputs,\n offload_weight_update_variables,\n replicated_optimizer_state_sharding,\n gradient_accumulation_count):\n \"\"\"\n Creates a resource update computation in the XLA graph from the Python\n function `fn`.\n Returns the computation outputs.\n\n Args:\n - fn: A Python callable which will be converted into the XLA resource\n update.\n - name: Base name of the XLA resource update.\n - control_outputs: Operations which must have been executed before the XLA\n resource update can be said to have been executed.\n - offload_weight_update_variables: When enabled, the `tf.Variable`s that\n are only used by the XLA resource update generated by this function will\n be stored in remote memory. During the weight update, these variables will\n be streamed onto the device and then streamed back to remote memory after\n they have been updated. Requires the machine to be configured with support\n for `Poplar remote buffers`. Offloading variables into remote memory can\n reduce maximum memory liveness, but can also increase the computation time\n of the weight update. When set to `None` the variables will be placed in\n either in-processor or remote memory automatically based on the current\n best placement.\n - replicated_optimizer_state_sharding: If True, any `tf.Variable` which is\n offloaded via `offload_weight_update_variables` will be partitioned across\n the replicas. This can exploit the additional bandwidth of the IPU-Links\n and the parallelism of the replicas to improve overall throughput.\n\n \"\"\"\n offload_weight_update_variables = bool_to_three_state(\n offload_weight_update_variables,\n threestate_pb2.ThreeState.Name(threestate_pb2.THREESTATE_UNDEFINED))\n replicated_optimizer_state_sharding = bool_to_three_state(\n replicated_optimizer_state_sharding,\n default=offload_weight_update_variables)\n\n rts_on = replicated_optimizer_state_sharding != 'THREESTATE_OFF'\n offload_on = offload_weight_update_variables != 'THREESTATE_OFF'\n if rts_on and not offload_on:\n raise ValueError(\n \"To use replicated_optimizer_state_sharding, optimizer state must be\"\n \" offloaded by using offload_weight_update_variables.\")\n\n # Create the resource update and lower the function into XLA.\n with ops.name_scope(name + \"/WU\") as scope:\n func_graph, captured_args, constant_outputs = \\\n functional_ops._compile_function( # pylint: disable=protected-access\n fn, [gradient_accumulation_count], scope, control_outputs, True)\n\n # Add a call op to the graph that calls the resource update.\n with ops.control_dependencies(list(func_graph.control_captures)):\n outputs = gen_functional_ops.resource_update(\n captured_args,\n to_apply=util.create_new_tf_function(func_graph),\n Tout=func_graph.output_types,\n output_shapes=func_graph.output_shapes,\n offload_weight_update_variables=offload_weight_update_variables,\n replicated_optimizer_state_sharding=replicated_optimizer_state_sharding\n )\n outputs = functional_ops._replace_outputs(outputs, constant_outputs) # pylint: disable=protected-access\n\n return outputs\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for IPU Embedding layer.\"\"\"\n\nimport numpy as np\n\nfrom tensorflow.python import ipu\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.platform import test\n\ndataType = np.float32\n\n\ndef kerasIPUEmbeddingLookup(params, ids, name=None, serialization_factor=1):\n input_dim = params.shape[0]\n output_dim = params.shape[1]\n layer = ipu.layers.Embedding(\n input_dim=input_dim,\n output_dim=output_dim,\n embeddings_initializer=keras.initializers.constant(params),\n name=name,\n serialization_factor=serialization_factor)\n layer.build(input_shape=ids.shape)\n\n @def_function.function\n def impl(ids):\n return layer(inputs=ids)\n\n return impl(ids)\n\n\nclass IPUEmbeddingLookupTest(test.TestCase):\n def testEmbeddingLookup(self):\n ids = constant_op.constant([[1, 2, 3]])\n paras = np.array([[10], [20], [80], [40]])\n emb_lookup_tf = nn.embedding_lookup(paras, ids)\n emb_lookup_ipu = kerasIPUEmbeddingLookup(paras, ids, name=\"emb_test_0\")\n self.assertAllClose(emb_lookup_tf, emb_lookup_ipu)\n\n def testEmbeddingLookupBatchSize2(self):\n ids = constant_op.constant([[1, 2, 3], [3, 4, 5]])\n paras = np.array([[10], [20], [80], [40], [50], [60]])\n emb_lookup_tf = nn.embedding_lookup(paras, ids)\n emb_lookup_ipu = kerasIPUEmbeddingLookup(paras, ids, name=\"emb_test_1\")\n self.assertAllClose(emb_lookup_tf, emb_lookup_ipu)\n\n # Based on ipu/tests/embedding_lookup_test.py\n def testEmbeddingLookupBigGather(self):\n ids = np.arange(0, 8, dtype=np.int32).reshape([1, 8])\n paras = np.arange(2400000, dtype=dataType).reshape([12000, 200])\n result_ipu = kerasIPUEmbeddingLookup(paras, ids, name=\"emb_test_2\")\n result_np = np.take(paras, ids, axis=0)\n self.assertAllClose(result_ipu, result_np)\n self.assertEqual(result_ipu.shape, (1, 8, 200))\n\n def testEmbeddingBadInputShape(self):\n ids = np.arange(0, 16, dtype=np.int32)\n paras = np.arange(25600, dtype=dataType).reshape([32, 200, 4])\n with self.assertRaisesRegexp(ValueError, r'The input shape should be a'):\n kerasIPUEmbeddingLookup(paras, ids, name=\"emb_test_4\")\n\n def testEmbeddingLookupSerialization(self):\n ids = constant_op.constant([[1, 2, 3]])\n paras = np.array([[10], [20], [80], [40]])\n emb_lookup_tf = nn.embedding_lookup(paras, ids)\n emb_lookup_ipu = kerasIPUEmbeddingLookup(paras,\n ids,\n name=\"emb_test_5\",\n serialization_factor=4)\n self.assertAllClose(emb_lookup_tf, emb_lookup_ipu)\n\n @test_util.run_v2_only\n def testGetConfig(self):\n layer = ipu.layers.Embedding(input_dim=32, output_dim=200)\n config = layer.get_config()\n layer2 = ipu.layers.Embedding.from_config(config)\n self.assertEqual(config, layer2.get_config())\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test for IPU Keras single IPU model.\"\"\"\n\nimport os\nfrom tensorflow.python.ipu.config import IPUConfig\nimport numpy as np\n\nfrom tensorflow.compiler.plugin.poplar.tests import test_utils as tu\nfrom tensorflow.python import ipu\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\n\n\ndef dataset_with_labels():\n x1 = np.ones((8), dtype=np.float64)\n x2 = np.ones((8), dtype=np.float64)\n x3 = np.ones((8), dtype=np.float64)\n y1 = np.ones((1), dtype=np.float64)\n y2 = np.ones((1), dtype=np.float64)\n ds_x = dataset_ops.Dataset.from_tensors((x1, x2, x3))\n ds_y = dataset_ops.Dataset.from_tensors((y1, y2))\n ds_xy = dataset_ops.Dataset.zip(\n (ds_x, ds_y)).repeat(16).batch(2, drop_remainder=True)\n return ds_xy\n\n\ndef numpy_data():\n x1 = np.ones((2, 8), dtype=np.float64)\n x2 = np.ones((2, 8), dtype=np.float64)\n x3 = np.ones((2, 8), dtype=np.float64)\n return (x1, x2, x3)\n\n\ndef model_fn(nested_outputs=False):\n input_1 = keras.Input(8)\n input_2 = keras.Input(8)\n input_3 = keras.Input(8)\n\n init = keras.initializers.Constant(1)\n\n cat = keras.layers.Concatenate()([input_1, input_2, input_3])\n\n dense_3 = keras.layers.Dense(1,\n kernel_initializer=init,\n activation=keras.activations.relu,\n name=\"output1\")(cat)\n dense_4 = keras.layers.Dense(2,\n kernel_initializer=init,\n activation=keras.activations.relu,\n name=\"output2\")(cat)\n\n if nested_outputs:\n return ((input_1, input_2, input_3), ((dense_3,), (dense_4,)))\n\n return ((input_1, input_2, input_3), (dense_3, dense_4))\n\n\nclass KerasSyntheticDataTest(test.TestCase):\n @tu.skip_on_hw\n @test_util.run_v2_only\n def testSyntheticDataFit(self):\n poplar_flags = os.environ.get(\"TF_POPLAR_FLAGS\", \"\")\n poplar_flags += \" --use_synthetic_data\"\n\n with test.mock.patch.dict(\"os.environ\", {\"TF_POPLAR_FLAGS\": poplar_flags}):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n model.fit(dataset_with_labels(), epochs=4)\n\n @tu.skip_on_hw\n @test_util.run_v2_only\n def testSyntheticDataEvaluate(self):\n poplar_flags = os.environ.get(\"TF_POPLAR_FLAGS\", \"\")\n poplar_flags += \" --use_synthetic_data\"\n\n with test.mock.patch.dict(\"os.environ\", {\"TF_POPLAR_FLAGS\": poplar_flags}):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n model.evaluate(dataset_with_labels())\n\n @tu.skip_on_hw\n @test_util.run_v2_only\n def testSyntheticDataPredict(self):\n poplar_flags = os.environ.get(\"TF_POPLAR_FLAGS\", \"\")\n poplar_flags += \" --use_synthetic_data\"\n\n with test.mock.patch.dict(\"os.environ\", {\"TF_POPLAR_FLAGS\": poplar_flags}):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n model.predict(numpy_data(), batch_size=2)\n\n @tu.skip_on_hw\n @test_util.run_v2_only\n def testSyntheticDataPredictNestedOutput(self):\n poplar_flags = os.environ.get(\"TF_POPLAR_FLAGS\", \"\")\n poplar_flags += \" --use_synthetic_data\"\n\n with test.mock.patch.dict(\"os.environ\", {\"TF_POPLAR_FLAGS\": poplar_flags}):\n strategy = ipu.ipu_strategy.IPUStrategy()\n with strategy.scope():\n cfg = IPUConfig()\n tu.enable_ipu_events(cfg)\n cfg.auto_select_ipus = 1\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn(nested_outputs=True))\n model.compile('sgd', ['mse', 'mse'], metrics=['accuracy'])\n\n model.predict(numpy_data(), batch_size=2)\n\n @tu.test_uses_ipus(num_ipus=2)\n @test_util.run_v2_only\n def testSyntheticDataWithReplication(self):\n poplar_flags = os.environ.get(\"TF_POPLAR_FLAGS\", \"\")\n poplar_flags += \" --use_synthetic_data\"\n\n with test.mock.patch.dict(\"os.environ\", {\"TF_POPLAR_FLAGS\": poplar_flags}):\n strategy = ipu.ipu_strategy.IPUStrategyV1()\n with strategy.scope():\n cfg = IPUConfig()\n cfg.auto_select_ipus = 2\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n model = keras.Model(*model_fn())\n model.compile('sgd', ['mse', 'mse'],\n metrics=['accuracy'],\n steps_per_execution=8)\n\n model.fit(dataset_with_labels(), epochs=4)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.ipu.ops.pipelining_ops.recomputation_checkpoint" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.keras.layers.Dense", "tensorflow.python.keras.engine.base_layer_utils.enable_v2_dtype_behavior", "numpy.all", "tensorflow.python.keras.layers.Reshape", "tensorflow.python.keras.layers.Activation", "tensorflow.python.keras.layers.concatenate", "tensorflow.python.ipu.ipu_strategy.IPUStrategyV1", "numpy.full", "tensorflow.python.platform.test.main", "tensorflow.compiler.plugin.poplar.tests.test_utils.ReportJSON", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.keras.optimizer_v2.gradient_descent.SGD", "tensorflow.python.keras.Model", "tensorflow.python.keras.layers.Input", "tensorflow.compiler.plugin.poplar.tests.test_utils.enable_ipu_events", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "tensorflow.python.keras.optimizer_v2.learning_rate_schedule.PiecewiseConstantDecay", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.keras.Input", "tensorflow.compiler.plugin.poplar.tests.test_utils.ReportHelper", "numpy.ones", "tensorflow.python.keras.optimizer_v2.learning_rate_schedule.ExponentialDecay", "tensorflow.python.keras.initializers.Constant", "tensorflow.python.keras.layers.Concatenate", "tensorflow.python.data.ops.dataset_ops.Dataset.zip", "numpy.shape", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.layers.Dense", "tensorflow.python.ops.math_ops.greater", "tensorflow.python.ipu.ops.cross_replica_ops.assume_equal_across_replicas", "tensorflow.python.ipu.ipu_strategy.IPUStrategy", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ipu.scopes.ipu_scope", "tensorflow.python.ops.math_ops.not_equal", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.math_ops.logical_and", "tensorflow.python.ipu.ipu_compiler.compile", "tensorflow.python.ipu.cross_replica_ops.cross_replica_sum", "tensorflow.python.ops.math_ops.less", "tensorflow.compiler.plugin.poplar.tests.test_utils.test_uses_ipus", "numpy.full", "tensorflow.python.platform.googletest.main", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ipu.keras.layers.AssumeEqualAcrossReplicas", "tensorflow.python.ipu.ops.cross_replica_ops.cross_replica_sum", "tensorflow.python.ipu.ipu_outfeed_queue.IPUOutfeedQueue", "tensorflow.python.keras.Model", "tensorflow.python.ipu.ipu_infeed_queue.IPUInfeedQueue", "tensorflow.python.client.session.Session", "tensorflow.python.keras.layers.Input", "tensorflow.python.ipu.loops.repeat", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.keras.initializers.Constant", "tensorflow.python.ipu.cross_replica_ops.assume_equal_across_replicas", "numpy.broadcast_to", "tensorflow.compiler.plugin.poplar.tests.test_utils.add_hw_ci_connection_options", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ipu.ipu_compiler.compile", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.ops.math_ops.less", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ipu.scopes.ipu_scope", "numpy.broadcast_to", "tensorflow.python.platform.googletest.main", "tensorflow.python.framework.ops.device", "numpy.zeros", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ipu.ipu_compiler.compile", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.ipu.ops.reduce_scatter_op.reduce_scatter", "tensorflow.python.ipu.ipu_outfeed_queue.IPUOutfeedQueue", "numpy.arange", "tensorflow.compiler.plugin.poplar.tests.test_utils.test_uses_ipus", "numpy.ceil", "tensorflow.python.ipu.scopes.ipu_scope", "tensorflow.python.client.session.Session", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.platform.googletest.main", "tensorflow.python.framework.ops.device", "tensorflow.compiler.plugin.poplar.tests.test_utils.add_hw_ci_connection_options" ], [ "tensorflow.debugging.assert_equal", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.ipu.horovod.init", "tensorflow.python.ipu.horovod.shutdown", "tensorflow.python.ipu.horovod.rank", "tensorflow.python.ipu.horovod.popdist_strategy.PopDistStrategy", "tensorflow.python.ops.variables.Variable", "tensorflow.python.platform.test.main", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.ipu.horovod.size", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.tpu.ops.tpu_ops.all_to_all", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.tpu.training_loop.repeat", "tensorflow.python.ops.math_ops.add", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.tpu.tpu_feed.InfeedQueue", "tensorflow.python.ops.control_flow_util.IsInXLAContext", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.special_math_ops.einsum", "tensorflow.python.framework.ops.Graph", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.tpu.tpu.TPUReplicateContext", "tensorflow.python.tpu.tpu.rewrite", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.compiler.plugin.poplar.ops.gen_popops_ops.ipu_histogram_update", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.math_ops.linspace", "tensorflow.compiler.plugin.poplar.ops.gen_popops_ops.ipu_histogram", "tensorflow.python.ops.math_ops.reduce_min", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.math_ops.reduce_sum" ], [ "tensorflow.python.ops.array_ops.strided_slice", "tensorflow.python.training.momentum.MomentumOptimizer", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.ipu.rand_ops.dropout", "tensorflow.python.ipu.tests.pipelining_test_util.PipelineTester.compare_pipeline_to_sharding", "tensorflow.python.ops.init_ops.ones_initializer", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.ipu.tests.pipelining_test_util.PipelineTester.compare_pipeline_to_cpu", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.python.ipu.utils.running_on_ipu_model", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.nn.relu", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.compiler.plugin.poplar.tests.test_utils.create_single_increasing_dataset", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "tensorflow.compat.v1.disable_v2_behavior", "tensorflow.python.ipu.embedding_ops.embedding_lookup", "tensorflow.python.ipu.internal_ops.print_tensor", "tensorflow.python.ipu.custom_ops.precompiled_user_op", "tensorflow.python.ops.array_ops.pad", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ipu.pipelining_ops.recomputation_checkpoint" ], [ "tensorflow.python.ops.nn_grad._Conv3DBackpropFilterGrad", "tensorflow.python.ipu.functional_ops._compile_function", "tensorflow.compiler.plugin.poplar.driver.backend_config_pb2.FrontendAttributeId.Name", "tensorflow.compiler.plugin.poplar.driver.threestate_pb2.ThreeState.Name", "tensorflow.compiler.plugin.poplar.ops.gen_poputil_ops.gradient_accumulator_sink", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.control_flow_util_v2.create_new_tf_function", "tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes", "tensorflow.python.framework.ops.RegisterGradient", "tensorflow.python.ops.nn_grad._DepthwiseConv2dNativeGrad", "tensorflow.python.ops.nn_grad._DepthwiseConv2dNativeBackpropInputGrad", "tensorflow.python.ops.math_grad._MatMulGrad", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.nn_grad._Conv2DBackpropInputGrad", "tensorflow.python.ops.nn_grad._Conv2DBackpropFilterGrad", "tensorflow.compiler.plugin.poplar.ops.gen_poputil_ops.gradient_accumulator_create", "tensorflow.python.ipu.functional_ops._replace_outputs", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.core.framework.attr_value_pb2.AttrValue", "tensorflow.compiler.plugin.poplar.driver.backend_config_pb2.MLType.Name", "tensorflow.python.ops.math_grad._BatchMatMulV2", "tensorflow.python.ops.nn_grad._Conv3DGrad", "tensorflow.python.ops.nn_grad._Conv3DBackpropInputGrad", "tensorflow.python.ops.nn_grad._DepthwiseConv2dNativeBackpropFilterGrad", "tensorflow.python.ops.math_grad._BatchMatMul", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.nn_grad._Conv2DGrad" ], [ "tensorflow.python.ops.nn.embedding_lookup", "numpy.take", "numpy.arange", "tensorflow.python.ipu.layers.Embedding.from_config", "tensorflow.python.keras.initializers.constant", "tensorflow.python.ipu.layers.Embedding", "tensorflow.python.platform.test.main", "numpy.array", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.ipu.config.IPUConfig", "tensorflow.python.keras.Input", "tensorflow.python.keras.layers.Dense", "tensorflow.compiler.plugin.poplar.tests.test_utils.add_hw_ci_connection_options", "tensorflow.compiler.plugin.poplar.tests.test_utils.test_uses_ipus", "tensorflow.python.ipu.ipu_strategy.IPUStrategyV1", "numpy.ones", "tensorflow.python.ipu.ipu_strategy.IPUStrategy", "tensorflow.python.keras.initializers.Constant", "tensorflow.python.keras.layers.Concatenate", "tensorflow.python.data.ops.dataset_ops.Dataset.zip", "tensorflow.python.platform.test.main", "tensorflow.python.platform.test.mock.patch.dict", "tensorflow.compiler.plugin.poplar.tests.test_utils.enable_ipu_events" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] }, { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
leander-dsouza/Gazebo
[ "4e4c92115c9132b096f9b5a7fc9a9c0f5ed9e598" ]
[ "scripts/Tennis Ball Detection/ball_detection_taskphase.py" ]
[ "#!/usr/bin/env python3\nimport rospy\nimport cv2\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nimport numpy as np\n\n\n\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5, 5))\nkernel1= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3, 3))\n\naratio = 1.0\n\ndef nothing(x):\n pass\n\n\n# *********************************************************************************************************************\ndef adjust_gamma(image, gamma=1.0):\n if gamma == 0:\n gamma = 0.01\n\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255\n for i in np.arange(0, 256)]).astype(\"uint8\")\n\n return cv2.LUT(image, table)\n\n\n# *********************************************************************************************************************\n\nimg1= np.zeros((300, 512, 3), np.uint8)\ncv2.namedWindow('GAMMA')\n\ncv2.createTrackbar('g', 'GAMMA', 1, 10, nothing)\n\ndef callback(data):\n global aratio\n br = CvBridge()\n frame1 = br.imgmsg_to_cv2(data)\n frame1 = cv2.cvtColor(frame1, cv2.COLOR_RGB2BGR)\n frame = frame1\n gamma = (cv2.getTrackbarPos('g', 'GAMMA')) * 0.1\n cv2.imshow('GAMMA', img1)\n frame = adjust_gamma(frame, gamma=gamma)\n\n cv2.putText(frame, \"g={}\".format(gamma), (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)\n\n #cv2.imshow(\"camera\", frame)\n hsv = frame\n hsv = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV) #RGB reading\n hsv = cv2.GaussianBlur(hsv, (5, 5), 0)\n\n # define range of yellow color in HSV\n lower_yellow = np.array([29, 86, 6])\n upper_yellow = np.array([64, 255, 255])\n\n # Threshold the HSV image to get only blue colors\n mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel1)\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel1)\n\n mask = cv2.erode(mask, kernel, iterations=2)\n mask = cv2.dilate(mask, kernel1, iterations=13)\n\n # Bitwise-AND mask and original image\n res = cv2.bitwise_and(frame, frame, mask=mask)\n\n # BOUNDING RECTANGLE .............................................................................................\n\n conts, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n conts = np.array(conts)\n\n if len(conts) > 0:\n\n for i, contour in enumerate(conts):\n rect = cv2.minAreaRect(contour)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n aratio = (rect[1][0] / rect[1][1])\n if (aratio > 0.9) and (aratio < 1.1):\n cv2.drawContours(frame, [box], 0, (0, 0, 255), 2)\n\n #print(\"Aspect Ratio\", aratio)\n\n # HOUGH CIRCLES........................................................................................................\n\n gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)\n\n circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 200, param1=255, param2=20, minRadius=0, maxRadius=0)\n # # print circles\n\n # ensure at least some circles were found\n if circles is not None:\n # convert the (x, y) coordinates and radius of the circles to integers\n circles = np.round(circles[0, :]).astype(\"int\")\n # loop over the (x, y) coordinates and radius of the circles\n for (x, y, r) in circles:\n # draw the circle in the output image, then draw a rectangle in the image\n # corresponding to the center of the circle\n\n if (aratio > 0.9) and (aratio < 1.1):\n cv2.circle(res, (x, y), r, (0, 255, 0), 4)\n cv2.rectangle(res, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)\n cv2.putText(frame, \"BALL DETECTED\", (430, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8,\n (255, 0, 0),\n 3)\n\n # DISPLAY................................................................................................................\n\n cv2.putText(frame1, \"ORIGINAL FRAME\", (10, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 3)\n cv2.putText(frame, \"OUTPUT FRAME\", (10, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 3)\n\n cv2.putText(res, \"RESULTANT\", (10, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 3)\n\n mask = cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)\n horizontal1 = np.hstack([frame1,frame])\n horizontal2 = np.hstack((mask,res))\n vertical = np.vstack((horizontal1,horizontal2))\n\n '''cv2.imshow('GAMMA CORRECTED', frame)\n cv2.imshow('MASK', mask)\n cv2.imshow('RESULT', res)\n cv2.imshow('ORIGINAL FRAME', frame1)'''\n\n cv2.putText(vertical, \"MASK\", (10, 940), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 3)\n cv2.imshow('RESULT', vertical)\n\n # .....................................................................................................................\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n quit()\n\n\n\ndef listener():\n rospy.init_node('listener', anonymous=True,disable_signals=True)\n\n rospy.Subscriber('/d435/camera/color/image_raw', Image, callback)\n\n rospy.spin()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n listener()\n\n" ]
[ [ "numpy.int0", "numpy.hstack", "numpy.arange", "numpy.round", "numpy.array", "numpy.zeros", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rcourivaud/video-to-pose3D
[ "b908014fe2c531c075c11cee72bb798120f970c2", "b908014fe2c531c075c11cee72bb798120f970c2", "b908014fe2c531c075c11cee72bb798120f970c2", "b908014fe2c531c075c11cee72bb798120f970c2", "b908014fe2c531c075c11cee72bb798120f970c2" ]
[ "joints_detectors/Alphapose/yolo/video_demo_half.py", "joints_detectors/Alphapose/SPPE/src/main_fast_inference.py", "pose_trackers/lighttrack/unit_test/test_utils_convert_heatmap.py", "joints_detectors/hrnet/lib/detector/yolo/soft_NMS.py", "pose_trackers/lighttrack/HPE/train_PoseTrack_COCO_17_MSRA152.py" ]
[ "from __future__ import division\nimport time\nimport torch \nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nimport cv2 \nfrom .util import *\nfrom .darknet import Darknet\nfrom .preprocess import prep_image, inp_to_image, letterbox_image\nimport pandas as pd\nimport random \nimport pickle as pkl\nimport argparse\n\n\ndef get_test_input(input_dim, CUDA):\n img = cv2.imread(\"dog-cycle-car.png\")\n img = cv2.resize(img, (input_dim, input_dim)) \n img_ = img[:,:,::-1].transpose((2,0,1))\n img_ = img_[np.newaxis,:,:,:]/255.0\n img_ = torch.from_numpy(img_).float()\n img_ = Variable(img_)\n \n if CUDA:\n img_ = img_.cuda()\n \n return img_\n\ndef prep_image(img, inp_dim):\n \"\"\"\n Prepare image for inputting to the neural network. \n \n Returns a Variable \n \"\"\"\n\n orig_im = img\n dim = orig_im.shape[1], orig_im.shape[0]\n img = (letterbox_image(orig_im, (inp_dim, inp_dim)))\n img_ = img[:,:,::-1].transpose((2,0,1)).copy()\n img_ = torch.from_numpy(img_).float().div(255.0).unsqueeze(0)\n return img_, orig_im, dim\n\ndef write(x, img):\n c1 = tuple(x[1:3].int())\n c2 = tuple(x[3:5].int())\n cls = int(x[-1])\n label = \"{0}\".format(classes[cls])\n color = random.choice(colors)\n cv2.rectangle(img, c1, c2,color, 1)\n t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1 , 1)[0]\n c2 = c1[0] + t_size[0] + 3, c1[1] + t_size[1] + 4\n cv2.rectangle(img, c1, c2,color, -1)\n cv2.putText(img, label, (c1[0], c1[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225,255,255], 1);\n return img\n\ndef arg_parse():\n \"\"\"\n Parse arguements to the detect module\n \n \"\"\"\n \n \n parser = argparse.ArgumentParser(description='YOLO v2 Video Detection Module')\n \n parser.add_argument(\"--video\", dest = 'video', help = \n \"Video to run detection upon\",\n default = \"video.avi\", type = str)\n parser.add_argument(\"--dataset\", dest = \"dataset\", help = \"Dataset on which the network has been trained\", default = \"pascal\")\n parser.add_argument(\"--confidence\", dest = \"confidence\", help = \"Object Confidence to filter predictions\", default = 0.5)\n parser.add_argument(\"--nms_thresh\", dest = \"nms_thresh\", help = \"NMS Threshhold\", default = 0.4)\n parser.add_argument(\"--cfg\", dest = 'cfgfile', help = \n \"Config file\",\n default = \"cfg/yolov3-spp.cfg\", type = str)\n parser.add_argument(\"--weights\", dest = 'weightsfile', help = \n \"weightsfile\",\n default = \"yolov3-spp.weights\", type = str)\n parser.add_argument(\"--reso\", dest = 'reso', help = \n \"Input resolution of the network. Increase to increase accuracy. Decrease to increase speed\",\n default = \"416\", type = str)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = arg_parse()\n confidence = float(args.confidence)\n nms_thesh = float(args.nms_thresh)\n start = 0\n\n CUDA = torch.cuda.is_available()\n\n \n\n CUDA = torch.cuda.is_available()\n num_classes = 80 \n bbox_attrs = 5 + num_classes\n \n print(\"Loading network.....\")\n model = Darknet(args.cfgfile)\n model.load_weights(args.weightsfile)\n print(\"Network successfully loaded\")\n \n model.net_info[\"height\"] = args.reso\n inp_dim = int(model.net_info[\"height\"])\n assert inp_dim % 32 == 0 \n assert inp_dim > 32\n\n \n if CUDA:\n model.cuda().half()\n \n model(get_test_input(inp_dim, CUDA), CUDA)\n\n model.eval()\n \n videofile = 'video.avi'\n \n cap = cv2.VideoCapture(videofile)\n \n assert cap.isOpened(), 'Cannot capture source'\n \n frames = 0\n start = time.time() \n while cap.isOpened():\n \n ret, frame = cap.read()\n if ret:\n \n\n img, orig_im, dim = prep_image(frame, inp_dim)\n \n im_dim = torch.FloatTensor(dim).repeat(1,2) \n \n \n if CUDA:\n img = img.cuda().half()\n im_dim = im_dim.half().cuda()\n write_results = write_results_half\n predict_transform = predict_transform_half\n \n \n output = model(Variable(img, volatile = True), CUDA)\n output = write_results(output, confidence, num_classes, nms = True, nms_conf = nms_thesh)\n\n \n if type(output) == int:\n frames += 1\n print(\"FPS of the video is {:5.2f}\".format( frames / (time.time() - start)))\n cv2.imshow(\"frame\", orig_im)\n key = cv2.waitKey(1)\n if key & 0xFF == ord('q'):\n break\n continue\n\n \n im_dim = im_dim.repeat(output.size(0), 1)\n scaling_factor = torch.min(inp_dim/im_dim,1)[0].view(-1,1)\n \n output[:,[1,3]] -= (inp_dim - scaling_factor*im_dim[:,0].view(-1,1))/2\n output[:,[2,4]] -= (inp_dim - scaling_factor*im_dim[:,1].view(-1,1))/2\n \n output[:,1:5] /= scaling_factor\n \n for i in range(output.shape[0]):\n output[i, [1,3]] = torch.clamp(output[i, [1,3]], 0.0, im_dim[i,0])\n output[i, [2,4]] = torch.clamp(output[i, [2,4]], 0.0, im_dim[i,1])\n \n \n classes = load_classes('data/coco.names')\n colors = pkl.load(open(\"pallete\", \"rb\"))\n \n list(map(lambda x: write(x, orig_im), output))\n \n \n cv2.imshow(\"frame\", orig_im)\n key = cv2.waitKey(1)\n if key & 0xFF == ord('q'):\n break\n frames += 1\n print(\"FPS of the video is {:5.2f}\".format( frames / (time.time() - start)))\n\n \n else:\n break\n \n\n \n \n\n", "import sys\n\nimport torch\nimport torch._utils\nimport torch.nn as nn\nimport torch.utils.data\nimport torch.utils.data.distributed\n\nfrom SPPE.src.models.FastPose import createModel\nfrom SPPE.src.utils.img import flip, shuffleLR\n\ntry:\n torch._utils._rebuild_tensor_v2\nexcept AttributeError:\n def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):\n tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)\n tensor.requires_grad = requires_grad\n tensor._backward_hooks = backward_hooks\n return tensor\n torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2\n\n\nclass InferenNet(nn.Module):\n def __init__(self, kernel_size, dataset):\n super(InferenNet, self).__init__()\n\n model = createModel().cuda()\n print('Loading pose model from {}'.format('joints_detectors/Alphapose/models/sppe/duc_se.pth'))\n sys.stdout.flush()\n model.load_state_dict(torch.load('joints_detectors/Alphapose/models/sppe/duc_se.pth'))\n model.eval()\n self.pyranet = model\n\n self.dataset = dataset\n\n def forward(self, x):\n out = self.pyranet(x)\n out = out.narrow(1, 0, 17)\n\n flip_out = self.pyranet(flip(x))\n flip_out = flip_out.narrow(1, 0, 17)\n\n flip_out = flip(shuffleLR(\n flip_out, self.dataset))\n\n out = (flip_out + out) / 2\n\n return out\n\n\nclass InferenNet_fast(nn.Module):\n def __init__(self, kernel_size, dataset):\n super(InferenNet_fast, self).__init__()\n\n model = createModel().cuda()\n print('Loading pose model from {}'.format('models/sppe/duc_se.pth'))\n model.load_state_dict(torch.load('models/sppe/duc_se.pth'))\n model.eval()\n self.pyranet = model\n\n self.dataset = dataset\n\n def forward(self, x):\n out = self.pyranet(x)\n out = out.narrow(1, 0, 17)\n\n return out\n", "'''\n Author: Guanghan Ning\n E-mail: [email protected]\n Dec, 2016\n'''\n\nimport os\nimport sys\n\nsys.path.append(os.path.abspath(\"../utils/\"))\nfrom utils_convert_heatmap import *\nimport numpy as np\n\n\ndef test_rebin():\n np_array = np.arange(36).reshape([6, 6])\n print(np_array)\n\n cropped = rebin(np_array, (2, 3))\n print(cropped)\n\n\ndef test_pad_heatmaps():\n heatmap = np.arange(64).reshape([8, 8])\n heatmaps = []\n for n in range(3):\n heatmaps.append(heatmap)\n\n norm_size = 8\n scale = 0.8\n heatmaps_pad = pad_heatmaps(heatmaps, norm_size, scale)\n print(heatmaps_pad)\n\n\ndef main():\n print(\"Testing: utils_convert_heatmap\")\n\n passed = test_rebin()\n if passed is False:\n print(\"\\t test_rebin failed\")\n\n passed = test_pad_heatmaps()\n if passed is False:\n print(\"\\t test_pad_heatmaps failed\")\n\n\nif __name__ == '__main__':\n main()\n", "import numpy as np\n\n\ndef soft_nms(boxes, scores, sigma=0.5, Nt=0.3, threshold=0.3, method=0):\n N = boxes.size(0)\n count = 0\n keep = scores.new(scores.size(0)).zero_().long()\n for i in range(N):\n maxscore = scores[i]\n maxpos = i\n tx1 = boxes[i, 0] # temp\n ty1 = boxes[i, 1]\n tx2 = boxes[i, 2]\n ty2 = boxes[i, 3]\n ts = scores[i]\n\n pos = i + 1\n # get max box\n while pos < N:\n if maxscore < scores[pos]:\n maxscore = scores[pos]\n pos = pos + 1\n\n # add max box as a detection\n boxes[i, 0] = boxes[maxpos, 0]\n boxes[i, 1] = boxes[maxpos, 1]\n boxes[i, 2] = boxes[maxpos, 2]\n boxes[i, 3] = boxes[maxpos, 3]\n scores[i] = scores[maxpos]\n\n # swap\n boxes[maxpos, 0] = tx1\n boxes[maxpos, 1] = ty1\n boxes[maxpos, 2] = tx2\n boxes[maxpos, 3] = ty2\n scores[maxpos] = ts\n\n tx1 = boxes[i, 0] # temp\n ty1 = boxes[i, 1]\n tx2 = boxes[i, 2]\n ty2 = boxes[i, 3]\n ts = scores[i]\n keep[count] = i\n pos = i + 1\n\n # NMS iterations\n while pos < N:\n x1 = boxes[i, 0] # temp\n y1 = boxes[i, 1]\n x2 = boxes[i, 2]\n y2 = boxes[i, 3]\n s = scores[i]\n\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n iw = (min(tx2, x2) - max(ty1, y1) + 1)\n if iw > 0:\n ih = (min(ty2, y2) - max(ty1, x1) + 1)\n if ih > 0:\n ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)\n ov = iw * ih / ua # IoU\n\n # import ipdb;ipdb.set_trace()\n if method == 1: # LINEAR\n if ov > Nt:\n weight = 1 - ov\n else:\n weight = 1\n\n elif method == 2: # Gaussain\n weight = np.exp(-(ov * ov) / sigma).data.numpy()\n else: # original NMS\n if ov > Nt:\n weight = 0\n else:\n weight = 1\n\n scores[pos] = weight * scores[pos]\n\n # discard the score less than threshold\n # update N\n if scores[pos] < threshold:\n boxes[pos, 0] = boxes[N - 1, 0]\n boxes[pos, 1] = boxes[N - 1, 1]\n boxes[pos, 2] = boxes[N - 1, 2]\n boxes[pos, 3] = boxes[N - 1, 3]\n scores[pos] = scores[N - 1]\n N = N - 1\n pos = pos - 1\n pos = pos + 1\n\n keep = [i for i in range(N)]\n return keep, N\n", "'''\n Modified by: Guanghan Ning\n E-mail: [email protected]\n March, 2019\n'''\nimport argparse\nfrom functools import partial\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom config import cfg\nfrom nets.basemodel import resnet152, resnet_arg_scope, resnet_v1\nfrom tfflat.base import ModelDesc, Trainer\nfrom tfflat.utils import mem_info\n\nresnet_arg_scope = partial(resnet_arg_scope, bn_trainable=cfg.bn_train)\n\n\ndef create_global_net(blocks, is_training, trainable=True):\n global_fms = []\n global_outs = []\n last_fm = None\n initializer = tf.contrib.layers.xavier_initializer()\n for i, block in enumerate(reversed(blocks)):\n with slim.arg_scope(resnet_arg_scope(bn_is_training=is_training)):\n lateral = slim.conv2d(block, 256, [1, 1],\n trainable=trainable, weights_initializer=initializer,\n padding='SAME', activation_fn=tf.nn.relu,\n scope='lateral/res{}'.format(5 - i))\n\n if last_fm is not None:\n sz = tf.shape(lateral)\n upsample = tf.image.resize_bilinear(last_fm, (sz[1], sz[2]),\n name='upsample/res{}'.format(5 - i))\n upsample = slim.conv2d(upsample, 256, [1, 1],\n trainable=trainable, weights_initializer=initializer,\n padding='SAME', activation_fn=None,\n scope='merge/res{}'.format(5 - i))\n last_fm = upsample + lateral\n else:\n last_fm = lateral\n\n with slim.arg_scope(resnet_arg_scope(bn_is_training=is_training)):\n tmp = slim.conv2d(last_fm, 256, [1, 1],\n trainable=trainable, weights_initializer=initializer,\n padding='SAME', activation_fn=tf.nn.relu,\n scope='tmp/res{}'.format(5 - i))\n out = slim.conv2d(tmp, cfg.nr_skeleton, [3, 3],\n trainable=trainable, weights_initializer=initializer,\n padding='SAME', activation_fn=None,\n scope='pyramid/res{}'.format(5 - i))\n global_fms.append(last_fm)\n global_outs.append(tf.image.resize_bilinear(out, (cfg.output_shape[0], cfg.output_shape[1])))\n global_fms.reverse()\n global_outs.reverse()\n return global_fms, global_outs\n\n\ndef create_refine_net(blocks, is_training, trainable=True):\n initializer = tf.contrib.layers.xavier_initializer()\n bottleneck = resnet_v1.bottleneck\n refine_fms = []\n for i, block in enumerate(blocks):\n mid_fm = block\n with slim.arg_scope(resnet_arg_scope(bn_is_training=is_training)):\n for j in range(i):\n mid_fm = bottleneck(mid_fm, 256, 128, stride=1, scope='res{}/refine_conv{}'.format(2 + i, j)) # no projection\n mid_fm = tf.image.resize_bilinear(mid_fm, (cfg.output_shape[0], cfg.output_shape[1]),\n name='upsample_conv/res{}'.format(2 + i))\n refine_fms.append(mid_fm)\n refine_fm = tf.concat(refine_fms, axis=3)\n with slim.arg_scope(resnet_arg_scope(bn_is_training=is_training)):\n refine_fm = bottleneck(refine_fm, 256, 128, stride=1, scope='final_bottleneck')\n res = slim.conv2d(refine_fm, cfg.nr_skeleton, [3, 3],\n trainable=trainable, weights_initializer=initializer,\n padding='SAME', activation_fn=None,\n scope='refine_out')\n return res\n\n\nclass Network(ModelDesc):\n\n def render_gaussian_heatmap(self, coord, output_shape, sigma):\n\n x = [i for i in range(output_shape[1])]\n y = [i for i in range(output_shape[0])]\n xx, yy = tf.meshgrid(x, y)\n xx = tf.reshape(tf.to_float(xx), (1, *output_shape, 1))\n yy = tf.reshape(tf.to_float(yy), (1, *output_shape, 1))\n\n x = tf.floor(tf.reshape(coord[:, :, 0], [-1, 1, 1, cfg.nr_skeleton]) / cfg.data_shape[1] * output_shape[1] + 0.5)\n y = tf.floor(tf.reshape(coord[:, :, 1], [-1, 1, 1, cfg.nr_skeleton]) / cfg.data_shape[0] * output_shape[0] + 0.5)\n\n heatmap = tf.exp(-(((xx - x) / tf.to_float(sigma)) ** 2) / tf.to_float(2) - (((yy - y) / tf.to_float(sigma)) ** 2) / tf.to_float(2))\n return heatmap * 255.\n\n def make_data(self):\n ''' Load PoseTrack data '''\n from AllJoints_PoseTrack import PoseTrackJoints\n from AllJoints_COCO import PoseTrackJoints_COCO\n from dataset import Preprocessing\n\n d = PoseTrackJoints()\n train_data, _ = d.load_data(cfg.min_kps)\n print(len(train_data))\n\n # '''\n d2 = PoseTrackJoints_COCO()\n train_data_coco, _ = d2.load_data(cfg.min_kps)\n print(len(train_data_coco))\n\n train_data.extend(train_data_coco)\n print(len(train_data))\n # '''\n\n from random import shuffle\n shuffle(train_data)\n\n from tfflat.data_provider import DataFromList, MultiProcessMapDataZMQ, BatchData, MapData\n dp = DataFromList(train_data)\n if cfg.dpflow_enable:\n dp = MultiProcessMapDataZMQ(dp, cfg.nr_dpflows, Preprocessing)\n else:\n dp = MapData(dp, Preprocessing)\n dp = BatchData(dp, cfg.batch_size // cfg.nr_aug)\n dp.reset_state()\n dataiter = dp.get_data()\n\n return dataiter\n\n def head_net(self, blocks, is_training, trainable=True):\n\n normal_initializer = tf.truncated_normal_initializer(0, 0.01)\n msra_initializer = tf.contrib.layers.variance_scaling_initializer()\n xavier_initializer = tf.contrib.layers.xavier_initializer()\n\n with slim.arg_scope(resnet_arg_scope(bn_is_training=is_training)):\n out = slim.conv2d_transpose(blocks[-1], 256, [4, 4], stride=2,\n trainable=trainable, weights_initializer=normal_initializer,\n padding='SAME', activation_fn=tf.nn.relu,\n scope='up1')\n out = slim.conv2d_transpose(out, 256, [4, 4], stride=2,\n trainable=trainable, weights_initializer=normal_initializer,\n padding='SAME', activation_fn=tf.nn.relu,\n scope='up2')\n out = slim.conv2d_transpose(out, 256, [4, 4], stride=2,\n trainable=trainable, weights_initializer=normal_initializer,\n padding='SAME', activation_fn=tf.nn.relu,\n scope='up3')\n\n out = slim.conv2d(out, cfg.nr_skeleton, [1, 1],\n trainable=trainable, weights_initializer=msra_initializer,\n padding='SAME', normalizer_fn=None, activation_fn=None,\n scope='out')\n\n return out\n\n def make_network(self, is_train):\n if is_train:\n image = tf.placeholder(tf.float32, shape=[cfg.batch_size, *cfg.data_shape, 3])\n # target_coord = tf.placeholder(tf.float32, shape=[cfg.batch_size, cfg.nr_skeleton, 2])\n # valid = tf.placeholder(tf.float32, shape=[cfg.batch_size, cfg.nr_skeleton])\n # self.set_inputs(image, target_coord, valid)\n\n label15 = tf.placeholder(tf.float32, shape=[cfg.batch_size, *cfg.output_shape, cfg.nr_skeleton])\n label11 = tf.placeholder(tf.float32, shape=[cfg.batch_size, *cfg.output_shape, cfg.nr_skeleton])\n label9 = tf.placeholder(tf.float32, shape=[cfg.batch_size, *cfg.output_shape, cfg.nr_skeleton])\n label7 = tf.placeholder(tf.float32, shape=[cfg.batch_size, *cfg.output_shape, cfg.nr_skeleton])\n valids = tf.placeholder(tf.float32, shape=[cfg.batch_size, cfg.nr_skeleton])\n labels = [label15, label11, label9, label7]\n # labels.reverse() # The original labels are reversed. For reproduction of our pre-trained model, I'll keep it same.\n self.set_inputs(image, label15, label11, label9, label7, valids)\n else:\n image = tf.placeholder(tf.float32, shape=[None, *cfg.data_shape, 3])\n self.set_inputs(image)\n\n resnet_fms = resnet152(image, is_train, bn_trainable=True)\n\n heatmap_outs = self.head_net(resnet_fms, is_train)\n\n # make loss\n if is_train:\n def ohkm(loss, top_k):\n ohkm_loss = 0.\n for i in range(cfg.batch_size):\n sub_loss = loss[i]\n topk_val, topk_idx = tf.nn.top_k(sub_loss, k=top_k, sorted=False, name='ohkm{}'.format(i))\n tmp_loss = tf.gather(sub_loss, topk_idx, name='ohkm_loss{}'.format(i)) # can be ignore ???\n ohkm_loss += tf.reduce_sum(tmp_loss) / top_k\n ohkm_loss /= cfg.batch_size\n return ohkm_loss\n\n label = label7 * tf.to_float(tf.greater(tf.reshape(valids, (-1, 1, 1, cfg.nr_skeleton)), 0.1))\n loss = tf.reduce_mean(tf.square(heatmap_outs - label))\n\n self.add_tower_summary('loss', loss)\n self.set_loss(loss)\n else:\n self.set_outputs(heatmap_outs)\n\n\nif __name__ == '__main__':\n def parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', '-d', type=str, dest='gpu_ids')\n parser.add_argument('--continue', '-c', dest='continue_train', action='store_true')\n parser.add_argument('--debug', dest='debug', action='store_true')\n args = parser.parse_args()\n\n if not args.gpu_ids:\n args.gpu_ids = str(np.argmin(mem_info()))\n\n if '-' in args.gpu_ids:\n gpus = args.gpu_ids.split('-')\n gpus[0] = 0 if not gpus[0].isdigit() else int(gpus[0])\n gpus[1] = len(mem_info()) if not gpus[1].isdigit() else int(gpus[1]) + 1\n args.gpu_ids = ','.join(map(lambda x: str(x), list(range(*gpus))))\n\n return args\n\n\n args = parse_args()\n\n cfg.set_args(args.gpu_ids, args.continue_train)\n trainer = Trainer(Network(), cfg)\n trainer.train()\n" ]
[ [ "torch.min", "torch.from_numpy", "torch.FloatTensor", "torch.cuda.is_available", "torch.clamp", "torch.autograd.Variable" ], [ "torch._utils._rebuild_tensor", "torch.load" ], [ "numpy.arange" ], [ "numpy.exp" ], [ "tensorflow.image.resize_bilinear", "tensorflow.concat", "tensorflow.contrib.layers.variance_scaling_initializer", "tensorflow.shape", "tensorflow.reduce_sum", "tensorflow.reshape", "tensorflow.truncated_normal_initializer", "tensorflow.placeholder", "tensorflow.contrib.slim.conv2d_transpose", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.contrib.slim.conv2d", "tensorflow.meshgrid", "tensorflow.to_float", "tensorflow.square" ] ]
[ { "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": [ "1.13", "1.10", "1.12" ] } ]
tinapiao/Software-IC-Automation
[ "74b23cd94aa6e4658b110e93b5deb635e014f3a6", "74b23cd94aa6e4658b110e93b5deb635e014f3a6", "74b23cd94aa6e4658b110e93b5deb635e014f3a6", "74b23cd94aa6e4658b110e93b5deb635e014f3a6", "74b23cd94aa6e4658b110e93b5deb635e014f3a6" ]
[ "laygo/generators/serdes/des_layout_generator_woM5.py", "laygo/generators/adc_sar/adc_sar_sarclkgen_static_layout_generator.py", "laygo/generators/serdes/ser_layout_generator.py", "laygo/generators/splash/adc_sar_salatch_pmos_layout_generator_standalone.py", "laygo/generators/splash/adc_sar_sar_wsamp_layout_generator.py" ]
[ "#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"DES library\n\"\"\"\nimport laygo\nimport numpy as np\n#from logic_layout_generator import *\nfrom math import log\nimport yaml\nimport os\n#import logging;logging.basicConfig(level=logging.DEBUG)\n\ndef generate_boundary(laygen, objectname_pfix, placement_grid,\n devname_bottom, devname_top, devname_left, devname_right,\n shape_bottom=None, shape_top=None, shape_left=None, shape_right=None,\n transform_bottom=None, transform_top=None, transform_left=None, transform_right=None,\n origin=np.array([0, 0])):\n #generate a boundary structure to resolve boundary design rules\n pg = placement_grid\n #parameters\n if shape_bottom == None:\n shape_bottom = [np.array([1, 1]) for d in devname_bottom]\n if shape_top == None:\n shape_top = [np.array([1, 1]) for d in devname_top]\n if shape_left == None:\n shape_left = [np.array([1, 1]) for d in devname_left]\n if shape_right == None:\n shape_right = [np.array([1, 1]) for d in devname_right]\n if transform_bottom == None:\n transform_bottom = ['R0' for d in devname_bottom]\n if transform_top == None:\n transform_top = ['R0' for d in devname_top]\n if transform_left == None:\n transform_left = ['R0' for d in devname_left]\n if transform_right == None:\n transform_right = ['R0' for d in devname_right]\n\n #bottom\n dev_bottom=[]\n dev_bottom.append(laygen.place(\"I\" + objectname_pfix + 'BNDBTM0', devname_bottom[0], pg, xy=origin,\n shape=shape_bottom[0], transform=transform_bottom[0]))\n for i, d in enumerate(devname_bottom[1:]):\n dev_bottom.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDBTM'+str(i+1), templatename = d, gridname = pg, refinstname = dev_bottom[-1].name,\n shape=shape_bottom[i+1], transform=transform_bottom[i+1]))\n dev_left=[]\n dev_left.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDLFT0', templatename = devname_left[0], gridname = pg, refinstname = dev_bottom[0].name, direction='top',\n shape=shape_left[0], transform=transform_left[0]))\n for i, d in enumerate(devname_left[1:]):\n dev_left.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDLFT'+str(i+1), templatename = d, gridname = pg, refinstname = dev_left[-1].name, direction='top',\n shape=shape_left[i+1], transform=transform_left[i+1]))\n dev_right=[]\n dev_right.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDRHT0', templatename = devname_right[0], gridname = pg, refinstname = dev_bottom[-1].name, direction='top',\n shape=shape_right[0], transform=transform_right[0]))\n for i, d in enumerate(devname_right[1:]):\n dev_right.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDRHT'+str(i+1), templatename = d, gridname = pg, refinstname = dev_right[-1].name, direction='top',\n shape=shape_right[i+1], transform=transform_right[i+1]))\n dev_top=[]\n dev_top.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDTOP0', templatename = devname_top[0], gridname = pg, refinstname = dev_left[-1].name, direction='top',\n shape=shape_top[0], transform=transform_top[0]))\n for i, d in enumerate(devname_top[1:]):\n dev_top.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDTOP'+str(i+1), templatename = d, gridname = pg, refinstname = dev_top[-1].name,\n shape=shape_top[i+1], transform=transform_top[i+1]))\n dev_right=[]\n return [dev_bottom, dev_top, dev_left, dev_right]\n\ndef generate_deserializer(laygen, objectname_pfix, templib_logic, placement_grid, routing_grid_m2m3,\n routing_grid_m4m5, num_des=8, num_flop=1, m_des_dff=1, origin=np.array([0, 0])):\n \"\"\"generate deserializer \"\"\"\n pg = placement_grid\n\n rg_m2m3 = routing_grid_m2m3\n rg_m4m5 = routing_grid_m4m5\n\n tap_name='tap'\n #ff_name = 'dff_1x'\n #ff_rst_name = 'dff_strsth_1x'\n ff_name = 'dff_'+str(m_des_dff)+'x'\n ff_rst_name = 'dff_strsth_'+str(m_des_dff)+'x'\n\n #Calculate layout size\n x0=num_flop * (2*laygen.templates.get_template(ff_name, templib_logic).xy[1][0] + laygen.templates.get_template(ff_rst_name, templib_logic).xy[1][0]) \\\n + 2*laygen.templates.get_template(tap_name, templib_logic).xy[1][0]\n num_row=int((num_des/num_flop + 0.99))+1\n #boundaries\n m_bnd = int(x0 / laygen.templates.get_template('boundary_bottom').xy[1][0])\n devname_bnd_left = []\n devname_bnd_right = []\n transform_bnd_left = []\n transform_bnd_right = []\n for i in range(num_row):\n if i%2==0:\n devname_bnd_left += ['nmos4_fast_left', 'pmos4_fast_left']\n devname_bnd_right += ['nmos4_fast_right', 'pmos4_fast_right']\n transform_bnd_left += ['R0', 'MX']\n transform_bnd_right += ['R0', 'MX']\n else:\n devname_bnd_left += ['pmos4_fast_left', 'nmos4_fast_left']\n devname_bnd_right += ['pmos4_fast_right', 'nmos4_fast_right']\n transform_bnd_left += ['R0', 'MX']\n transform_bnd_right += ['R0', 'MX']\n [bnd_bottom, bnd_top, bnd_left, bnd_right] = generate_boundary(laygen, objectname_pfix='BND0',\n placement_grid=pg,\n devname_bottom=['boundary_bottomleft',\n 'boundary_bottom',\n 'boundary_bottomright'],\n shape_bottom=[np.array([1, 1]), np.array([m_bnd, 1]),\n np.array([1, 1])],\n devname_top=['boundary_topleft', 'boundary_top',\n 'boundary_topright'],\n shape_top=[np.array([1, 1]), np.array([m_bnd, 1]),\n np.array([1, 1])],\n devname_left=devname_bnd_left,\n transform_left=transform_bnd_left,\n devname_right=devname_bnd_right,\n transform_right=transform_bnd_right,\n origin=np.array([0, 0]))\n #Calculate origins for placement\n tap_origin = origin + laygen.get_xy(obj = bnd_bottom[0], gridname = pg) \\\n + laygen.get_xy(obj = bnd_bottom[0].template, gridname = pg)\n array_origin = origin + laygen.get_xy(obj = bnd_bottom[0], gridname = pg) \\\n + laygen.get_xy(obj = bnd_bottom[0].template, gridname = pg) \\\n + np.array([laygen.get_xy(obj=laygen.get_template(name = tap_name, libname = templib_logic), gridname = pg)[0], 0])\n tapr_origin = tap_origin + m_bnd*np.array([laygen.get_xy(obj=laygen.get_template(name = 'boundary_bottom'), gridname = pg)[0], 0]) \\\n - np.array([laygen.get_xy(obj=laygen.get_template(name = tap_name, libname = templib_logic), gridname = pg)[0], 0])\n FF0_origin = array_origin + np.array([0, laygen.get_xy(obj=laygen.get_template(name = 'inv_1x', libname = templib_logic), gridname = pg)[1]]) + \\\n np.array([0, laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)[1]])\n # placement\n iffout=[]\n iffin=[]\n iffdiv=[]\n iclkbuf=[]\n idivbuf=[]\n isp1x=[]\n itapl=[]\n itapr=[]\n tf='R0'\n if num_flop == 1: #Layout height reduction factor, no reduction\n for i in range(num_row):\n if i%2==0: tf='R0'\n else: tf='MX'\n if i==0: #Row for clock buffers \n itapl.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPL0', templatename = tap_name,\n gridname = pg, xy=tap_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n itapr.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPR0', templatename = tap_name,\n gridname = pg, xy=tapr_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n idivbuf.append(laygen.place(name = \"I\" + objectname_pfix + 'DIVBUF32x', templatename = 'inv_32x',\n gridname = pg, xy=array_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF8x', templatename = 'inv_8x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF2x', templatename = 'inv_2x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF1x', templatename = 'inv_1x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF1x', templatename = 'inv_1x',\n gridname = pg, refinstname = idivbuf[3].name, transform=tf, shape=np.array([1,1]), xy=np.array([0,0]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF2x', templatename = 'inv_2x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF8x', templatename = 'inv_8x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF32x', templatename = 'inv_32x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n else:\n itapl.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPL'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapl[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n itapr.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPR'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapr[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n if i==1: #Reference FF: FFOUT1\n iffout.append(laygen.place(name = \"I\" + objectname_pfix + 'FFOUT1', templatename = ff_name,\n gridname = pg, xy=FF0_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n else:\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT'+str(i), templatename = ff_name,\n gridname = pg, refinstname = iffout[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n refi = iffout[-1].name\n iffin.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFIN'+str(i), templatename = ff_name,\n gridname = pg, refinstname = refi, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n refi2 = iffin[-1].name\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV'+str(i), templatename = ff_rst_name,\n gridname = pg, refinstname = refi2, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n if num_flop == 2: #Layout height reduced by half\n for i in range(num_row):\n if i%2==0: tf='R0'\n else: tf='MX'\n if i==0: #Low for clock buffers \n itapl.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPL0', templatename = tap_name,\n gridname = pg, xy=tap_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n itapr.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPR0', templatename = tap_name,\n gridname = pg, xy=tapr_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n idivbuf.append(laygen.place(name = \"I\" + objectname_pfix + 'DIVBUF32x', templatename = 'inv_32x',\n gridname = pg, xy=array_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF8x', templatename = 'inv_8x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF2x', templatename = 'inv_2x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n idivbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'DIVBUF1x', templatename = 'inv_1x',\n gridname = pg, refinstname = idivbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF1x', templatename = 'inv_1x',\n gridname = pg, refinstname = idivbuf[3].name, transform=tf, shape=np.array([1,1]), xy=np.array([0,0]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF2x', templatename = 'inv_2x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF8x', templatename = 'inv_8x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iclkbuf.append(laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF32x', templatename = 'inv_32x',\n gridname = pg, refinstname = iclkbuf[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n else:\n itapl.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPL'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapl[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n itapr.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPR'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapr[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n if i==1: #Reference FF: FFOUT1 and FFOUT2\n iffout.append(laygen.place(name = \"I\" + objectname_pfix + 'FFOUT1', templatename = ff_name,\n gridname = pg, xy=FF0_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT2', templatename = ff_name,\n gridname = pg, refinstname = iffout[0].name, transform=tf, shape=np.array([1,1]),\n direction = 'right', template_libname=templib_logic))\n elif i==(num_row-1): #The last low depending on num_des: even or odd\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT'+str(2*i-1), templatename = ff_name,\n gridname = pg, refinstname = iffout[-2].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n if num_des%2==0: #If not, space should be placed rather than FF\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT'+str(2*i), templatename = ff_name,\n gridname = pg, refinstname = iffout[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'right', template_libname=templib_logic))\n else: #FFOUTs will be the reference for FFIN and FFDIV\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT'+str(2*i-1), templatename = ff_name,\n gridname = pg, refinstname = iffout[-2].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n iffout.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFOUT'+str(2*i), templatename = ff_name,\n gridname = pg, refinstname = iffout[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'right', template_libname=templib_logic))\n for j in range(num_des): #Relplace of FFIN and the left side of FFDIV\n if iffout[j].transform=='MX': tf='MX'\n else: tf='R0'\n iffin.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFIN'+str(j+1), templatename = ff_name,\n gridname = pg, refinstname = iffout[j].name, transform=tf, shape=np.array([1,1]),\n xy=np.array([laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)[0], 0]), template_libname=templib_logic))\n if j%2==0:\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV'+str(int(j/2+1)), templatename = ff_rst_name,\n gridname = pg, refinstname = iffin[j].name, transform=tf, shape=np.array([1,1]),\n xy=np.array([laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)[0], 0]), template_libname=templib_logic))\n for i in range(num_row, num_des+1): #Right side of FFDIV\n if num_des%2==1:\n if i%2==0: tf='R0'\n else: tf='MX'\n if num_des%2==0:\n if i%2==0: tf='MX'\n else: tf='R0'\n if i==num_row: #Even: relplaced by top FFDIV, odd: relplaced by second FFDIV from top\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV'+str(i), templatename = ff_rst_name,\n gridname = pg, refinstname = iffdiv[int(num_des/2)-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'right', template_libname=templib_logic))\n else:\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV'+str(i), templatename = ff_rst_name,\n gridname = pg, refinstname = iffdiv[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'bottom', template_libname=templib_logic))\n\n #Space placement at the first row\n space_name = 'space_1x'\n space4x_name = 'space_4x'\n space_width = laygen.get_xy(obj=laygen.get_template(name = space_name, libname = templib_logic), gridname = pg)[0]\n space4_width = laygen.get_xy(obj=laygen.get_template(name = space4x_name, libname = templib_logic), gridname = pg)[0]\n inv_width=[]\n for i in (1,2,8,32):\n inv_width.append(laygen.get_xy(obj=laygen.get_template(name = 'inv_' + str(i) + 'x', libname = templib_logic), gridname = pg)[0])\n blank_width = tapr_origin[0] - array_origin[0] - 2 * (inv_width[0]+inv_width[1]+inv_width[2]+inv_width[3])\n m_space4 = int(blank_width / space4_width)\n m_space1 = int((blank_width-m_space4*space4_width)/space_width)\n ispace4=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE4', templatename = space4x_name,\n gridname = pg, refinstname = iclkbuf[3].name, transform='R0', shape=np.array([m_space4-1,1]),\n template_libname=templib_logic)\n ispace1=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE1', templatename = space_name,\n gridname = pg, refinstname = ispace4.name, transform='R0', shape=np.array([m_space1+4,1]),\n template_libname=templib_logic)\n #Space placement at the last row for odd num_des\n m_ff_space = int(laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)[0] / space_width)\n m_ffrst_space = int(laygen.get_xy(obj=laygen.get_template(name = ff_rst_name, libname = templib_logic), gridname = pg)[0] / space_width)\n if (num_des%2)==1:\n if num_flop==2:\n ispace_out=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACEOUT', templatename = space_name,\n gridname = pg, refinstname = iffout[num_des-1].name, transform=iffout[num_des-1].transform, shape=np.array([m_ff_space,1]),\n template_libname=templib_logic)\n ispace_in=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACEIN', templatename = space_name,\n gridname = pg, refinstname = iffin[num_des-1].name, transform=iffin[num_des-1].transform, shape=np.array([m_ff_space,1]),\n template_libname=templib_logic)\n ispace_div=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACEDIV', templatename = space_name,\n gridname = pg, refinstname = iffdiv[int(num_des/2)].name, transform=iffdiv[int(num_des/2)].transform, shape=np.array([m_ffrst_space,1]),\n template_libname=templib_logic)\n \n #Internal Pins\n ffin_in_xy=[]\n ffin_in_xy45=[]\n ffin_out_xy=[]\n ffout_in_xy=[]\n ffout_out_xy=[]\n ffdiv_in_xy=[]\n ffdiv_in_xy45=[]\n ffdiv_out_xy=[]\n ffdiv_rst_xy=[]\n ffdiv_st_xy=[]\n for i in range(num_des):\n ffin_in_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'I', rg_m3m4))\n ffin_out_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'O', rg_m3m4))\n ffout_in_xy.append(laygen.get_inst_pin_xy(iffout[i].name, 'I', rg_m3m4))\n ffout_out_xy.append(laygen.get_inst_pin_xy(iffout[i].name, 'O', rg_m3m4))\n ffdiv_in_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'I', rg_m3m4))\n ffdiv_out_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'O', rg_m3m4))\n ffdiv_rst_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'RST', rg_m3m4))\n ffdiv_st_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'ST', rg_m3m4))\n ffin_in_xy45.append(laygen.get_inst_pin_xy(iffin[i].name, 'I', rg_m4m5))\n ffdiv_in_xy45.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'I', rg_m4m5))\n # Route\n for i in range(num_des):\n if num_flop==1: #Routing offset selection for rows in R0 and MX\n if iffin[i].transform=='MX': offset=1\n if iffin[i].transform=='R0': offset=4\n if iffdiv[i].transform=='MX': offset_div=1\n if iffdiv[i].transform=='R0': offset_div=3\n if num_flop==2: #Offset_div would be different because of different placement\n if i in range(int((num_des+1)/2)):\n if iffin[i].transform=='MX': \n if i%2==1:\n offset=1\n else:\n offset=8\n if iffin[i].transform=='R0': offset=3+i%2\n if iffdiv[i].transform=='MX': offset_div=1\n if iffdiv[i].transform=='R0': offset_div=3\n else:\n if iffin[i].transform=='MX':\n if i%2==1:\n offset=1\n else:\n offset=8\n if iffin[i].transform=='R0': offset=3+i%2\n if iffdiv[i].transform=='MX': offset_div=10\n if iffdiv[i].transform=='R0': offset_div=13\n if i in range(num_des-1):\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #in-to-in\n ffin_out_xy[i][0], ffin_in_xy[i+1][0], ffin_out_xy[i][1][1]+7-offset, rg_m3m4) \n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #div-to-div \n ffdiv_out_xy[i][0], ffdiv_in_xy[i+1][0]-np.array([0,0]), ffdiv_out_xy[i][1][1]+7-offset_div, rg_m3m4)\n #[rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # ffdiv_in_xy[i+1][0], ffdiv_in_xy[i+1][0]-np.array([0,0]), ffdiv_in_xy[i+1][0][1], rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #in-to-out\n ffin_out_xy[i][0], ffout_in_xy[i][0], ffin_out_xy[i][1][1]+7-offset, rg_m3m4)\n if m_des_dff==1:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #div feedback\n ffdiv_out_xy[num_des-1][0], ffdiv_in_xy[0][0]+np.array([-2,0]), ffdiv_out_xy[num_des-1][1][1]+7-offset_div,\n rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #M3-to-M5\n ffdiv_in_xy[0][0], ffdiv_in_xy[0][1]+np.array([-2,0]), ffdiv_in_xy[0][0][1], rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n else:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #div feedback\n ffdiv_out_xy[num_des-1][0], ffdiv_in_xy[0][0]+np.array([-2,0]), ffdiv_out_xy[num_des-1][1][1]+7-offset_div, \n rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #M3-to-M5\n ffdiv_in_xy[0][0], ffdiv_in_xy[0][1]+np.array([-2,0]), ffdiv_in_xy[0][0][1], rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n #CLK Buffer\n for i in range(3):\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(iclkbuf[i].name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(iclkbuf[i + 1].name, 'I', rg_m3m4)[0],\n laygen.get_inst_pin_xy(iclkbuf[i].name, 'O', rg_m3m4)[0][1] + i % 2, rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(idivbuf[3 - i].name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(idivbuf[2 - i].name, 'I', rg_m3m4)[0],\n laygen.get_inst_pin_xy(idivbuf[3 - i].name, 'O', rg_m3m4)[0][1] + i % 2, rg_m3m4)\n\n #DIVCLK Route\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(idivbuf[3].name, 'I', rg_m3m4)[0], laygen.get_inst_pin_xy(iffdiv[0].name, 'I', rg_m3m4)[0],\n laygen.get_inst_pin_xy(idivbuf[3].name, 'I', rg_m3m4)[0][1] + 3, rg_m3m4)\n for i in range(num_des):\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(idivbuf[0].name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(iffout[i].name, 'CLK', rg_m3m4)[0],\n laygen.get_inst_pin_xy(idivbuf[0].name, 'O', rg_m3m4)[0][1] + 5, rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(iclkbuf[3].name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(iffin[i].name, 'CLK', rg_m3m4)[0],\n laygen.get_inst_pin_xy(iclkbuf[3].name, 'O', rg_m3m4)[0][1] + 6, rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(iclkbuf[3].name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(iffdiv[i].name, 'CLK', rg_m3m4)[0],\n laygen.get_inst_pin_xy(iclkbuf[3].name, 'O', rg_m3m4)[0][1] + 6, rg_m3m4)\n #RST Route\n for i in range(num_des):\n if i in range(int((num_des+1)/2)): #First half of FFDIVs\n if not i==int((num_des+1)/2)-1:\n rrst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_rst_xy[i][0], xy1=ffdiv_rst_xy[i+1][0], gridname0=rg_m3m4)\n rst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_st_xy[i][0], xy1=ffdiv_st_xy[i+1][0], gridname0=rg_m3m4)\n #[rrstv, rrsth] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # ffdiv_rst_xy[i][0], ffdiv_rst_xy[i+1][0], rg_m3m4)\n #[rstv, rsth] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # ffdiv_st_xy[i][0], ffdiv_st_xy[i+1][0], rg_m3m4)\n else:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n ffdiv_rst_xy[i][0], ffdiv_st_xy[i+1][0], ffdiv_rst_xy[i][1][1]+5, rg_m3m4)\n else: #Second half of FFDIVs\n if not i==num_des-1:\n rst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_st_xy[i][0], xy1=ffdiv_st_xy[i+1][0], gridname0=rg_m3m4)\n rrst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_rst_xy[i][0], xy1=ffdiv_rst_xy[i+1][0], gridname0=rg_m3m4)\n #[rrstv, rrsth] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # ffdiv_rst_xy[i][0], ffdiv_rst_xy[i+1][0], rg_m3m4)\n #[rstv, rsth] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # ffdiv_st_xy[i][0], ffdiv_st_xy[i+1][0], rg_m3m4)\n [rh0, rv0] = laygen.route_hv(laygen.layers['metal'][2], laygen.layers['metal'][3],\n laygen.get_inst_pin_xy(iffdiv[0].name, 'VSS', rg_m2m3)[0], laygen.get_inst_pin_xy(iffdiv[0].name, 'ST', rg_m2m3)[0], rg_m2m3)\n [rh0, rv0] = laygen.route_hv(laygen.layers['metal'][2], laygen.layers['metal'][3],\n laygen.get_inst_pin_xy(iffdiv[num_des - 1].name, 'VSS', rg_m2m3)[0], laygen.get_inst_pin_xy(iffdiv[num_des - 1].name, 'RST', rg_m2m3)[0], rg_m2m3)\n \n #Pin\n clkin_xy=laygen.get_inst_pin_xy(iclkbuf[0].name, 'I', rg_m3m4)\n rclkin=laygen.route(None, laygen.layers['metal'][3], xy0=clkin_xy[0], xy1=np.array([clkin_xy[0][0],0]), gridname0=rg_m3m4)\n laygen.boundary_pin_from_rect(rclkin, rg_m3m4, \"clk\", laygen.layers['pin'][3], size=0, direction='left')\n divin_xy=laygen.get_inst_pin_xy(idivbuf[len(divbuf_list)-1].name, 'I', rg_m3m4)\n rdivin=laygen.route(None, laygen.layers['metal'][3], xy0=divin_xy[0], xy1=np.array([divin_xy[0][0],0]), gridname0=rg_m3m4)\n laygen.boundary_pin_from_rect(rdivin, rg_m3m4, \"div<0>\", laygen.layers['pin'][3], size=0, direction='left')\n din_xy34=laygen.get_inst_pin_xy(iffin[0].name, 'I', rg_m3m4)\n din_xy45=laygen.get_inst_pin_xy(iffin[0].name, 'I', rg_m4m5)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n din_xy34[0], np.array([din_xy34[0][0]-1,0]), din_xy34[0][1], \n rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n rdummy = laygen.route(None, laygen.layers['metal'][4], xy0=din_xy34[0], xy1=din_xy34[0]+np.array([-4,0]), gridname0=rg_m3m4)\n laygen.boundary_pin_from_rect(rv1, rg_m3m4, \"in\", laygen.layers['pin'][3], size=4, direction='bottom')\n for i in range(num_des):\n datao_xy = laygen.get_inst_pin_xy(iffout[i].name, 'O', rg_m3m4)\n laygen.pin(name='dout<'+str(i)+'>', layer=laygen.layers['pin'][3], xy=datao_xy, gridname=rg_m3m4)\n clkdiv_xy = laygen.get_inst_pin_xy(iffout[-1].name, 'CLK', rg_m3m4)\n laygen.pin(name='clk_div', layer=laygen.layers['pin'][3], xy=clkdiv_xy, gridname=rg_m3m4)\n rst_xy34=laygen.get_inst_pin_xy(iffdiv[0].name, 'RST', rg_m3m4)\n rst_xy45=laygen.get_inst_pin_xy(iffdiv[0].name, 'RST', rg_m4m5)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n rst_xy34[0], np.array([rst_xy34[0][0]-2,0]), rst_xy34[0][1], \n rg_m3m4, layerv1=laygen.layers['metal'][3], gridname1=rg_m3m4)\n rdummy = laygen.route(None, laygen.layers['metal'][4], xy0=rst_xy34[0], xy1=rst_xy34[0]+np.array([-4,0]), gridname0=rg_m3m4)\n laygen.boundary_pin_from_rect(rv1, rg_m3m4, \"RST\", laygen.layers['pin'][3], size=4, direction='bottom')\n\n # power pin\n pwr_dim=laygen.get_xy(obj =itapl[-1].template, gridname=rg_m2m3)\n rvdd = []\n rvss = []\n if num_row%2==0: rp1='VSS'\n else: rp1='VDD'\n print(int(pwr_dim[0]/2))\n for i in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i, 0]), xy1=np.array([2*i, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+1, 0]), xy1=np.array([2*i+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2+1, 0]), xy1=np.array([2*i+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2, 0]), xy1=np.array([2*i+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n \n for i in range(num_row):\n for j in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j, 0]), xy1=np.array([2*j, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapl[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+1, 0]), xy1=np.array([2*j+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2+1, 0]), xy1=np.array([2*j+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapr[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2, 0]), xy1=np.array([2*j+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n \nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'serdes_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n\n #display\n #laygen.display()\n #laygen.templates.display()\n #laygen.save_template(filename=workinglib+'_templates.yaml', libname=workinglib)\n\n mycell_list = []\n \n #load from preset\n load_from_file=True\n yamlfile_spec=\"serdes_spec.yaml\"\n yamlfile_size=\"serdes_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n cell_name='des_1to'+str(specdict['num_des'])\n num_des=specdict['num_des']\n num_flop=specdict['num_flop']\n m_des_dff=sizedict['m_des_dff']\n clkbuf_list=sizedict['des_clkbuf_list']\n divbuf_list=sizedict['des_divbuf_list']\n\n print(cell_name+\" generating\")\n mycell_list.append(cell_name)\n laygen.add_cell(cell_name)\n laygen.sel_cell(cell_name)\n generate_deserializer(laygen, objectname_pfix='DES', templib_logic=logictemplib, \n placement_grid=pg, routing_grid_m2m3=rg_m2m3, routing_grid_m4m5=rg_m4m5, num_des=num_des,\n num_flop=num_flop, m_des_dff=m_des_dff, origin=np.array([0, 0]))\n laygen.add_template_from_cell()\n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n", "#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"ADC library\n\"\"\"\nimport laygo\nimport numpy as np\nimport yaml\nimport os\n#import logging;logging.basicConfig(level=logging.DEBUG)\n\ndef create_power_pin_from_inst(laygen, layer, gridname, inst_left, inst_right):\n \"\"\"create power pin\"\"\"\n rvdd0_pin_xy = laygen.get_inst_pin_xy(inst_left.name, 'VDD', gridname, sort=True)\n rvdd1_pin_xy = laygen.get_inst_pin_xy(inst_right.name, 'VDD', gridname, sort=True)\n rvss0_pin_xy = laygen.get_inst_pin_xy(inst_left.name, 'VSS', gridname, sort=True)\n rvss1_pin_xy = laygen.get_inst_pin_xy(inst_right.name, 'VSS', gridname, sort=True)\n\n laygen.pin(name='VDD', layer=layer, xy=np.vstack((rvdd0_pin_xy[0],rvdd1_pin_xy[1])), gridname=gridname)\n laygen.pin(name='VSS', layer=layer, xy=np.vstack((rvss0_pin_xy[0],rvss1_pin_xy[1])), gridname=gridname)\n\ndef generate_sarclkgen_static(laygen, objectname_pfix, templib_logic, placement_grid, routing_grid_m3m4,\n m=2, fo=2, m_space_left_4x=0, m_space_4x=0, m_space_2x=0, m_space_1x=0, fast=True, origin=np.array([0, 0]),\n mux_fast=False):\n \"\"\"generate a static sar clock generator \"\"\"\n pg = placement_grid\n rg_m3m4 = routing_grid_m3m4\n\n tap_name = 'tap'\n inv_name = 'inv_' + str(m) + 'x'\n invd_name = 'inv_1x'\n iobuf_name = 'inv_' + str(fo*m) + 'x'\n iobuf2_name = 'inv_' + str(fo*m*2) + 'x'\n nand_name = 'nand_' + str(2*m) + 'x'\n nand2_name = 'nand_' + str(fo*m) + 'x'\n nor_name = 'nor_' + str(m) + 'x'\n sr_name = 'ndsr_2x'\n mux_name = 'mux2to1_' + str(2*m) + 'x' # static signal, doesn't need fast?\n core_name = 'sarclkgen_core_static2'\n #core2_name = 'sarclkgen_core2'\n delay_name = 'sarclkdelay_compact_dual'\n space_1x_name = 'space_1x'\n space_2x_name = 'space_2x'\n space_4x_name = 'space_4x'\n\n # placement\n itapl = laygen.place(name = \"I\" + objectname_pfix + 'TAPL0', templatename = tap_name,\n gridname = pg, xy=origin, template_libname = templib_logic)\n refi=itapl.name\n if not m_space_left_4x==0:\n ispl4x=laygen.relplace(name=\"I\" + objectname_pfix + 'SPL4X0', templatename=space_4x_name,\n shape = np.array([m_space_left_4x, 1]), gridname=pg,\n refinstname=refi, template_libname=templib_logic)\n refi = ispl4x.name\n iinv7 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV7', templatename=invd_name,\n gridname=pg, refinstname=refi, template_libname=templib_logic)\n inand0 = laygen.relplace(name=\"I\" + objectname_pfix + 'ND0', templatename=nand_name,\n gridname=pg, refinstname=iinv7.name, template_libname=templib_logic)\n #icore2 = laygen.relplace(name=\"I\" + objectname_pfix + 'CORE2', templatename=core2_name,\n # gridname=pg, refinstname=iinv7.name, template_libname=workinglib)\n #inand0=icore2\n idly0 = laygen.relplace(name=\"I\" + objectname_pfix + 'DLY0', templatename=delay_name,\n gridname=pg, refinstname=inand0.name, template_libname=workinglib)\n iinv5 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV5', templatename=inv_name,\n gridname=pg, refinstname=idly0.name, template_libname=templib_logic)\n if mux_fast is False:\n icore0 = laygen.relplace(name=\"I\" + objectname_pfix + 'CORE0', templatename=core_name,\n gridname=pg, refinstname=iinv5.name, template_libname=workinglib)\n else:\n imuxinv = laygen.relplace(name='I'+objectname_pfix+'MUXINV0', templatename=inv_name,\n gridname=pg, refinstname=iinv5.name, template_libname=templib_logic)\n imux0 = laygen.relplace(name=\"I\" + objectname_pfix + 'MUX0', templatename=mux_name,\n gridname=pg, refinstname=imuxinv.name, template_libname=templib_logic)\n icore0 = laygen.relplace(name=\"I\" + objectname_pfix +'CORE0', templatename=core_name,\n gridname=pg, refinstname=imux0.name, template_libname=workinglib)\n iinv8 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV8', templatename=iobuf_name,\n gridname=pg, refinstname=icore0.name, template_libname=templib_logic)\n iinv8b = laygen.relplace(name=\"I\" + objectname_pfix + 'INV8B', templatename=iobuf2_name,\n gridname=pg, refinstname=iinv8.name, template_libname=templib_logic)\n iinv8c = laygen.relplace(name=\"I\" + objectname_pfix + 'INV8C', templatename=iobuf2_name,\n gridname=pg, refinstname=iinv8b.name, template_libname=templib_logic)\n iinv0 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV0', templatename=invd_name,\n gridname=pg, refinstname=iinv8c.name, template_libname=templib_logic)\n iinv1 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV1', templatename=invd_name,\n gridname=pg, refinstname=iinv0.name, template_libname=templib_logic)\n iinv2 = laygen.relplace(name=\"I\" + objectname_pfix + 'INV2', templatename=invd_name,\n gridname=pg, refinstname=iinv1.name, template_libname=templib_logic)\n\n #refl=iinv8c.name\n #reflcn=iinv8c.cellname\n #refl=iinv8.name\n #reflcn=iinv8.cellname\n refl=iinv2.name\n reflcn=iinv2.cellname\n isp4x = []\n isp2x = []\n isp1x = []\n refi=refl\n if not m_space_4x==0:\n isp4x.append(laygen.relplace(name=\"I\" + objectname_pfix + 'SP4X0', templatename=space_4x_name,\n shape = np.array([m_space_4x, 1]), gridname=pg,\n refinstname=refi, template_libname=templib_logic))\n refi = isp4x[-1].name\n if not m_space_2x==0:\n isp2x.append(laygen.relplace(name=\"I\" + objectname_pfix + 'SP2X0', templatename=space_2x_name,\n shape = np.array([m_space_2x, 1]), gridname=pg,\n refinstname=refi, template_libname=templib_logic))\n refi = isp2x[-1].name\n if not m_space_1x==0:\n isp1x.append(laygen.relplace(name=\"I\" + objectname_pfix + 'SP1X0', templatename=space_1x_name,\n shape=np.array([m_space_1x, 1]), gridname=pg,\n refinstname=refi, template_libname=templib_logic))\n refi = isp1x[-1].name\n itapr=laygen.relplace(name = \"I\" + objectname_pfix + 'TAPR0', templatename = tap_name,\n gridname = pg, refinstname = refi, template_libname = templib_logic)\n\n # internal pins\n pdict = laygen.get_inst_pin_xy(None, None, rg_m3m4)\n pdict23 = laygen.get_inst_pin_xy(None, None, rg_m2m3)\n\n # internal routes\n #x0 = laygen.get_xy(obj =inand0, gridname=rg_m3m4)[0] + 1\n x0 = laygen.get_xy(obj =iinv7, gridname=rg_m3m4)[0] + 1\n x1 = laygen.get_xy(obj =laygen.get_inst(name=refl), gridname=rg_m3m4)[0]\\\n +laygen.get_xy(obj=laygen.get_template(name=reflcn, libname=templib_logic), gridname=rg_m3m4)[0] - 1\n y0 = pdict[inand0.name]['A'][0][1] + 0\n # internal routes - and2\n [rv0, rphi0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore0.name]['PHI0'][0],\n pdict[iinv8.name]['I'][0], y0 - 2 + 1, rg_m3m4)\n\n # internal routes - clkdelay\n [rv0, rdone0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[inand0.name]['O'][0],\n pdict[idly0.name]['I'][0], y0 + 0+2, rg_m3m4) \n\n # internal routes - phi0 logic\n [rv0, rup0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[idly0.name]['O'][0],\n pdict[iinv5.name]['I'][0], y0 + 0, rg_m3m4) # up\n if fast==True and mux_fast==False:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore0.name]['UPB'][0],\n pdict[iinv5.name]['O'][0], y0 + 2-1+1, rg_m3m4) # upb\n elif fast==False:\n [rv0, rh0] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][2], pdict23[icore0.name]['UPB'][0],\n pdict23[icore0.name]['VDD'][0], rg_m2m3) # upb\n else:\n laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[imux0.name]['EN0'][0],\n pdict[imuxinv.name]['O'][0], y0+2-1, rg_m3m4)\n laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[imux0.name]['EN1'][0],\n pdict[imuxinv.name]['I'][0], y0, rg_m3m4)\n laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[imux0.name]['I0'][0],\n pdict[iinv5.name]['O'][0], y0+2-1+1, rg_m3m4)\n laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][2], pdict23[imux0.name]['I1'][0],\n pdict23[imux0.name]['VDD'][0], rg_m2m3) # upb\n laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore0.name]['UPB'][0],\n pdict[imux0.name]['O'][0], y0+2-1+1, rg_m3m4)\n\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore0.name]['DONE'][0],\n pdict[inand0.name]['O'][0], y0 + 0+4, rg_m3m4) #DONE-pre\n # internal routes - outputbuf\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv8.name]['O'][0],\n pdict[iinv8b.name]['I'][0], y0 - 1, rg_m3m4) \n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv8b.name]['O'][0],\n pdict[iinv8c.name]['I'][0], y0 + 1, rg_m3m4) \n\n # input routes\n rv0, rsaop0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[inand0.name]['A'][0],\n np.array([x0, y0 + 2+1]), rg_m3m4)\n rv0, rsaom0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[inand0.name]['B'][0],\n np.array([x0, y0 + 1]), rg_m3m4)\n rv0, rrst0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore0.name]['RST'][0],\n np.array([x0, y0 - 2+1]), rg_m3m4)\n rv0, rextsel_clk0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv7.name]['I'][0],\n np.array([x0, y0 + 5]), rg_m3m4)\n #rv0, rextclk0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv9.name]['I'][0],\n # np.array([x0, y0 + 5]), rg_m3m4)\n\n #sel routes\n rv0, rsel0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv0.name]['O'][0],\n pdict[idly0.name]['SEL<0>'][0], rg_m3m4)\n rv0, rsel1 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv1.name]['O'][0],\n pdict[idly0.name]['SEL<1>'][0], rg_m3m4)\n rv0, rsel2 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv2.name]['O'][0],\n pdict[idly0.name]['SEL<2>'][0], rg_m3m4)\n rv0, rsel0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv0.name]['I'][0],\n np.array([x1, y0+5]), rg_m3m4)\n rv0, rsel1 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv1.name]['I'][0],\n np.array([x1, y0+4]), rg_m3m4)\n rv0, rsel2 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv2.name]['I'][0],\n np.array([x1, y0+3]), rg_m3m4)\n #rsel0 = laygen.route(None, laygen.layers['metal'][4], xy0=pdict[idly0.name]['SEL<0>'][0], xy1=np.array([x1, pdict[idly0.name]['SEL<0>'][0][1]]), gridname0=rg_m3m4)\n #rsel1 = laygen.route(None, laygen.layers['metal'][4], xy0=pdict[idly0.name]['SEL<1>'][0], xy1=np.array([x1, pdict[idly0.name]['SEL<1>'][0][1]]), gridname0=rg_m3m4)\n #Short/en\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv7.name]['O'][0],\n pdict[idly0.name]['ENB'][0], y0 - 7, rg_m3m4) # upb\n #rv0, rshort0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[idly0.name]['SHORTB'][0],\n # np.array([x0, y0+8]), rg_m3m4)\n rv0, rshort0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[idly0.name]['SHORTB'][0],\n np.array([pdict[idly0.name]['SHORTB'][0][0]+6, y0-9]), rg_m3m4)\n\n if mux_fast is True:\n _, rmodesel0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[imuxinv.name]['I'][0],\n np.array([pdict[imuxinv.name]['I'][0][0]+6, y0-8]), rg_m3m4)\n\n #output routes\n #[rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[icore2.name]['CLKB'][0],\n # pdict[iinv8c.name]['O'][0], y0 + 8-13, rg_m3m4) \n v0, rclkob0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv8c.name]['O'][0],\n np.array([x1, y0 + 8-13]), rg_m3m4)\n v0, rclko0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv8b.name]['O'][0],\n np.array([x1, y0 + 1]), rg_m3m4)\n\n # pins\n laygen.boundary_pin_from_rect(rsaop0, rg_m3m4, \"SAOP\", laygen.layers['pin'][4], size=6, direction='left')\n laygen.boundary_pin_from_rect(rsaom0, rg_m3m4, \"SAOM\", laygen.layers['pin'][4], size=6, direction='left')\n laygen.boundary_pin_from_rect(rphi0, rg_m3m4, \"PHI0\", laygen.layers['pin'][4], size=6, direction='left')\n laygen.boundary_pin_from_rect(rrst0, rg_m3m4, \"RST\", laygen.layers['pin'][4], size=6, direction='left')\n laygen.boundary_pin_from_rect(rup0, rg_m3m4, \"UP\", laygen.layers['pin'][4], size=4, direction='right')\n laygen.boundary_pin_from_rect(rextsel_clk0, rg_m3m4, \"EXTSEL_CLK\", laygen.layers['pin'][4], size=6,\n direction='left')\n laygen.boundary_pin_from_rect(rshort0, rg_m3m4, \"SHORTB\", laygen.layers['pin'][4], size=6, direction='left')\n #laygen.boundary_pin_from_rect(rextclk0, rg_m3m4, \"EXTCLK\", laygen.layers['pin'][4], size=6, direction='left')\n if mux_fast is True:\n laygen.boundary_pin_from_rect(rmodesel0, rg_m3m4, \"MODESEL\", laygen.layers['pin'][4], size=6, direction='left')\n laygen.boundary_pin_from_rect(rdone0, rg_m3m4, \"DONE\", laygen.layers['pin'][4], size=4, direction='right')\n laygen.boundary_pin_from_rect(rclkob0, rg_m3m4, \"CLKOB\", laygen.layers['pin'][4], size=6, direction='right')\n laygen.boundary_pin_from_rect(rclko0, rg_m3m4, \"CLKO\", laygen.layers['pin'][4], size=6, direction='right')\n laygen.boundary_pin_from_rect(rsel0, rg_m3m4, \"SEL<0>\", laygen.layers['pin'][4], size=6, direction='right')\n laygen.boundary_pin_from_rect(rsel1, rg_m3m4, \"SEL<1>\", laygen.layers['pin'][4], size=6, direction='right')\n laygen.boundary_pin_from_rect(rsel2, rg_m3m4, \"SEL<2>\", laygen.layers['pin'][4], size=6, direction='right')\n\n # power route (horizontal)\n #create_power_pin_from_inst(laygen, layer=laygen.layers['pin'][2], gridname=rg_m1m2, inst_left=itapl, inst_right=itapr)\n laygen.route(None, laygen.layers['metal'][2], xy0=np.array([0, 0]), xy1=np.array([0, 0]), gridname0=rg_m1m2,\n refinstname0=itapl.name, refpinname0='VDD', refinstname1=itapr.name, refpinname1='VDD')\n laygen.route(None, laygen.layers['metal'][2], xy0=np.array([0, 0]), xy1=np.array([0, 0]), gridname0=rg_m1m2,\n refinstname0=itapl.name, refpinname0='VSS', refinstname1=itapr.name, refpinname1='VSS')\n\n # power pin\n pwr_dim=laygen.get_xy(obj =itapl.template, gridname=rg_m2m3)\n rvdd = []\n rvss = []\n rp1='VDD'\n for i in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i, 0]), xy1=np.array([2*i, 0]), gridname0=rg_m2m3,\n refinstname0=itapl.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl.name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+1, 0]), xy1=np.array([2*i+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl.name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2+1, 0]), xy1=np.array([2*i+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr.name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2, 0]), xy1=np.array([2*i+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr.name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n for j in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j, 0]), xy1=np.array([2*j, 0]), gridname0=rg_m2m3,\n refinstname0=itapl.name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapl.name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+1, 0]), xy1=np.array([2*j+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl.name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapl.name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2+1, 0]), xy1=np.array([2*j+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr.name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapr.name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2, 0]), xy1=np.array([2*j+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr.name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapr.name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n\n\nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'adc_sar_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n #display\n #laygen.display()\n #laygen.templates.display()\n #laygen.save_template(filename=workinglib+'_templates.yaml', libname=workinglib)\n\n mycell_list = []\n num_bits=9\n m=2\n fo=2\n #load from preset\n load_from_file=True\n yamlfile_spec=\"adc_sar_spec.yaml\"\n yamlfile_size=\"adc_sar_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n num_bits=specdict['n_bit']\n m=sizedict['sarclkgen']['m']\n fo=sizedict['sarclkgen']['fo']\n ndelay=sizedict['sarclkgen']['ndelay']\n fast=sizedict['sarclkgen']['fast']\n mux_fast=sizedict['sarclkgen']['mux_fast']\n m_space_left_4x=sizedict['sarabe_m_space_left_4x']\n #generation (2 step)\n cellname='sarclkgen_static'\n print(cellname+\" generating\")\n mycell_list.append(cellname)\n #1. generate without spacing\n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n generate_sarclkgen_static(laygen, objectname_pfix='CKG0', templib_logic=logictemplib, placement_grid=pg,\n routing_grid_m3m4=rg_m3m4,\n m=m, fo=fo, m_space_left_4x=m_space_left_4x, m_space_4x=0, m_space_2x=0, m_space_1x=0, fast=fast,\n origin=np.array([0, 0]),mux_fast=mux_fast)\n laygen.add_template_from_cell()\n #2. calculate spacing param and regenerate\n x0 = laygen.templates.get_template('sarafe_nsw', libname=workinglib).xy[1][0] \\\n - laygen.templates.get_template(cellname, libname=workinglib).xy[1][0] \\\n - laygen.templates.get_template('nmos4_fast_left').xy[1][0] * 2\n m_space = int(round(x0 / laygen.templates.get_template('space_1x', libname=logictemplib).xy[1][0]))\n m_space_4x=int(m_space/4)\n m_space_2x=int((m_space-m_space_4x*4)/2)\n m_space_1x=int(m_space-m_space_4x*4-m_space_2x*2)\n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n generate_sarclkgen_static(laygen, objectname_pfix='CKG0', templib_logic=logictemplib, placement_grid=pg,\n routing_grid_m3m4=rg_m3m4,\n m=m, fo=fo, m_space_left_4x=m_space_left_4x, \n m_space_4x=m_space_4x, m_space_2x=m_space_2x, m_space_1x=m_space_1x, fast=fast, origin=np.array([0, 0]),\n mux_fast=mux_fast)\n laygen.add_template_from_cell()\n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n", "#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"SER library\n\"\"\"\nimport laygo\nimport numpy as np\n#from logic_layout_generator import *\nfrom math import log\nimport yaml\nimport os\n#import logging;logging.basicConfig(level=logging.DEBUG)\n\ndef generate_boundary(laygen, objectname_pfix, placement_grid,\n devname_bottom, devname_top, devname_left, devname_right,\n shape_bottom=None, shape_top=None, shape_left=None, shape_right=None,\n transform_bottom=None, transform_top=None, transform_left=None, transform_right=None,\n origin=np.array([0, 0])):\n #generate a boundary structure to resolve boundary design rules\n pg = placement_grid\n #parameters\n if shape_bottom == None:\n shape_bottom = [np.array([1, 1]) for d in devname_bottom]\n if shape_top == None:\n shape_top = [np.array([1, 1]) for d in devname_top]\n if shape_left == None:\n shape_left = [np.array([1, 1]) for d in devname_left]\n if shape_right == None:\n shape_right = [np.array([1, 1]) for d in devname_right]\n if transform_bottom == None:\n transform_bottom = ['R0' for d in devname_bottom]\n if transform_top == None:\n transform_top = ['R0' for d in devname_top]\n if transform_left == None:\n transform_left = ['R0' for d in devname_left]\n if transform_right == None:\n transform_right = ['R0' for d in devname_right]\n\n #bottom\n dev_bottom=[]\n dev_bottom.append(laygen.place(\"I\" + objectname_pfix + 'BNDBTM0', devname_bottom[0], pg, xy=origin,\n shape=shape_bottom[0], transform=transform_bottom[0]))\n for i, d in enumerate(devname_bottom[1:]):\n dev_bottom.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDBTM'+str(i+1), templatename = d, gridname = pg, refinstname = dev_bottom[-1].name,\n shape=shape_bottom[i+1], transform=transform_bottom[i+1]))\n dev_left=[]\n dev_left.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDLFT0', templatename = devname_left[0], gridname = pg, refinstname = dev_bottom[0].name, direction='top',\n shape=shape_left[0], transform=transform_left[0]))\n for i, d in enumerate(devname_left[1:]):\n dev_left.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDLFT'+str(i+1), templatename = d, gridname = pg, refinstname = dev_left[-1].name, direction='top',\n shape=shape_left[i+1], transform=transform_left[i+1]))\n dev_right=[]\n dev_right.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDRHT0', templatename = devname_right[0], gridname = pg, refinstname = dev_bottom[-1].name, direction='top',\n shape=shape_right[0], transform=transform_right[0]))\n for i, d in enumerate(devname_right[1:]):\n dev_right.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDRHT'+str(i+1), templatename = d, gridname = pg, refinstname = dev_right[-1].name, direction='top',\n shape=shape_right[i+1], transform=transform_right[i+1]))\n dev_top=[]\n dev_top.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDTOP0', templatename = devname_top[0], gridname = pg, refinstname = dev_left[-1].name, direction='top',\n shape=shape_top[0], transform=transform_top[0]))\n for i, d in enumerate(devname_top[1:]):\n dev_top.append(laygen.relplace(name = \"I\" + objectname_pfix + 'BNDTOP'+str(i+1), templatename = d, gridname = pg, refinstname = dev_top[-1].name,\n shape=shape_top[i+1], transform=transform_top[i+1]))\n dev_right=[]\n return [dev_bottom, dev_top, dev_left, dev_right]\n\ndef generate_serializer(laygen, objectname_pfix, templib_logic, placement_grid, routing_grid_m2m3,\n routing_grid_m4m5, m_dff=1, m_cbuf1=2, m_cbuf2=8, m_pbuf1=2, m_pbuf2=8, m_mux=2, m_out=2, num_ser=8, m_ser=1, origin=np.array([0, 0])):\n pg = placement_grid\n\n rg_m2m3 = routing_grid_m2m3\n rg_m4m5 = routing_grid_m4m5\n\n tap_name='tap'\n ff_name = 'dff_'+str(int(m_dff))+'x'\n ff_rst_name = 'dff_strsth_'+str(int(m_dff))+'x'\n latch_name = 'latch_2ck_1x'\n inv1_name = 'inv_'+str(int(m_cbuf1))+'x'\n inv2_name = 'inv_'+str(int(m_cbuf2))+'x'\n tinv_name = 'tinv_'+str(int(m_mux))+'x'\n outinv_name = 'inv_'+str(int(m_out))+'x'\n sub_ser = int(num_ser/2)\n\n #Calculate layout size\n ff_size=laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)\n ff_rst_size=laygen.get_xy(obj=laygen.get_template(name = ff_rst_name, libname = templib_logic), gridname = pg)\n latch_size=laygen.get_xy(obj=laygen.get_template(name = latch_name, libname = templib_logic), gridname = pg)\n inv1_size=laygen.get_xy(obj=laygen.get_template(name = inv1_name, libname = templib_logic), gridname = pg)\n inv2_size=laygen.get_xy(obj=laygen.get_template(name = inv2_name, libname = templib_logic), gridname = pg)\n tinv_size=laygen.get_xy(obj=laygen.get_template(name = tinv_name, libname = templib_logic), gridname = pg)\n outinv_size=laygen.get_xy(obj=laygen.get_template(name = outinv_name, libname = templib_logic), gridname = pg)\n tap_size=laygen.get_xy(obj=laygen.get_template(name = tap_name, libname = templib_logic), gridname = pg)\n x0=ff_size[0]+ff_rst_size[0]+inv1_size[0]+2*inv2_size[0]+tinv_size[0]+2*tap_size[0]\n num_row=int(sub_ser)+1\n\n #boundaries\n m_bnd = int(x0 / laygen.get_xy(obj=laygen.get_template(name = 'boundary_bottom'), gridname = pg)[0])\n devname_bnd_left = []\n devname_bnd_right = []\n transform_bnd_left = []\n transform_bnd_right = []\n for i in range(num_row):\n if i%2==0:\n devname_bnd_left += ['nmos4_fast_left', 'pmos4_fast_left']\n devname_bnd_right += ['nmos4_fast_right', 'pmos4_fast_right']\n transform_bnd_left += ['R0', 'MX']\n transform_bnd_right += ['R0', 'MX']\n else:\n devname_bnd_left += ['pmos4_fast_left', 'nmos4_fast_left']\n devname_bnd_right += ['pmos4_fast_right', 'nmos4_fast_right']\n transform_bnd_left += ['R0', 'MX']\n transform_bnd_right += ['R0', 'MX']\n [bnd_bottom, bnd_top, bnd_left, bnd_right] = generate_boundary(laygen, objectname_pfix='BND0',\n placement_grid=pg,\n devname_bottom=['boundary_bottomleft',\n 'boundary_bottom',\n 'boundary_bottomright'],\n shape_bottom=[np.array([1, 1]), np.array([m_bnd, 1]),\n np.array([1, 1])],\n devname_top=['boundary_topleft', 'boundary_top',\n 'boundary_topright'],\n shape_top=[np.array([1, 1]), np.array([m_bnd, 1]),\n np.array([1, 1])],\n devname_left=devname_bnd_left,\n transform_left=transform_bnd_left,\n devname_right=devname_bnd_right,\n transform_right=transform_bnd_right,\n origin=np.array([0, 0]))\n #Calculate origins for placement\n tap_origin = origin + laygen.get_xy(obj = bnd_bottom[0], gridname = pg) \\\n + laygen.get_xy(obj = bnd_bottom[0].template, gridname = pg)\n array_origin = origin + laygen.get_xy(obj = bnd_bottom[0], gridname = pg) \\\n + laygen.get_xy(obj = bnd_bottom[0].template, gridname = pg) \\\n + np.array([laygen.get_xy(obj=laygen.get_template(name = tap_name, libname = templib_logic), gridname = pg)[0], 0])\n tapr_origin = tap_origin + m_bnd*np.array([laygen.get_xy(obj=laygen.get_template(name = 'boundary_bottom'), gridname = pg)[0], 0]) \\\n - np.array([laygen.get_xy(obj=laygen.get_template(name = tap_name, libname = templib_logic), gridname = pg)[0], 0])\n FF0_origin = array_origin + np.array([0, laygen.get_xy(obj=laygen.get_template(name = 'inv_1x', libname = templib_logic), gridname = pg)[1]]) + \\\n np.array([0, laygen.get_xy(obj=laygen.get_template(name = ff_name, libname = templib_logic), gridname = pg)[1]])\n # placement\n iffdiv=[]\n ipbuf1=[]\n ipbuf2=[]\n ipbuf3=[]\n iffin=[]\n itinv=[]\n isp1x=[]\n itapl=[]\n itapr=[]\n tf='R0'\n for i in range(num_row):\n if i%2==0: tf='R0'\n else: tf='MX'\n if i==0: #Reference low \n itapl.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPL0', templatename = tap_name,\n gridname = pg, xy=tap_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n itapr.append(laygen.place(name = \"I\" + objectname_pfix + 'TAPR0', templatename = tap_name,\n gridname = pg, xy=tapr_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n iffdiv.append(laygen.place(name = \"I\" + objectname_pfix + 'FFDIV1', templatename = ff_rst_name,\n gridname = pg, xy=array_origin, transform=tf, shape=np.array([1,1]), template_libname = templib_logic))\n ipbuf1.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P1BUF1', templatename = inv1_name,\n gridname = pg, refinstname = iffdiv[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n ipbuf2.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P1BUF2', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf1[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n ipbuf3.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P1BUF3', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf2[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n iffin.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFIN1', templatename = ff_name,\n gridname = pg, refinstname = ipbuf3[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n itinv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TINV1', templatename = tinv_name,\n gridname = pg, refinstname = iffin[-1].name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic))\n else:\n itapl.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPL'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapl[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n itapr.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TAPR'+str(i), templatename = tap_name,\n gridname = pg, refinstname = itapr[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n if i==num_row-1: #Top row for last bit latch, input clock buffer, and outinv\n iclkbuf1=laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF1', templatename = inv1_name,\n gridname = pg, refinstname = iffdiv[-1].name, transform=tf, shape=np.array([1,1]),\n xy=np.array([(-ff_rst_size[0]+inv1_size[0])/2,0]), direction = 'top', template_libname=templib_logic)\n iclkbuf2=laygen.relplace(name = \"I\" + objectname_pfix + 'CLKBUF2', templatename = inv2_name,\n gridname = pg, refinstname = iclkbuf1.name, transform=tf, shape=np.array([1,1]),\n template_libname=templib_logic)\n ilatch=laygen.relplace(name = \"I\" + objectname_pfix + 'LATCH0', templatename = latch_name,\n gridname = pg, refinstname = iffin[-1].name, transform=tf, shape=np.array([1,1]),\n xy=np.array([(ff_size[0]-latch_size[0])/2,0]), direction = 'top', template_libname=templib_logic)\n ioutinv=laygen.relplace(name = \"I\" + objectname_pfix + 'OUTINV', templatename = inv1_name,\n gridname = pg, refinstname = itinv[-1].name, transform=tf, shape=np.array([1,1]),\n xy=np.array([(tinv_size[0]-outinv_size[0])/2,0]), direction = 'top', template_libname=templib_logic)\n elif i==num_row-2: #Row for the last bit (p0 row)\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV0', templatename = ff_rst_name,\n gridname = pg, refinstname = iffdiv[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf1.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P0BUF1', templatename = inv1_name,\n gridname = pg, refinstname = ipbuf1[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf2.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P0BUF2', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf2[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf3.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P0BUF3', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf3[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n iffin.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFIN0', templatename = ff_name,\n gridname = pg, refinstname = iffin[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n itinv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TINV0', templatename = tinv_name,\n gridname = pg, refinstname = itinv[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n else:\n iffdiv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFDIV'+str(i+1), templatename = ff_rst_name,\n gridname = pg, refinstname = iffdiv[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf1.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P'+str(i+1)+'BUF1', templatename = inv1_name,\n gridname = pg, refinstname = ipbuf1[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf2.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P'+str(i+1)+'BUF2', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf2[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n ipbuf3.append(laygen.relplace(name = \"I\" + objectname_pfix + 'P'+str(i+1)+'BUF3', templatename = inv2_name,\n gridname = pg, refinstname = ipbuf3[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n iffin.append(laygen.relplace(name = \"I\" + objectname_pfix + 'FFIN'+str(i+1), templatename = ff_name,\n gridname = pg, refinstname = iffin[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n itinv.append(laygen.relplace(name = \"I\" + objectname_pfix + 'TINV'+str(i+1), templatename = tinv_name,\n gridname = pg, refinstname = itinv[-1].name, transform=tf, shape=np.array([1,1]),\n direction = 'top', template_libname=templib_logic))\n #Space placement at the last row\n space_name = 'space_1x'\n space4x_name = 'space_4x'\n space_width = laygen.get_xy(obj=laygen.get_template(name = space_name, libname = templib_logic), gridname = pg)[0]\n space4_width = laygen.get_xy(obj=laygen.get_template(name = space4x_name, libname = templib_logic), gridname = pg)[0]\n blank1_width = x0 - (2*tap_size + inv1_size + inv2_size + tinv_size + latch_size)[0]\n blank2_width = (tinv_size - inv1_size)[0]\n m_space4 = int(blank1_width / space4_width)\n m_space1 = int((blank1_width-m_space4*space4_width)/space_width)\n #m_space1 = int(blank1_width / space_width)\n m_space2 = int(blank2_width / space_width)\n if num_row%2==0: tf_s='MX'\n else: tf_s='R0'\n ispace4=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE4', templatename = space4x_name,\n gridname = pg, refinstname = iclkbuf2.name, transform=tf_s, shape=np.array([m_space4-1,1]),\n template_libname=templib_logic)\n ispace1=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE1', templatename = space_name,\n gridname = pg, refinstname = ispace4.name, transform=tf_s, shape=np.array([m_space1+4,1]),\n template_libname=templib_logic)\n #ispace1=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE1', templatename = space_name,\n #gridname = pg, refinstname = iclkbuf2.name, transform=tf_s, shape=np.array([m_space1,1]),\n #template_libname=templib_logic)\n ispace2=laygen.relplace(name = \"I\" + objectname_pfix + 'SPACE2', templatename = space_name,\n gridname = pg, refinstname = ilatch.name, transform=tf_s, shape=np.array([m_space2,1]),\n template_libname=templib_logic)\n\n #Internal Pins\n ffin_in_xy=[]\n ffin_in_xy45=[]\n ffin_out_xy=[]\n ffin_vss_xy=[]\n ffin_clk_xy=[]\n ffdiv_in_xy=[]\n ffdiv_out_xy45=[]\n ffdiv_out_xy=[]\n ffdiv_vss_xy=[]\n ffdiv_clk_xy=[]\n ffdiv_rst_xy=[]\n ffdiv_st_xy=[]\n ffdiv_st_xy45=[]\n pbuf1_in_xy=[]\n pbuf1_out_xy=[]\n pbuf2_in_xy=[]\n pbuf2_out_xy=[]\n pbuf3_in_xy=[]\n pbuf3_out_xy=[]\n tinv_in_xy=[]\n tinv_out_xy=[]\n tinv_en_xy=[]\n tinv_enb_xy=[]\n for i in range(sub_ser):\n ffin_in_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'I', rg_m3m4))\n ffin_out_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'O', rg_m3m4))\n ffin_vss_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'VSS', rg_m3m4))\n ffin_clk_xy.append(laygen.get_inst_pin_xy(iffin[i].name, 'CLK', rg_m3m4))\n ffdiv_in_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'I', rg_m3m4))\n ffdiv_out_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'O', rg_m3m4))\n ffdiv_vss_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'VSS', rg_m3m4))\n ffdiv_clk_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'CLK', rg_m3m4))\n ffdiv_rst_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'RST', rg_m3m4))\n ffdiv_st_xy.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'ST', rg_m3m4))\n ffdiv_st_xy45.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'ST', rg_m4m5))\n ffin_in_xy45.append(laygen.get_inst_pin_xy(iffin[i].name, 'I', rg_m4m5))\n ffdiv_out_xy45.append(laygen.get_inst_pin_xy(iffdiv[i].name, 'O', rg_m4m5))\n pbuf1_in_xy.append(laygen.get_inst_pin_xy(ipbuf1[i].name, 'I', rg_m3m4))\n pbuf1_out_xy.append(laygen.get_inst_pin_xy(ipbuf1[i].name, 'O', rg_m3m4))\n pbuf2_in_xy.append(laygen.get_inst_pin_xy(ipbuf2[i].name, 'I', rg_m3m4))\n pbuf2_out_xy.append(laygen.get_inst_pin_xy(ipbuf2[i].name, 'O', rg_m3m4))\n pbuf3_in_xy.append(laygen.get_inst_pin_xy(ipbuf3[i].name, 'I', rg_m3m4))\n pbuf3_out_xy.append(laygen.get_inst_pin_xy(ipbuf3[i].name, 'O', rg_m3m4))\n tinv_in_xy.append(laygen.get_inst_pin_xy(itinv[i].name, 'I', rg_m3m4))\n tinv_out_xy.append(laygen.get_inst_pin_xy(itinv[i].name, 'O', rg_m3m4))\n tinv_en_xy.append(laygen.get_inst_pin_xy(itinv[i].name, 'EN', rg_m3m4))\n tinv_enb_xy.append(laygen.get_inst_pin_xy(itinv[i].name, 'ENB', rg_m3m4))\n\n # Route\n y_ref_m3m4=[]\n for i in range(sub_ser):\n y_ref_m3m4.append(laygen.get_xy(obj = bnd_bottom[0].template, gridname = rg_m3m4)[1] \\\n + 2 * (i+1) * laygen.get_xy(obj = bnd_left[0].template, gridname = rg_m3m4)[1])\n if iffdiv[i].transform=='MX': offset=5\n if iffdiv[i].transform=='R0': offset=7\n if iffin[i].transform=='MX': offset_p=-5\n if iffin[i].transform=='R0': offset_p=5\n if not i==sub_ser-1:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #DIVFF \n ffdiv_in_xy[i][0], ffdiv_out_xy[i+1][0], y_ref_m3m4[i]+1, rg_m3m4)\n rclk=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_clk_xy[i][0], xy1=ffdiv_clk_xy[i+1][0], gridname0=rg_m3m4) #CLK\n rp0buf=laygen.route(None, laygen.layers['metal'][3], xy0=ffin_clk_xy[i][0], xy1=ffin_clk_xy[i+1][0], gridname0=rg_m3m4) #P0BUF\n [rh0, rv0] = laygen.route_hv(laygen.layers['metal'][2], laygen.layers['metal'][3], #ST to VSS\n laygen.get_inst_pin_xy(iffdiv[i].name, 'VSS', rg_m2m3)[0], laygen.get_inst_pin_xy(iffdiv[i].name, 'ST', rg_m2m3)[0], rg_m2m3)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #FFin to tinv\n ffin_out_xy[i][0], tinv_in_xy[i][1], ffin_vss_xy[i][0][1] + 5 * (-1) ** (i%2), rg_m3m4)\n if not i==sub_ser-2: #RST routing\n rrst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_rst_xy[i][0], xy1=ffdiv_rst_xy[i+1][0], gridname0=rg_m3m4)\n else: #RST-ST crossing\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n ffdiv_rst_xy[i][0], ffdiv_st_xy45[i+1][0]-np.array([4,0]), ffdiv_rst_xy[i][0][1], rg_m3m4,\n layerv1=laygen.layers['metal'][5], gridname1=rg_m4m5)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n ffdiv_st_xy[i+1][0], ffdiv_st_xy45[i+1][0]-np.array([4,1]), ffdiv_st_xy[i+1][0][1], rg_m3m4,\n layerv1=laygen.layers['metal'][5], gridname1=rg_m4m5)\n else: #p0 row\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #DIV feedback path\n ffdiv_in_xy[i][0], ffdiv_out_xy45[0][0]+np.array([4,0]), y_ref_m3m4[i]+1, rg_m3m4,\n layerv1=laygen.layers['metal'][5], gridname1=rg_m4m5)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #M3-to-M5\n ffdiv_out_xy[0][0], ffdiv_out_xy45[0][0]+np.array([4,1]), ffdiv_vss_xy[0][0][1] + 5 - 3, rg_m3m4, \n layerv1=laygen.layers['metal'][5], gridname1=rg_m4m5)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #Clock\n ffdiv_clk_xy[i][0], laygen.get_inst_pin_xy(iclkbuf2.name, 'O', rg_m3m4)[0], y_ref_m3m4[i]+1, rg_m3m4)\n [rh0, rv0] = laygen.route_hv(laygen.layers['metal'][2], laygen.layers['metal'][3], #RST\n laygen.get_inst_pin_xy(iffdiv[i].name, 'VSS', rg_m2m3)[0], laygen.get_inst_pin_xy(iffdiv[i].name, 'RST', rg_m2m3)[0], rg_m2m3)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #p0buf to FFin\n pbuf2_out_xy[i][0], ffin_clk_xy[i][0], pbuf2_out_xy[i][0][1]+offset_p, rg_m3m4)\n #Latch connections\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #Input\n laygen.get_inst_pin_xy(ilatch.name, 'I', rg_m3m4)[0], np.array([ffin_out_xy[0][0][0]+2, ffin_vss_xy[i][0][1]+offset_p]),\n y_ref_m3m4[i], rg_m3m4)\n laygen.route(None, laygen.layers['metal'][4], xy0=np.array([ffin_out_xy[0][0][0], ffin_vss_xy[i][0][1]+offset_p]), \n xy1=np.array([ffin_out_xy[0][0][0]+2, ffin_vss_xy[i][0][1]+offset_p]), \n gridname0=rg_m3m4, via0=[0,0], via1=[0,0]) #for resolving M3 spacing\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #p0buf\n pbuf2_out_xy[i][0], laygen.get_inst_pin_xy(ilatch.name, 'CLKB', rg_m3m4)[0] - np.array([2, 0]), ffin_out_xy[i][0][1] + offset_p, rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #p0buf\n laygen.get_inst_pin_xy(ilatch.name, 'CLKB', rg_m3m4)[0], laygen.get_inst_pin_xy(ilatch.name, 'CLKB', rg_m3m4)[0] - np.array([2, 0]),\n laygen.get_inst_pin_xy(ilatch.name, 'CLKB', rg_m3m4)[0][1], rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #p0bufb\n pbuf3_out_xy[i][0], laygen.get_inst_pin_xy(ilatch.name, 'CLK', rg_m3m4)[0] + np.array([2, 0]),\n pbuf3_out_xy[i][0][1] + offset_p - (-1) ** (i%2), rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #p0bufb\n laygen.get_inst_pin_xy(ilatch.name, 'CLK', rg_m3m4)[0], laygen.get_inst_pin_xy(ilatch.name, 'CLK', rg_m3m4)[0] + np.array([2, 0]),\n laygen.get_inst_pin_xy(ilatch.name, 'CLK', rg_m3m4)[0][1], rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #tinv\n laygen.get_inst_pin_xy(ilatch.name, 'O', rg_m3m4)[0], tinv_in_xy[i][0],\n laygen.get_inst_pin_xy(ilatch.name, 'O', rg_m3m4)[0][1], rg_m3m4)\n #Multiphase buffer\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n ffdiv_out_xy[i][0]+np.array([0,0]), pbuf1_in_xy[i][0], ffdiv_vss_xy[i][0][1] + 5 * (-1) ** (i%2), rg_m3m4, extendr=2)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n pbuf1_out_xy[i][1], pbuf2_in_xy[i][0], pbuf1_out_xy[i][1][1], rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n pbuf2_out_xy[i][1], pbuf3_in_xy[i][0], pbuf2_out_xy[i][1][1], rg_m3m4)\n #Multiphase to TINV\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n pbuf2_out_xy[i][0], tinv_en_xy[i][0], pbuf2_out_xy[i][0][1]+offset_p, rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], \n pbuf3_out_xy[i][0], tinv_enb_xy[i][0], pbuf3_out_xy[i][0][1]+offset_p-(-1)**(i%2), rg_m3m4)\n #MUX\n if not i==sub_ser-1:\n routb=laygen.route(None, laygen.layers['metal'][3], xy0=tinv_out_xy[i][0], xy1=tinv_out_xy[i+1][0], gridname0=rg_m3m4) #OUTB\n else:\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #OUTINV\n tinv_out_xy[i][0], laygen.get_inst_pin_xy(ioutinv.name, 'I', rg_m3m4)[1] - np.array([2, 0]),\n tinv_out_xy[i][0][1], rg_m3m4)\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4], #OUTINV\n laygen.get_inst_pin_xy(ioutinv.name, 'I', rg_m3m4)[1], laygen.get_inst_pin_xy(ioutinv.name, 'I', rg_m3m4)[1] - np.array([2, 0]),\n laygen.get_inst_pin_xy(ioutinv.name, 'I', rg_m3m4)[1][1], rg_m3m4, extendr=2)\n #CLKIN buffer\n [rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],\n laygen.get_inst_pin_xy(iclkbuf1.name, 'O', rg_m3m4)[0], laygen.get_inst_pin_xy(iclkbuf2.name, 'I', rg_m3m4)[0],\n laygen.get_inst_pin_xy(iclkbuf1.name, 'O', rg_m3m4)[0][1], rg_m3m4)\n\n #Pin\n clkin_xy=laygen.get_inst_pin_xy(iclkbuf1.name, 'I', rg_m3m4)[1]\n [rv0, rclkin] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n clkin_xy, np.array([0,clkin_xy[1]]), rg_m3m4)\n laygen.boundary_pin_from_rect(rclkin, rg_m3m4, \"clk_in\", laygen.layers['pin'][4], size=4, direction='left')\n for i in range(sub_ser):\n if iffin[i].transform=='MX': offset_din=4\n if iffin[i].transform=='R0': offset_din=6\n din_xy34=laygen.get_inst_pin_xy(iffin[i].name, 'I', rg_m3m4)\n [rv0, rh0] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n din_xy34[1], np.array([0,y_ref_m3m4[i]]), rg_m3m4)\n if not i==sub_ser-1:\n laygen.boundary_pin_from_rect(rh0, rg_m3m4, \"in<\" + str(i + 1) + \">\", laygen.layers['pin'][4],\n size=4, direction='left')\n else:\n laygen.boundary_pin_from_rect(rh0, rg_m3m4, \"in<0>\", laygen.layers['pin'][4], size=4,\n direction='left')\n datao_xy=laygen.get_inst_pin_xy(ioutinv.name, 'O', rg_m3m4)\n laygen.pin(name='out', layer=laygen.layers['pin'][3], xy=datao_xy, gridname=rg_m3m4)\n #[rv0, rdatao] = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], \n # datao_xy[0], datao_xy+np.array([5,0]), rg_m3m4)\n #laygen.boundary_pin_from_rect(rdatao, rg_m3m4, \"out\", laygen.layers['pin'][4], size=4, direction='right')\n laygen.pin(name='p1buf', layer=laygen.layers['pin'][3], xy=pbuf2_out_xy[0], gridname=rg_m3m4)\n rrst=laygen.route(None, laygen.layers['metal'][3], xy0=ffdiv_rst_xy[0][0], xy1=np.array([ffdiv_rst_xy[0][0][0],0]), gridname0=rg_m3m4)\n laygen.boundary_pin_from_rect(rrst, rg_m3m4, \"RST\", laygen.layers['pin'][3], size=4, direction='bottom')\n\n # power pin\n pwr_dim=laygen.get_xy(obj =itapl[-1].template, gridname=rg_m2m3)\n rvdd = []\n rvss = []\n if num_row%2==0: rp1='VSS'\n else: rp1='VDD'\n print(int(pwr_dim[0]/2))\n for i in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i, 0]), xy1=np.array([2*i, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+1, 0]), xy1=np.array([2*i+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-2), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2+1, 0]), xy1=np.array([2*i+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2, 0]), xy1=np.array([2*i+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[0].name, refpinname0='VSS', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[-1].name, refpinname1=rp1, refinstindex1=np.array([0, 0])))\n laygen.pin(name = 'VDD'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvdd[-1], gridname=rg_m2m3, netname='VDD')\n laygen.pin(name = 'VSS'+str(2*i-1), layer = laygen.layers['pin'][3], refobj = rvss[-1], gridname=rg_m2m3, netname='VSS')\n \n for i in range(num_row):\n for j in range(0, int(pwr_dim[0]/2)):\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j, 0]), xy1=np.array([2*j, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapl[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+1, 0]), xy1=np.array([2*j+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapl[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapl[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n rvdd.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2+1, 0]), xy1=np.array([2*j+2+1, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]), via0=[[0, 0]],\n refinstname1=itapr[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0])))\n rvss.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*j+2, 0]), xy1=np.array([2*j+2, 0]), gridname0=rg_m2m3,\n refinstname0=itapr[i].name, refpinname0='VDD', refinstindex0=np.array([0, 0]),\n refinstname1=itapr[i].name, refpinname1='VSS', refinstindex1=np.array([0, 0]), via1=[[0, 0]]))\n\nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'serdes_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n\n #display\n #laygen.display()\n #laygen.templates.display()\n #laygen.save_template(filename=workinglib+'_templates.yaml', libname=workinglib)\n\n mycell_list = []\n \n #load from preset\n load_from_file=True\n yamlfile_spec=\"serdes_spec.yaml\"\n yamlfile_size=\"serdes_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n cell_name='ser_'+str(int(specdict['num_ser']/2))+'to1'\n num_ser=specdict['num_ser']\n m_dff=sizedict['m_dff']\n m_cbuf1=sizedict['m_cbuf1']\n m_cbuf2=sizedict['m_cbuf2']\n m_pbuf1=sizedict['m_pbuf1']\n m_pbuf2=sizedict['m_pbuf2']\n m_mux=sizedict['m_mux']\n m_out=sizedict['m_out']\n m_ser=sizedict['m_ser']\n\n print(cell_name+\" generating\")\n mycell_list.append(cell_name)\n laygen.add_cell(cell_name)\n laygen.sel_cell(cell_name)\n generate_serializer(laygen, objectname_pfix='SER', templib_logic=logictemplib, \n placement_grid=pg, routing_grid_m2m3=rg_m2m3, routing_grid_m4m5=rg_m4m5, num_ser=num_ser,\n m_dff=m_dff, m_cbuf1=m_cbuf1, m_cbuf2=m_cbuf2, m_pbuf1=m_pbuf1, m_pbuf2=m_pbuf2, m_mux=m_mux, m_out=m_out, m_ser=m_ser, origin=np.array([0, 0]))\n laygen.add_template_from_cell()\n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n", "#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"ADC library\n\"\"\"\nimport laygo\nimport numpy as np\nimport os\nimport yaml\n#import logging;logging.basicConfig(level=logging.DEBUG)\nfrom adc_sar_salatch_pmos_layout_generator import *\n\nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'adc_sar_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_basic_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m2m3_thick = 'route_M2_M3_thick_basic'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n #display\n #laygen.display()\n #laygen.templates.display()\n #laygen.save_template(filename=workinglib+'_templates.yaml', libname=workinglib)\n\n mycell_list = []\n #salatch generation (wboundary)\n #cellname = 'salatch'\n cellname = 'salatch_pmos_standalone'\n print(cellname+\" generating\")\n mycell_list.append(cellname)\n m_sa=8\n m_rst_sa=8\n m_rgnn_sa=2\n m_buf_sa=8\n #load from preset\n load_from_file=True\n yamlfile_spec=\"adc_sar_spec.yaml\"\n yamlfile_size=\"adc_sar_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n m_sa=sizedict['salatch_m']\n m_rst_sa=sizedict['salatch_m_rst']\n m_rgnn_sa=sizedict['salatch_m_rgnn']\n m_buf_sa=sizedict['salatch_m_buf']\n m_in=int(m_sa/2) #4\n m_clkh=max(1, m_in-1) #4\n m_rstn=int(m_rst_sa/2) #1\n m_buf=int(m_buf_sa/2)\n m_rgnn=int(m_rgnn_sa/2) \n m_ofst=1\n\n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n\n sa_origin=np.array([0, 0])\n\n #salatch body\n # 1. generate without spacing\n generate_salatch_pmos(laygen, objectname_pfix='SA0',\n placement_grid=pg, routing_grid_m1m2=rg_m1m2, routing_grid_m1m2_thick=rg_m1m2_thick,\n routing_grid_m2m3=rg_m2m3, routing_grid_m2m3_thick=rg_m2m3_thick, \n routing_grid_m3m4=rg_m3m4, routing_grid_m4m5=rg_m4m5,\n devname_ptap_boundary='ptap_fast_boundary', devname_ptap_body='ptap_fast_center_nf1',\n devname_nmos_boundary='nmos4_fast_boundary', devname_nmos_body='nmos4_fast_center_nf2',\n devname_nmos_dmy='nmos4_fast_dmy_nf2',\n devname_pmos_boundary='pmos4_fast_boundary', devname_pmos_body='pmos4_fast_center_nf2',\n devname_pmos_dmy='pmos4_fast_dmy_nf2',\n devname_ntap_boundary='ntap_fast_boundary', devname_ntap_body='ntap_fast_center_nf1',\n m_in=m_in, m_ofst=m_ofst, m_clkh=m_clkh, m_rgnn=m_rgnn, m_rstn=m_rstn, m_buf=m_buf,\n num_vert_pwr=2, origin=sa_origin)\n laygen.add_template_from_cell()\n # 2. calculate spacing param and regenerate\n x0 = 2*laygen.templates.get_template('capdac', libname=workinglib).xy[1][0] \\\n - laygen.templates.get_template(cellname, libname=workinglib).xy[1][0]\n m_space = int(round(x0 / 2 / laygen.templates.get_template('space_1x', libname=logictemplib).xy[1][0]))\n m_space_4x = int(m_space / 4)\n m_space_2x = int((m_space - m_space_4x * 4) / 2)\n m_space_1x = int(m_space - m_space_4x * 4 - m_space_2x * 2)\n #print(\"debug\", x0, laygen.templates.get_template('capdrv_array_7b', libname=workinglib).xy[1][0] \\\n # , laygen.templates.get_template(cellname, libname=workinglib).xy[1][0] \\\n # , laygen.templates.get_template('space_1x', libname=logictemplib).xy[1][0], m_space, m_space_4x, m_space_2x, m_space_1x)\n \n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n generate_salatch_pmos(laygen, objectname_pfix='SA0',\n placement_grid=pg, routing_grid_m1m2=rg_m1m2, routing_grid_m1m2_thick=rg_m1m2_thick,\n routing_grid_m2m3=rg_m2m3, routing_grid_m2m3_thick=rg_m2m3_thick, \n routing_grid_m3m4=rg_m3m4, routing_grid_m4m5=rg_m4m5,\n devname_ptap_boundary='ptap_fast_boundary', devname_ptap_body='ptap_fast_center_nf1',\n devname_nmos_boundary='nmos4_fast_boundary', devname_nmos_body='nmos4_fast_center_nf2',\n devname_nmos_dmy='nmos4_fast_dmy_nf2',\n devname_pmos_boundary='pmos4_fast_boundary', devname_pmos_body='pmos4_fast_center_nf2',\n devname_pmos_dmy='pmos4_fast_dmy_nf2',\n devname_ntap_boundary='ntap_fast_boundary', devname_ntap_body='ntap_fast_center_nf1',\n m_in=m_in, m_ofst=m_ofst, m_clkh=m_clkh, m_rgnn=m_rgnn, m_rstn=m_rstn, m_buf=m_buf,\n num_vert_pwr=2, origin=sa_origin)\n laygen.add_template_from_cell()\n \n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n", "#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"ADC library\n\"\"\"\nimport laygo\nimport numpy as np\nfrom math import log\nimport yaml\nimport os\nimport laygo.GridLayoutGeneratorHelper as laygenhelper #utility functions\n#import logging;logging.basicConfig(level=logging.DEBUG)\n\ndef generate_sar_wsamp(laygen, objectname_pfix, workinglib, samp_lib, space_1x_lib, sar_name, samp_name, space_1x_name,\n placement_grid, routing_grid_m5m6,\n routing_grid_m5m6_thick, routing_grid_m5m6_thick_basic,\n num_bits=9, origin=np.array([0, 0])):\n \"\"\"generate sar with sampling frontend \"\"\"\n pg = placement_grid\n\n rg_m5m6 = routing_grid_m5m6\n rg_m5m6_thick = routing_grid_m5m6_thick\n rg_m5m6_thick_basic = routing_grid_m5m6_thick_basic #for clock routing\n\n # placement\n # sar\n isar=laygen.place(name=\"I\" + objectname_pfix + 'SAR0', templatename=sar_name,\n gridname=pg, xy=origin, template_libname=workinglib)\n # samp\n isamp = laygen.relplace(name=\"I\" + objectname_pfix + 'SAMP0', templatename=samp_name,\n gridname=pg, refinstname=isar.name, direction='top', template_libname=samp_lib)\n\n #prboundary\n sar_size = laygen.templates.get_template(sar_name, libname=workinglib).size\n samp_size = laygen.templates.get_template(samp_name, libname=samp_lib).size\n space_size = laygen.templates.get_template(space_1x_name, libname=space_1x_lib).size\n size_x=sar_size[0]\n size_y=int((sar_size[1]+samp_size[1])/space_size[1]+1)*space_size[1]\n laygen.add_rect(None, np.array([origin, origin+np.array([size_x, size_y])]), laygen.layers['prbnd'])\n\n # template handles\n sar_template = laygen.templates.get_template(sar_name, workinglib)\n samp_template = laygen.templates.get_template(samp_name, samp_lib)\n\n #reference coordinates\n pdict_m5m6=laygen.get_inst_pin_xy(None, None, rg_m5m6)\n pdict_m5m6_thick=laygen.get_inst_pin_xy(None, None, rg_m5m6_thick)\n pdict_m5m6_thick_basic=laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_basic)\n sar_pins=sar_template.pins\n samp_pins=samp_template.pins\n #sar_xy=isar.xy[0]\n #samp_xy=isamp.xy[0]\n sar_xy=isar.xy\n samp_xy=isamp.xy\n\n #signal route (clk/inp/inm)\n #make virtual grids and route on the grids (assuming drc clearance of each block)\n rg_m5m6_thick_basic_temp_sig='route_M5_M6_thick_basic_temp_sig'\n laygenhelper.generate_grids_from_inst(laygen, gridname_input=rg_m5m6_thick_basic, gridname_output=rg_m5m6_thick_basic_temp_sig,\n instname=isamp.name, \n inst_pin_prefix=['ckout'], xy_grid_type='xgrid')\n pdict_m5m6_thick_basic_temp_sig = laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_basic_temp_sig)\n rg_m4m5_basic_thick_temp_sig='route_M4_M5_basic_thick_temp_sig'\n laygenhelper.generate_grids_from_inst(laygen, gridname_input=rg_m4m5_basic_thick, gridname_output=rg_m4m5_basic_thick_temp_sig,\n instname=isamp.name, \n inst_pin_prefix=['outp', 'outn'], xy_grid_type='xgrid')\n pdict_m4m5_basic_thick_temp_sig = laygen.get_inst_pin_xy(None, None, rg_m4m5_basic_thick_temp_sig)\n #clock\n rclk0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['ckout'][0],\n xy1=pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK0'][1]-np.array([0,1]), gridname0=rg_m5m6_thick_basic_temp_sig)\n laygen.via(None,pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK0'][1], rg_m5m6_thick_basic_temp_sig)\n laygen.via(None,pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK1'][1], rg_m5m6_thick_basic_temp_sig)\n #laygen.via(None,pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK2'][1], rg_m5m6_thick_basic_temp_sig)\n #rclk0 = laygen.route(None, laygen.layers['metal'][5],\n # xy0=pdict_m5m6_thick_basic[isamp.name]['ckout'][0],\n # xy1=pdict_m5m6_thick_basic[isar.name]['CLK'][1]-np.array([0,1]), gridname0=rg_m5m6_thick_basic)\n #laygen.via(None,pdict_m5m6_thick_basic[isar.name]['CLK'][1], rg_m5m6_thick_basic)\n\n #frontend sig\n inp_y_list=[]\n inm_y_list=[]\n for pn, p in pdict_m4m5_basic_thick_temp_sig[isar.name].items():\n if pn.startswith('INP'):\n inp_y_list.append(p[0][1])\n pv=np.array([pdict_m4m5_basic_thick_temp_sig[isamp.name]['outp'][0][0], p[0][1]])\n laygen.via(None,pv, rg_m4m5_basic_thick_temp_sig)\n #laygen.via(None,p[0], rg_m5m6_thick_basic_temp_sig)\n if pn.startswith('INM'):\n inm_y_list.append(p[0][1])\n pv=np.array([pdict_m4m5_basic_thick_temp_sig[isamp.name]['outn'][0][0], p[0][1]])\n laygen.via(None,pv, rg_m4m5_basic_thick_temp_sig)\n #laygen.via(None,p[0], rg_m5m6_thick_basic_temp_sig)\n inp_y=min(inp_y_list)\n inm_y=min(inm_y_list)\n rinp0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m4m5_basic_thick_temp_sig[isamp.name]['outp'][0],\n xy1=np.array([pdict_m4m5_basic_thick_temp_sig[isamp.name]['outp'][0][0],inp_y-1]), \n gridname0=rg_m4m5_basic_thick_temp_sig)\n rinm0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m4m5_basic_thick_temp_sig[isamp.name]['outn'][0],\n xy1=np.array([pdict_m4m5_basic_thick_temp_sig[isamp.name]['outn'][0][0],inm_y-1]), \n gridname0=rg_m4m5_basic_thick_temp_sig)\n #rinp0 = laygen.route(None, laygen.layers['metal'][5],\n # xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outp'][0],\n # xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isar.name]['INP0'][0][0],inp_y-1]), \n # gridname0=rg_m5m6_thick_basic_temp_sig)\n #rinm0 = laygen.route(None, laygen.layers['metal'][5],\n # xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outn'][0],\n # xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isar.name]['INM0'][0][0],inm_y-1]), \n # gridname0=rg_m5m6_thick_basic_temp_sig)\n\n #input pins (just duplicate from lower hierarchy cells)\n laygen.add_pin('CLK', 'CLK', samp_xy+samp_pins['ckin']['xy'], samp_pins['ckin']['layer'])\n laygen.add_pin('INP', 'INP', samp_xy+samp_pins['inp']['xy'], samp_pins['ckin']['layer'])\n laygen.add_pin('INM', 'INM', samp_xy+samp_pins['inn']['xy'], samp_pins['ckin']['layer'])\n\n laygen.add_pin('OSP', 'OSP', sar_xy+sar_pins['OSP']['xy'], sar_pins['OSP']['layer'])\n laygen.add_pin('OSM', 'OSM', sar_xy+sar_pins['OSM']['xy'], sar_pins['OSM']['layer'])\n for pn, p in sar_pins.items():\n if pn.startswith('VREF<0>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n laygen.add_pin(pn, 'VREF<0>', pxy, sar_pins[pn]['layer'])\n if pn.startswith('VREF<1>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n laygen.add_pin(pn, 'VREF<1>', pxy, sar_pins[pn]['layer'])\n if pn.startswith('VREF<2>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n laygen.add_pin(pn, 'VREF<2>', pxy, sar_pins[pn]['layer'])\n #laygen.add_pin('VREF_M5R<2>', 'VREF<2>', sar_xy+sar_pins['VREF_M5R<2>']['xy'], sar_pins['VREF_M5R<2>']['layer'])\n #laygen.add_pin('VREF_M5R<1>', 'VREF<1>', sar_xy+sar_pins['VREF_M5R<1>']['xy'], sar_pins['VREF_M5R<1>']['layer'])\n #laygen.add_pin('VREF_M5R<0>', 'VREF<0>', sar_xy+sar_pins['VREF_M5R<0>']['xy'], sar_pins['VREF_M5R<0>']['layer'])\n #laygen.add_pin('VREF_M5L<2>', 'VREF<2>', sar_xy+sar_pins['VREF_M5L<2>']['xy'], sar_pins['VREF_M5L<2>']['layer'])\n #laygen.add_pin('VREF_M5L<1>', 'VREF<1>', sar_xy+sar_pins['VREF_M5L<1>']['xy'], sar_pins['VREF_M5L<1>']['layer'])\n #laygen.add_pin('VREF_M5L<0>', 'VREF<0>', sar_xy+sar_pins['VREF_M5L<0>']['xy'], sar_pins['VREF_M5L<0>']['layer'])\n laygen.add_pin('CKDSEL0<1>', 'CKDSEL0<1>', sar_xy+sar_pins['CKDSEL0<1>']['xy'], sar_pins['CKDSEL0<1>']['layer'])\n laygen.add_pin('CKDSEL0<0>', 'CKDSEL0<0>', sar_xy+sar_pins['CKDSEL0<0>']['xy'], sar_pins['CKDSEL0<0>']['layer'])\n laygen.add_pin('CKDSEL1<1>', 'CKDSEL1<1>', sar_xy+sar_pins['CKDSEL1<1>']['xy'], sar_pins['CKDSEL1<1>']['layer'])\n laygen.add_pin('CKDSEL1<0>', 'CKDSEL1<0>', sar_xy+sar_pins['CKDSEL1<0>']['xy'], sar_pins['CKDSEL1<0>']['layer'])\n #laygen.add_pin('EXTCLK', 'EXTCLK', sar_xy+sar_pins['EXTCLK']['xy'], sar_pins['EXTCLK']['layer'])\n laygen.add_pin('EXTSEL_CLK', 'EXTSEL_CLK', sar_xy+sar_pins['EXTSEL_CLK']['xy'], sar_pins['EXTSEL_CLK']['layer'])\n #output pins (just duplicate from lower hierarchy cells)\n for i in range(num_bits):\n pn='ADCOUT'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n laygen.add_pin('CLKO0', 'CLKO', sar_xy+sar_pins['CLKOUT0']['xy'], sar_pins['CLKOUT0']['layer'])\n laygen.add_pin('CLKO1', 'CLKO', sar_xy+sar_pins['CLKOUT1']['xy'], sar_pins['CLKOUT1']['layer'])\n #laygen.add_pin('CLKO2', 'CLKO', sar_xy+sar_pins['CLKOUT2']['xy'], sar_pins['CLKOUT2']['layer'])\n \n #probe pins\n laygen.add_pin('CLK0', 'ICLK', sar_xy+sar_pins['CLK0']['xy'], sar_pins['CLK0']['layer'])\n laygen.add_pin('CLK1', 'ICLK', sar_xy+sar_pins['CLK1']['xy'], sar_pins['CLK1']['layer'])\n #laygen.add_pin('CLK2', 'ICLK', sar_xy+sar_pins['CLK2']['xy'], sar_pins['CLK2']['layer'])\n laygen.add_pin('CLKPRB_SAMP', 'CLKPRB_SAMP', samp_xy+samp_pins['ckpg']['xy'], samp_pins['ckpg']['layer'])\n #laygen.add_pin('CLKPRB_SAR', 'CLKPRB_SAR', sar_xy+sar_pins['CLKPRB']['xy'], sar_pins['CLKPRB']['layer'])\n laygen.add_pin('SAMPP', 'SAMPP', sar_xy+sar_pins['SAINP']['xy'], sar_pins['SAINP']['layer'])\n laygen.add_pin('SAMPM', 'SAMPM', sar_xy+sar_pins['SAINM']['xy'], sar_pins['SAINM']['layer'])\n laygen.add_pin('SAOP', 'SAOP', sar_xy+sar_pins['SAOP']['xy'], sar_pins['SAOP']['layer'])\n laygen.add_pin('SAOM', 'SAOM', sar_xy+sar_pins['SAOM']['xy'], sar_pins['SAOM']['layer'])\n laygen.add_pin('SARCLK', 'SARCLK', sar_xy+sar_pins['SARCLK']['xy'], sar_pins['SARCLK']['layer'])\n laygen.add_pin('SARCLKB', 'SARCLKB', sar_xy+sar_pins['SARCLKB']['xy'], sar_pins['SARCLKB']['layer'])\n #laygen.add_pin('COMPOUT', 'COMPOUT', sar_xy+sar_pins['COMPOUT']['xy'], sar_pins['COMPOUT']['layer'])\n laygen.add_pin('DONE', 'DONE', sar_xy+sar_pins['DONE']['xy'], sar_pins['DONE']['layer'])\n laygen.add_pin('UP', 'UP', sar_xy+sar_pins['UP']['xy'], sar_pins['UP']['layer'])\n laygen.add_pin('PHI0', 'PHI0', sar_xy+sar_pins['PHI0']['xy'], sar_pins['PHI0']['layer'])\n for i in range(num_bits):\n pn='ZP'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='ZMID'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='ZM'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='SB'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n for i in range(num_bits-1):\n pn='VOL'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='VOR'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n\n #VDD/VSS pin\n vddcnt=0\n vsscnt=0\n for p in pdict_m5m6[isar.name]:\n if p.startswith('VDD'):\n xy0=pdict_m5m6_thick[isar.name][p]\n laygen.pin(name='VDDSAR' + str(vddcnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick, netname='VDDSAR')\n vddcnt+=1\n if p.startswith('VSS'):\n xy0=pdict_m5m6_thick[isar.name][p]\n laygen.pin(name='VSSSAR' + str(vsscnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick, netname='VSS:')\n vsscnt+=1\n #extract VDD/VSS grid from samp and make power pins\n rg_m5m6_thick_temp_samp='route_M5_M6_thick_temp_samp'\n laygenhelper.generate_grids_from_inst(laygen, gridname_input=rg_m5m6_thick, gridname_output=rg_m5m6_thick_temp_samp,\n instname=isamp.name, \n inst_pin_prefix=['VDD', 'VSS'], xy_grid_type='ygrid')\n pdict_m5m6_thick_temp_samp = laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_temp_samp)\n vddcnt=0\n vsscnt=0\n for p in pdict_m5m6_thick_temp_samp[isamp.name]:\n if p.startswith('VDD'):\n xy0=pdict_m5m6_thick_temp_samp[isamp.name][p]\n laygen.pin(name='VDDSAMP' + str(vddcnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick_temp_samp, netname='VDDSAMP')\n vddcnt+=1\n if p.startswith('VSS'):\n xy0=pdict_m5m6_thick_temp_samp[isamp.name][p]\n laygen.pin(name='VSSSAMP' + str(vsscnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick_temp_samp, netname='VSS:')\n vsscnt+=1\n\nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n samp_lib = 'adc_sampler_ec'\n samp_name = 'sampler_nmos'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'adc_sar_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m4m5_basic_thick = 'route_M4_M5_basic_thick'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m5m6_thick = 'route_M5_M6_thick'\n rg_m5m6_basic_thick = 'route_M5_M6_basic_thick'\n rg_m5m6_thick_basic = 'route_M5_M6_thick_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n mycell_list = []\n num_bits=9\n #load from preset\n load_from_file=True\n yamlfile_spec=\"adc_sar_spec.yaml\"\n yamlfile_size=\"adc_sar_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n num_bits=specdict['n_bit']\n if specdict['samp_use_laygo'] is True:\n samp_lib = 'adc_sar_generated'\n samp_name = 'sarsamp'\n else:\n laygen.load_template(filename=samp_lib+'.yaml', libname=samp_lib)\n #yamlfile_system_input=\"adc_sar_dsn_system_input.yaml\"\n #if load_from_file==True:\n # with open(yamlfile_system_input, 'r') as stream:\n # sysdict_i = yaml.load(stream)\n # num_bits=sysdict_i['n_bit']\n #sar generation\n cellname='sar_wsamp' #_'+str(num_bits)+'b'\n sar_name = 'sar' #_'+str(num_bits)+'b'\n space_1x_name = 'space_1x'\n\n print(cellname+\" generating\")\n mycell_list.append(cellname)\n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n generate_sar_wsamp(laygen, objectname_pfix='SA0', workinglib=workinglib, samp_lib=samp_lib, space_1x_lib=logictemplib, sar_name=sar_name, samp_name=samp_name, space_1x_name=space_1x_name,\n placement_grid=pg, routing_grid_m5m6=rg_m5m6, routing_grid_m5m6_thick=rg_m5m6_thick, routing_grid_m5m6_thick_basic=rg_m5m6_thick_basic, \n num_bits=num_bits, origin=np.array([0, 0]))\n laygen.add_template_from_cell()\n \n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n" ]
[ [ "numpy.array" ], [ "numpy.array", "numpy.vstack" ], [ "numpy.array" ], [ "numpy.array" ], [ "numpy.array" ] ]
[ { "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": [] } ]
cypher-me/HAS-Qualifier-Challenges
[ "bb795303716155dad4a930880a58fecb5d9b50c5", "bb795303716155dad4a930880a58fecb5d9b50c5" ]
[ "centroids/challenge/ImageGen.py", "tweet/builder/pi3d/pi3d/shape/MergeShape.py" ]
[ "from scipy import signal\nfrom scipy import misc\nfrom scipy import stats as st\nimport numpy as np\n\nW = 128\nL = 128\nBody_Width = 3\nBorder = Body_Width+1\nPoints = 10\nNoise_Max = 10\nBody_Separation = 15\nBody_Scale = 30\nOvScale = 3\n\n\ndef gkern(kernlen=21, nsig=3):\n ''' 2D Gaussian Kernel. '''\n x = np.linspace(-nsig, nsig, kernlen+1)\n kern1d = np.diff(st.norm.cdf(x))\n kern2d = np.outer(kern1d, kern1d)\n return kern2d/kern2d.sum()\n\ndef genBackground():\n return np.random.rand(W,L)*(Noise_Max)\n\ndef genStarCoords():\n while True:\n star_cords = np.random.rand(Points,3) # N x [x,y,m]\n star_cords = star_cords * np.array([[ W-2*Border , L-2*Border , Body_Scale ]]) \n star_cords = star_cords + np.ones((Points,3)) * np.array([[ Border, Border, Body_Separation ]])\n bad = False\n for ii in range(0, Points-1):\n x0, y0, m0 = star_cords[ii,:]\n for jj in range(ii+1, Points):\n x1, y1, m1 = star_cords[jj,:]\n if np.abs(x0 - x1) < 4*Border and np.abs(y0 - y1) < 4*Border:\n '''\n x = np.random.random() * (W-2*Border) + Border\n y = np.random.random() * (W-2*Border) + Border\n star_cords[jj,0] = x\n star_cords[jj,1] = y\n '''\n \n bad = True\n break\n \n if np.abs(m0 - m1) < 5:\n star_cords[jj,2] = m1 + 5\n if not bad:\n break\n return star_cords\n\ndef starGauss(OvScale):\n gausKern = gkern(Body_Width*OvScale, Body_Width/(OvScale/3))\n gausKern = gausKern * (Body_Scale/np.max(np.max(gausKern)))\n return gausKern\n\ndef genImage(star_cords):\n # Overscale it \n spots_O = np.zeros((W*OvScale, L*OvScale))\n \n for (x,y,m) in star_cords:\n x = OvScale * (x+0.5)\n y = OvScale * (y+0.5) \n x_0, y_0 = map(int, np.floor([x,y]))\n x_1, y_1 = map(int, np.ceil([x,y]))\n spots_O[x_0:x_1, y_0:y_1] = m\n\n gausKern = starGauss(OvScale)\n spots_B = signal.convolve2d(spots_O, gausKern, boundary='symm', mode='same')\n\n spots = np.zeros((W,L))\n for (x,y,m) in star_cords:\n x = int(x)\n y = int(y)\n x0 = max(0, x-Body_Width-1)\n x1 = min(W, x+Body_Width+1)\n y0 = max(0, y-Body_Width-1)\n y1 = min(L, y+Body_Width+1)\n for ii in range(x0,x1+1):\n for jj in range(y0, y1+1):\n spots[ii,jj] = np.mean(spots_B[ii*OvScale:(ii+1)*OvScale, jj*OvScale:(jj+1)*OvScale])\n \n final = np.trunc( np.clip(genBackground() + spots, 0, 255) )\n return final\n", "from __future__ import absolute_import, division, print_function, unicode_literals\n\n#import ctypes\nimport math\nimport random\nimport numpy as np\n\nfrom pi3d.Buffer import Buffer\nfrom pi3d.Shape import Shape\nfrom pi3d.util.RotateVec import rotate_vec\nimport logging\n\nLOGGER = logging.getLogger(__name__)\n\nclass MergeShape(Shape):\n \"\"\" 3d model inherits from Shape. As there is quite a time penalty for\n doing the matrix recalculations and changing the variables being sent to\n the shader, each time an object is drawn, it is MUCH faster to use a MergeShape\n where several objects will always remain in the same positions relative to\n each other. i.e. trees in a forest.\n\n Where the objects have multiple Buffers, each needing a different texture\n (i.e. more complex Model objects) each must be combined into a different\n MergeShape\n \"\"\"\n def __init__(self, camera=None, light=None, name=\"\",\n x=0.0, y=0.0, z=0.0,\n rx=0.0, ry=0.0, rz=0.0,\n sx=1.0, sy=1.0, sz=1.0,\n cx=0.0, cy=0.0, cz=0.0):\n \"\"\"uses standard constructor for Shape\"\"\"\n super(MergeShape, self).__init__(camera, light, name, x, y, z,\n rx, ry, rz, sx, sy, sz, cx, cy, cz)\n\n LOGGER.info(\"Creating Merge Shape ...\")\n\n self.buf = [Buffer(self, [], [], [], [])] # create single empty buffer in case draw() before first merge()\n self.billboard_array = [np.zeros((0, 6), dtype='float32')] # list of arrays holding x0, z0, x, z, nx, nz for each vert\n self.childModel = None #unused but asked for by pickle\n\n def merge(self, bufr, x=0.0, y=0.0, z=0.0,\n rx=0.0, ry=0.0, rz=0.0,\n sx=1.0, sy=1.0, sz=1.0, bufnum=0):\n \"\"\"merge the vertices, normals etc from this Buffer with those already there\n the position, rotation, scale, offset are set according to the origin of\n the MergeShape. If bufr is not a Buffer then it will be treated as if it\n is a Shape and its first Buffer object will be merged. Argument additional\n to standard Shape:\n\n *bufr*\n Buffer object or Shape with a member buf[0] that is a Buffer object.\n OR an array or tuple where each element is an array or tuple with\n the required arguments i.e. [[bufr1, x1, y1, z1, rx1, ry1....],\n [bufr2, x2, y2...],[bufr3, x3, y3...]] this latter is a more efficient\n way of building a MergeShape from lots of elements. If multiple\n Buffers are passed in this way then the subsequent arguments (x,y,z etc)\n will be ignored.\n \n *x, y, z, rx, ry, rz, sx, sy, sz*\n Position rotation scale if merging a single Buffer\n \n *bufnum*\n Specify the index of Buffer to use. This allows a MergeShape to\n contain multiple Buffers each with potentially different shader,\n material, textures, draw_method and unib\n \"\"\"\n if not isinstance(bufr, list) and not isinstance(bufr, tuple):\n buflist = [[bufr, x, y, z, rx, ry, rz, sx, sy, sz, bufnum]]\n else:\n buflist = bufr\n\n # existing array and element buffers to add to (as well as other draw relevant values)\n vertices = [] # will hold a list of ndarrays - one for each Buffer\n normals = []\n tex_coords = []\n indices = []\n shader_list = []\n material_list = []\n textures_list = []\n draw_method_list = []\n unib_list = []\n for b in self.buf: # first of all collect info from pre-existing Buffers\n buf = b.array_buffer# alias to tidy code\n vertices.append(buf[:,0:3] if len(buf) > 0 else buf)\n normals.append(buf[:,3:6] if len(buf) > 0 else buf)\n tex_coords.append(buf[:,6:8] if len(buf) > 0 else buf) #TODO this will only cope with N_BYTES == 32\n indices.append(b.element_array_buffer[:])\n shader_list.append(b.shader)\n material_list.append(b.material[:])\n textures_list.append(b.textures[:])\n draw_method_list.append(b.draw_method)\n unib_list.append(b.unib[:])\n for b in buflist:\n if len(b) < 11: # no buffer number specified - use 0\n b.append(0)\n b_id = b[10] # alias for brevity and clarity below\n if b_id >= len(vertices): #add buffers if needed\n for i in range(b_id - len(vertices) + 1):\n vertices.append(np.zeros((0, 3), dtype='float32'))\n tex_coords.append(np.zeros((0, 2), dtype='float32'))\n indices.append(np.zeros((0, 3), dtype='float32'))\n normals.append(np.zeros((0, 3), dtype='float32'))\n shader_list.append(None)\n material_list.append(())\n textures_list.append([])\n draw_method_list.append(None)\n unib_list.append([])\n self.billboard_array.append(np.zeros((0, 6), dtype='float32'))\n if not(type(b[0]) is Buffer): #deal with being passed a Shape\n bufr = b[0].buf[0]\n else:\n bufr = b[0]\n\n n = len(bufr.array_buffer)\n\n LOGGER.info(\"Merging Buffer %s\", bufr)\n\n original_vertex_count = len(vertices[b_id])\n\n vrot = rotate_vec(b[4], b[5], b[6], np.array(bufr.array_buffer[:,0:3]))\n vrot[:,0] = vrot[:,0] * b[7] + b[1]\n vrot[:,1] = vrot[:,1] * b[8] + b[2]\n vrot[:,2] = vrot[:,2] * b[9] + b[3]\n if bufr.array_buffer.shape[1] >= 6:\n nrot = rotate_vec(b[4], b[5], b[6], np.array(bufr.array_buffer[:,3:6]))\n else:\n nrot = np.zeros((n, 3))\n\n vertices[b_id] = np.append(vertices[b_id], vrot)\n normals[b_id] = np.append(normals[b_id], nrot)\n if bufr.array_buffer.shape[1] == 8:\n tex_coords[b_id] = np.append(tex_coords[b_id], bufr.array_buffer[:,6:8])\n else:\n tex_coords[b_id] = np.append(tex_coords[b_id], np.zeros((n, 2)))\n\n nv = vrot.shape[0]\n ba = self.billboard_array[b_id] # aliases for brevity below\n ba = np.append(ba, np.zeros((nv, 6), dtype='float32')).reshape(-1, 6) # as append flattens array\n ba[-nv:,2:4] = vrot[:,::2] - [b[1], b[3]] # only holds x and z values\n ba[-nv:,0:2] = [b[1], b[3]] # offset of rotation centre from centre of MergeShape\n ba[-nv:,4:6] = nrot[:,::2] # step 2 to get x and z but not y\n self.billboard_array[b_id] = ba\n\n n = int(len(vertices[b_id]) / 3)\n vertices[b_id].shape = (n, 3)\n normals[b_id].shape = (n, 3)\n tex_coords[b_id].shape = (n, 2)\n\n #ctypes.restype = ctypes.c_short # TODO: remove this side-effect.\n faces = bufr.element_array_buffer + original_vertex_count\n indices[b_id] = np.append(indices[b_id], faces)\n\n n = int(len(indices[b_id]) / 3)\n indices[b_id].shape = (n, 3)\n\n shader_list[b_id] = bufr.shader\n material_list[b_id] = bufr.material[:]\n textures_list[b_id] = bufr.textures[:]\n draw_method_list[b_id] = bufr.draw_method\n unib_list[b_id] = bufr.unib[:]\n\n self.buf = []\n for i in range(len(vertices)):\n buf = Buffer(self, vertices[i], tex_coords[i], indices[i], normals[i])\n # add back Buffer details from lists\n buf.shader = shader_list[i]\n buf.material = material_list[i]\n buf.textures = textures_list[i]\n buf.draw_method = draw_method_list[i]\n for j in range(len(unib_list[i])): # have to change elements in ctypes array\n buf.unib[j] = unib_list[i][j]\n self.buf.append(buf)\n\n def add(self, bufr, x=0.0, y=0.0, z=0.0, rx=0.0, ry=0.0, rz=0.0,\n sx=1.0, sy=1.0, sz=1.0, bufnum=0):\n \"\"\"wrapper to alias merge method\"\"\"\n self.merge(bufr, x, y, z, rx, ry, rz, sx, sy, sz, bufnum)\n\n def cluster(self, bufr, elevmap, xpos, zpos, w, d, count, options, minscl, maxscl, bufnum=0, billboard=False):\n \"\"\"generates a random cluster on an ElevationMap.\n\n Arguments:\n *bufr*\n Buffer object to merge.\n *elevmap*\n ElevationMap object to merge onto.\n *xpos, zpos*\n x and z location of centre of cluster. These are locations RELATIVE\n to the origin of the MergeShape\n *w, d*\n x and z direction size of the cluster.\n *count*\n Number of objects to generate.\n *options*\n Deprecated.\n *minscl*\n The minimum scale value for random selection.\n *maxscl*\n The maximum scale value for random selection.\n *billboard*\n If True then all Buffers are set rotated 180 degrees so that they turn to face\n Camera location when billboard() called\n \"\"\"\n #create a cluster of shapes on an elevation map\n blist = []\n for _ in range(count):\n x = xpos + random.random() * w - w * 0.5\n z = zpos + random.random() * d - d * 0.5\n rh = random.random() * (maxscl - minscl) + minscl\n if billboard:\n rt = 180.0\n else:\n rt = random.random() * 360.0\n y = elevmap.calcHeight(self.unif[0] + x, self.unif[2] + z) + rh * 2\n blist.append([bufr, x, y, z, 0.0, rt, 0.0, rh, rh, rh, bufnum])\n self.merge(blist)\n\n def radialCopy(self, bufr, x=0, y=0, z=0, startRadius=2.0, endRadius=2.0,\n startAngle=0.0, endAngle=360.0, step=12, bufnum=0):\n \"\"\"generates a radially copied cluster, axix is in the y direction.\n\n Arguments:\n *bufr*\n Buffer object to merge.\n\n Keyword arguments:\n *x,y,z*\n Location of centre of cluster relative to origin of MergeShape.\n *startRadius*\n Start radius.\n *endRadius*\n End radius.\n *startAngle*\n Start angle for merging 0 is in +ve x direction.\n *andAngle*\n End angle for merging, degrees. Rotation is clockwise\n looking up the y axis.\n *step*\n Angle between each copy, degrees NB *NOT* number of steps.\n \"\"\"\n st = (endAngle - startAngle) / step\n rst = (endRadius - startRadius) / int(st)\n rd = startRadius\n sta = startAngle\n\n blist = []\n for r in range(int(st)):\n LOGGER.info(\"merging %d\", r)\n ca = math.cos(math.radians(sta))\n sa = math.sin(math.radians(sta))\n sta += step\n rd += rst\n blist.append([bufr, x + ca * rd, y, z + sa * rd,\n 0, sta, 0, 1.0, 1.0, 1.0, bufnum])\n\n self.merge(blist)\n LOGGER.info(\"merged all\")\n \n def billboard(self, cam_location):\n ''' rotates all merged shapes to face camera\n \n *cam_location*\n tuple of x,y,z location of camera'''\n for i, b in enumerate(self.buf):\n offset = self.billboard_array[i][:,:2] + [self.unif[0], self.unif[2]]- cam_location[::2] # \n inv_len = 1.0 / ((offset ** 2).sum(axis=1)) ** 0.5 # marginal saving by only doing one divide operation\n s = offset[:,0] * inv_len\n c = -offset[:,1] * inv_len # z direction reversed for rotation using standard [[c,-s],[s,c]]\n b.array_buffer[:,0] = self.billboard_array[i][:,0] + self.billboard_array[i][:,2] * c - self.billboard_array[i][:,3] * s\n b.array_buffer[:,2] = self.billboard_array[i][:,1] + self.billboard_array[i][:,2] * s + self.billboard_array[i][:,3] * c\n b.array_buffer[:,3] = self.billboard_array[i][:,4] * c - self.billboard_array[i][:,5] * s # rotate normals too\n b.array_buffer[:,4] = self.billboard_array[i][:,4] * s + self.billboard_array[i][:,5] * c\n b.re_init()" ]
[ [ "scipy.stats.norm.cdf", "numpy.linspace", "numpy.abs", "scipy.signal.convolve2d", "numpy.ones", "numpy.ceil", "numpy.max", "numpy.mean", "numpy.random.rand", "numpy.floor", "numpy.outer", "numpy.array", "numpy.zeros" ], [ "numpy.append", "numpy.array", "numpy.zeros" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xuanxu/py-pde
[ "de33d938aea8680eff872ae1b64569895662a248" ]
[ "pde/trackers/trackers.py" ]
[ "\"\"\"\nModule defining classes for tracking results from simulations.\n\nThe trackers defined in this module are:\n\n.. autosummary::\n :nosignatures:\n\n CallbackTracker\n ProgressTracker\n PrintTracker\n PlotTracker\n DataTracker\n SteadyStateTracker\n RuntimeTracker\n ConsistencyTracker\n MaterialConservationTracker\n\n.. codeauthor:: David Zwicker <[email protected]>\n\"\"\"\n\nfrom datetime import timedelta\nimport inspect\nimport sys\nimport time\nfrom typing import Callable, Optional, Union, IO, List, Any # @UnusedImport\n\nimport numpy as np\n\nfrom .base import TrackerBase, InfoDict, FinishedSimulation, Real\nfrom .intervals import IntervalData, RealtimeIntervals\nfrom ..fields.base import FieldBase\nfrom ..fields import FieldCollection\nfrom ..tools.parse_duration import parse_duration\nfrom ..tools.misc import get_progress_bar_class\n\n\n\nclass CallbackTracker(TrackerBase):\n \"\"\" Tracker that calls a function periodically \"\"\"\n \n def __init__(self, func: Callable,\n interval: IntervalData = 1):\n \"\"\" \n Args:\n func: The function to call periodically. The function signature\n should be `(state)` or `(state, time)`, where `state` contains\n the current state as an instance of\n :class:`~pde.fields.FieldBase` and `time` is a\n float value indicating the current time. Note that only a view\n of the state is supplied, implying that a copy needs to be made\n if the data should be stored.\n interval: |Arg_tracker_interval|\n \"\"\"\n super().__init__(interval=interval)\n self._callback = func\n self._num_args = len(inspect.signature(func).parameters)\n if not 0 < self._num_args < 3:\n raise ValueError('`func` must be a function accepting one or two '\n f'arguments, not {self._num_args}') \n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle data supplied to this tracker\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n The current state of the simulation\n t (float): The associated time\n \"\"\"\n if self._num_args == 1:\n self._callback(field)\n else:\n self._callback(field, t)\n\n\n\nclass ProgressTracker(TrackerBase):\n \"\"\" Tracker that shows the progress of the simulation \"\"\"\n \n name = 'progress'\n\n \n def __init__(self, interval: IntervalData = None,\n ndigits: int = 5, leave: bool = True):\n \"\"\"\n Args:\n interval: |Arg_tracker_interval|\n The default value `None` updates the progress bar approximately\n every (real) second.\n ndigits (int): The number of digits after the decimal point that are\n shown maximally.\n leave (bool): Whether to leave the progress bar after the simulation\n has finished (default: True)\n \"\"\" \n if interval is None:\n # print every second by default\n interval = RealtimeIntervals(duration=1)\n \n super().__init__(interval=interval)\n self.ndigits = ndigits\n self.leave = leave\n \n\n def initialize(self, field: FieldBase, info: InfoDict = None) -> float:\n \"\"\" initialize the tracker with information about the simulation\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n An example of the data that will be analyzed by the tracker\n info (dict):\n Extra information from the simulation \n \n Returns:\n float: The first time the tracker needs to handle data\n \"\"\"\n result = super().initialize(field, info)\n \n # get solver information\n controller_info = {} if info is None else info.get('controller', {})\n \n # initialize the progress bar\n pb_cls = get_progress_bar_class()\n self.progress_bar = pb_cls(total=controller_info.get('t_end'),\n initial=controller_info.get('t_start', 0),\n leave=self.leave)\n self.progress_bar.set_description('Initializing')\n\n return result\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle data supplied to this tracker\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n The current state of the simulation\n t (float): The associated time\n \"\"\"\n # show an update\n if self.progress_bar.total:\n t_new = min(t, self.progress_bar.total)\n else:\n t_new = t\n self.progress_bar.n = round(t_new, self.ndigits)\n self.progress_bar.set_description('')\n \n \n def finalize(self, info: InfoDict = None) -> None:\n \"\"\" finalize the tracker, supplying additional information\n\n Args:\n info (dict):\n Extra information from the simulation \n \"\"\"\n super().finalize(info)\n self.progress_bar.set_description('')\n\n # limit progress bar to 100%\n controller_info = {} if info is None else info.get('controller', {}) \n t_final = controller_info.get('t_final', -np.inf)\n t_end = controller_info.get('t_end', -np.inf)\n if t_final >= t_end and self.progress_bar.total:\n self.progress_bar.n = self.progress_bar.total\n self.progress_bar.refresh()\n \n if (controller_info.get('successful', False) and self.leave and\n hasattr(self.progress_bar, 'sp')):\n # show progress bar in green if simulation was successful. We\n # need to overwrite the default behavior (and disable the\n # progress bar) since reaching steady state means the simulation\n # was successful even though it did not reach t_final\n try:\n self.progress_bar.sp(bar_style='success')\n except TypeError:\n self.progress_bar.close()\n else:\n self.disable = True\n else:\n self.progress_bar.close()\n \n \n def __del__(self):\n if hasattr(self, 'progress_bar') and not self.progress_bar.disable:\n self.progress_bar.close()\n\n\n\nclass PrintTracker(TrackerBase):\n \"\"\" Tracker that prints data to a stream (default: stdout) \"\"\"\n \n name = 'print'\n \n \n def __init__(self, interval: IntervalData = 1,\n stream: IO[str] = sys.stdout):\n \"\"\"\n \n Args:\n interval: |Arg_tracker_interval|\n stream: The stream used for printing\n \"\"\"\n super().__init__(interval=interval)\n self.stream = stream\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle data supplied to this tracker\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n The current state of the simulation\n t (float): The associated time\n \"\"\"\n data = f\"c={field.data.mean():.3g}±{field.data.std():.3g}\"\n \n self.stream.write(f\"t={t:g}, {data}\\n\")\n self.stream.flush()\n\n\n\nclass PlotTracker(TrackerBase):\n \"\"\" Tracker that plots data on screen, to files, or writes a movie \"\"\"\n \n name = 'plot'\n \n def __init__(self, interval: IntervalData = 1,\n output_file: Optional[str] = None,\n output_folder: Optional[str] = None,\n movie_file: Optional[str] = None,\n quantities=None,\n show: bool = True):\n \"\"\"\n Args:\n interval: |Arg_tracker_interval|\n output_file (str, optional):\n Specifies a single image file, which is updated periodically, so\n that the progress can be monitored (e.g. on a compute cluster)\n output_folder (str, optional):\n Specifies a folder to which all images are written. The files\n will have names with increasing numbers.\n movie_file (str, optional):\n Specifies a filename to which a movie of all the frames is\n written after the simulation.\n quantities:\n |Args_plot_quantities|\n show (bool, optional):\n Determines whether the plot is shown while the simulation is\n running. If `False`, the files are created in the background.\n \"\"\"\n super().__init__(interval=interval)\n self.output_file = output_file\n self.output_folder = output_folder\n self.quantities = quantities\n self.show = show\n \n if movie_file is not None or output_folder is not None:\n from ..visualization.movies import Movie\n movie = Movie(filename=movie_file, image_folder=output_folder)\n self.movie: Optional[Movie] = movie\n self.movie._start() # initialize movie\n else:\n self.movie = None\n \n \n def initialize(self, field: FieldBase, info: InfoDict = None) -> float:\n \"\"\" initialize the tracker with information about the simulation\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n An example of the data that will be analyzed by the tracker\n info (dict):\n Extra information from the simulation\n \n Returns:\n float: The first time the tracker needs to handle data\n \"\"\"\n from ..visualization.plotting import ScalarFieldPlot\n self.plot = ScalarFieldPlot(field, quantities=self.quantities,\n show=self.show)\n \n return super().initialize(field, info=info)\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle data supplied to this tracker\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n The current state of the simulation\n t (float): The associated time\n \"\"\"\n self.plot.show_data(field, title=f'Time {t:g}')\n if self.output_file:\n self.plot.fig.savefig(self.output_file)\n if self.movie:\n self.movie.add_figure(self.plot.fig)\n \n\n def finalize(self, info: InfoDict = None) -> None:\n \"\"\" finalize the tracker, supplying additional information\n\n Args:\n info (dict):\n Extra information from the simulation \n \"\"\"\n super().finalize(info)\n if self.movie:\n if self.movie.filename:\n # write out movie file if requested\n self._logger.info(f'Writing movie to {self.movie.filename}...')\n self.movie.save()\n # finalize movie (e.g. delete temporary files)\n self.movie._end()\n if not self.show:\n del self.plot\n \n \n \nclass DataTracker(CallbackTracker):\n \"\"\" Tracker that stores custom data obtained by calling a function\n \n Attributes:\n times (list):\n The time points at which the data is stored\n data (list):\n The actually stored data, which is a list of the objects returned by\n the callback function. \n \"\"\"\n \n def __init__(self, func: Callable,\n interval: IntervalData = 1):\n \"\"\" \n Args:\n func: The function to call periodically. The function signature\n should be `(state)` or `(state, time)`, where `state` contains\n the current state as an instance of\n :class:`~pde.fields.FieldBase` and `time` is a\n float value indicating the current time. Note that only a view\n of the state is supplied, implying that a copy needs to be made\n if the data should be stored.\n interval: |Arg_tracker_interval|\n \"\"\"\n super().__init__(func=func, interval=interval)\n self.times: List[float] = []\n self.data: List[Any] = []\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle data supplied to this tracker\n \n Args:\n field (:class:`~pde.fields.FieldBase`):\n The current state of the simulation\n t (float): The associated time\n \"\"\"\n self.times.append(t)\n if self._num_args == 1:\n self.data.append(self._callback(field))\n else:\n self.data.append(self._callback(field, t))\n \n \n @property\n def dataframe(self):\n \"\"\" pandas.DataFrame: the data as a pandas DataFrame \"\"\"\n import pandas as pd\n df = pd.DataFrame(self.data)\n # insert the times and use them as an index\n df.insert(0, 'time', self.times)\n return df\n \n \n \nclass SteadyStateTracker(TrackerBase):\n \"\"\" Tracker that interrupts the simulation once steady state is reached\n \n Steady state is obtained when the state does not change anymore. This is the\n case when the derivative is close to zero.\n \"\"\"\n\n name = 'steady_state'\n\n\n def __init__(self, interval: IntervalData = None,\n atol: float = 1e-8,\n rtol: float = 1e-5):\n \"\"\"\n Args:\n interval: |Arg_tracker_interval|\n The default value `None` checks for the steady state\n approximately every (real) second.\n atol (float): Absolute tolerance that must be reached to abort the\n simulation\n rtol (float): Relative tolerance that must be reached to abort the\n simulation\n \"\"\" \n if interval is None:\n interval = RealtimeIntervals(duration=1)\n super().__init__(interval=interval)\n self.atol = atol \n self.rtol = rtol\n self._last_data = None\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle the data of `field` for a give `time` \"\"\"\n if self._last_data is not None:\n # scale with dt to make test independent of dt\n atol = self.atol * self.interval.dt\n rtol = self.rtol * self.interval.dt\n if np.allclose(self._last_data, field.data,\n rtol=rtol, atol=atol, equal_nan=True):\n raise FinishedSimulation('Reached stationary state')\n \n self._last_data = field.data.copy() # store data from last timestep\n \n\n\nclass RuntimeTracker(TrackerBase):\n \"\"\" Tracker that interrupts the simulation once a duration has passed \"\"\"\n\n\n def __init__(self, max_runtime: Union[Real, str],\n interval: IntervalData = 1): \n \"\"\"\n Args:\n max_runtime (float or str):\n The maximal runtime of the simulation. If the runtime is\n exceeded, the simulation is interrupted. Values can be either\n given as a number (interpreted as seconds) or as a string, which\n is then parsed using the function\n :func:`~pde.tools.parse_duration.parse_duration`.\n interval: |Arg_tracker_interval|\n \"\"\"\n super().__init__(interval=interval)\n \n try:\n self.max_runtime = float(max_runtime)\n except ValueError:\n td = parse_duration(str(max_runtime))\n self.max_runtime = td.total_seconds()\n\n\n def initialize(self, field: FieldBase, info: InfoDict = None) -> float:\n \"\"\" \n Args:\n field (:class:`~pde.fields.FieldBase`):\n An example of the data that will be analyzed by the tracker\n info (dict):\n Extra information from the simulation \n \n Returns:\n float: The first time the tracker needs to handle data\n \"\"\"\n self.max_time = time.time() + self.max_runtime\n return super().initialize(field, info)\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle the data of `field` for a give `time` \"\"\"\n if time.time() > self.max_time:\n dt = timedelta(seconds=self.max_runtime)\n raise FinishedSimulation(f'Reached maximal runtime of {str(dt)}')\n\n \n \nclass ConsistencyTracker(TrackerBase):\n \"\"\" Tracker that interrupts the simulation when the state is not finite \"\"\" \n\n name = 'consistency'\n \n \n def __init__(self, interval: IntervalData = None):\n \"\"\"\n Args:\n interval: |Arg_tracker_interval| The default value `None` checks for\n consistency approximately every (real) second.\n \"\"\" \n if interval is None:\n interval = RealtimeIntervals(duration=1)\n super().__init__(interval=interval)\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle the data of `field` for a give `time` \"\"\"\n if not np.all(np.isfinite(field.data)):\n raise StopIteration('Field was not finite')\n \n self._last = field.data.copy() # store data from last timestep\n \n\n\nclass MaterialConservationTracker(TrackerBase):\n \"\"\" Ensure that the amount of material is conserved \"\"\"\n\n name = 'material_conservation'\n\n\n def __init__(self, interval: IntervalData = 1,\n atol: float = 1e-4,\n rtol: float = 1e-4):\n \"\"\"\n Args:\n interval: |Arg_tracker_interval|\n atol (float): Absolute tolerance for amount deviations\n rtol (float): Relative tolerance for amount deviations\n \"\"\"\n super().__init__(interval=interval)\n self.atol = atol \n self.rtol = rtol\n \n \n def initialize(self, field: FieldBase, info: InfoDict = None) -> float:\n \"\"\" \n Args:\n field (:class:`~pde.fields.base.FieldBase`):\n An example of the data that will be analyzed by the tracker\n info (dict):\n Extra information from the simulation \n \n Returns:\n float: The first time the tracker needs to handle data\n \"\"\"\n if isinstance(field, FieldCollection):\n self._reference = np.array([f.magnitude for f in field])\n else:\n self._reference = field.magnitude # type: ignore\n \n return super().initialize(field, info)\n \n \n def handle(self, field: FieldBase, t: float) -> None:\n \"\"\" handle the data of `field` for a give `time` \"\"\"\n if isinstance(field, FieldCollection):\n mags = np.array([f.magnitude for f in field])\n else:\n mags = field.magnitude # type: ignore\n \n c = np.isclose(mags, self._reference, rtol=self.rtol, atol=self.atol)\n if not np.all(c):\n if isinstance(field, FieldCollection):\n msg = f'Material of field {np.flatnonzero(~c)} is not conserved'\n else:\n msg = f'Material is not conserved'\n raise StopIteration(msg)\n \n \n__all__ = ['CallbackTracker', 'ProgressTracker', 'PrintTracker', 'PlotTracker',\n 'DataTracker', 'SteadyStateTracker', 'RuntimeTracker',\n 'ConsistencyTracker', 'MaterialConservationTracker']\n" ]
[ [ "numpy.allclose", "numpy.isfinite", "pandas.DataFrame", "numpy.flatnonzero", "numpy.all", "numpy.array", "numpy.isclose" ] ]
[ { "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": [] } ]
NunoEdgarGFlowHub/pgmpy
[ "ac0ecc8f5bdd14999c386c6b00a3ce77407b83ce" ]
[ "pgmpy/readwrite/XMLBIF.py" ]
[ "#!/usr/bin/env python\n\ntry:\n from lxml import etree\nexcept ImportError:\n try:\n import xml.etree.ElementTree as etree\n except ImportError:\n #try:\n # import xml.etree.cElementTree as etree\n # commented out because xml.etree.cElementTree is giving errors with dictionary attributes\n print(\"Failed to import ElementTree from any known place\")\n \nimport numpy as np\n\nfrom pgmpy.models import BayesianModel\nfrom pgmpy.factors import TabularCPD, State\nfrom pgmpy.extern.six.moves import map, range\n\n\nclass XMLBIFReader(object):\n \"\"\"\n Base class for reading network file in XMLBIF format.\n \"\"\"\n def __init__(self, path=None, string=None):\n \"\"\"\n Initialisation of XMLBIFReader object.\n\n Parameters\n ----------\n path : file or str\n File of XMLBIF data\n string : str\n String of XMLBIF data\n\n Examples\n --------\n # xmlbif_test.xml is the file present in\n # http://www.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/\n >>> reader = XMLBIFReader(\"xmlbif_test.xml\")\n \"\"\"\n if path:\n self.network = etree.ElementTree(file=path).getroot().find('NETWORK')\n elif string:\n self.network = etree.fromstring(string).find('NETWORK')\n else:\n raise ValueError(\"Must specify either path or string\")\n self.network_name = self.network.find('NAME').text\n self.variables = self.get_variables()\n self.variable_parents = self.get_parents()\n self.edge_list = self.get_edges()\n self.variable_states = self.get_states()\n self.variable_CPD = self.get_cpd()\n self.variable_property = self.get_property()\n\n def get_variables(self):\n \"\"\"\n Returns list of variables of the network\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_variables()\n ['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out']\n \"\"\"\n variables = [variable.find('NAME').text for variable in self.network.findall('VARIABLE')]\n return variables\n\n def get_edges(self):\n \"\"\"\n Returns the edges of the network\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_edges()\n [['family-out', 'light-on'],\n ['family-out', 'dog-out'],\n ['bowel-problem', 'dog-out'],\n ['dog-out', 'hear-bark']]\n \"\"\"\n edge_list = [[value, key] for key in self.variable_parents\n for value in self.variable_parents[key]]\n return edge_list\n\n def get_states(self):\n \"\"\"\n Returns the states of variables present in the network\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_states()\n {'bowel-problem': ['true', 'false'],\n 'dog-out': ['true', 'false'],\n 'family-out': ['true', 'false'],\n 'hear-bark': ['true', 'false'],\n 'light-on': ['true', 'false']}\n \"\"\"\n variable_states = {variable.find('NAME').text: [outcome.text for outcome in variable.findall('OUTCOME')]\n for variable in self.network.findall('VARIABLE')}\n return variable_states\n\n def get_parents(self):\n \"\"\"\n Returns the parents of the variables present in the network\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_parents()\n {'bowel-problem': [],\n 'dog-out': ['family-out', 'bowel-problem'],\n 'family-out': [],\n 'hear-bark': ['dog-out'],\n 'light-on': ['family-out']}\n \"\"\"\n variable_parents = {definition.find('FOR').text: [edge.text for edge in definition.findall('GIVEN')][::-1]\n for definition in self.network.findall('DEFINITION')}\n return variable_parents\n\n def get_cpd(self):\n \"\"\"\n Returns the CPD of the variables present in the network\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_cpd()\n {'bowel-problem': array([[ 0.01],\n [ 0.99]]),\n 'dog-out': array([[ 0.99, 0.01, 0.97, 0.03],\n [ 0.9 , 0.1 , 0.3 , 0.7 ]]),\n 'family-out': array([[ 0.15],\n [ 0.85]]),\n 'hear-bark': array([[ 0.7 , 0.3 ],\n [ 0.01, 0.99]]),\n 'light-on': array([[ 0.6 , 0.4 ],\n [ 0.05, 0.95]])}\n \"\"\"\n variable_CPD = {definition.find('FOR').text: list(map(float, table.text.split()))\n for definition in self.network.findall('DEFINITION')\n for table in definition.findall('TABLE')}\n for variable in variable_CPD:\n arr = np.array(variable_CPD[variable])\n arr = arr.reshape((len(self.variable_states[variable]),\n arr.size//len(self.variable_states[variable])))\n variable_CPD[variable] = arr\n return variable_CPD\n\n def get_property(self):\n \"\"\"\n Returns the property of the variable\n\n Examples\n --------\n >>> reader = XMLBIF.XMLBIFReader(\"xmlbif_test.xml\")\n >>> reader.get_property()\n {'bowel-problem': ['position = (190, 69)'],\n 'dog-out': ['position = (155, 165)'],\n 'family-out': ['position = (112, 69)'],\n 'hear-bark': ['position = (154, 241)'],\n 'light-on': ['position = (73, 165)']}\n \"\"\"\n variable_property = {variable.find('NAME').text: [property.text for property in variable.findall('PROPERTY')]\n for variable in self.network.findall('VARIABLE')}\n return variable_property\n\n def get_model(self):\n model = BayesianModel(self.get_edges())\n model.name = self.network_name\n\n tabular_cpds = []\n for var, values in self.variable_CPD.items():\n cpd = TabularCPD(var, len(self.variable_states[var]), values,\n evidence=self.variable_parents[var],\n evidence_card=[len(self.variable_states[evidence_var])\n for evidence_var in self.variable_parents[var]])\n tabular_cpds.append(cpd)\n\n model.add_cpds(*tabular_cpds)\n\n for node, properties in self.variable_property.items():\n for prop in properties:\n prop_name, prop_value = map(lambda t: t.strip(), prop.split('='))\n model.node[node][prop_name] = prop_value\n\n return model\n\n\nclass XMLBIFWriter(object):\n \"\"\"\n Base class for writing XMLBIF network file format.\n \"\"\"\n def __init__(self, model, encoding='utf-8', prettyprint=True):\n \"\"\"\n Initialise a XMLBIFWriter object.\n\n Parameters\n ----------\n model: BayesianModel Instance\n Model to write\n encoding: str (optional)\n Encoding for text data\n prettyprint: Bool(optional)\n Indentation in output XML if true\n\n Examples\n --------\n >>> writer = XMLBIFWriter(model)\n \"\"\"\n if not isinstance(model, BayesianModel):\n raise TypeError(\"model must an instance of BayesianModel\")\n self.model = model\n\n self.encoding = encoding\n self.prettyprint = prettyprint\n\n self.xml = etree.Element(\"BIF\", attrib={'version': '0.3'})\n self.network = etree.SubElement(self.xml, 'NETWORK')\n if self.model.name:\n etree.SubElement(self.network, 'NAME').text = self.model.name\n\n self.variables = self.get_variables()\n self.states = self.get_states()\n self.properties = self.get_properties()\n self.definition = self.get_definition()\n self.tables = self.get_cpd()\n\n def __str__(self):\n \"\"\"\n Return the XML as string.\n \"\"\"\n if self.prettyprint:\n self.indent(self.xml)\n return etree.tostring(self.xml, encoding=self.encoding)\n\n def indent(self, elem, level=0):\n \"\"\"\n Inplace prettyprint formatter.\n \"\"\"\n i = \"\\n\" + level*\" \"\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = i + \" \"\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n for elem in elem:\n self.indent(elem, level+1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n else:\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = i\n\n def get_variables(self):\n \"\"\"\n Add variables to XMLBIF\n\n Return\n ------\n dict: dict of type {variable: variable tags}\n\n Examples\n --------\n >>> writer = XMLBIFWriter(model)\n >>> writer.get_variables()\n {'bowel-problem': <Element VARIABLE at 0x7fe28607dd88>,\n 'family-out': <Element VARIABLE at 0x7fe28607de08>,\n 'hear-bark': <Element VARIABLE at 0x7fe28607de48>,\n 'dog-out': <Element VARIABLE at 0x7fe28607ddc8>,\n 'light-on': <Element VARIABLE at 0x7fe28607de88>}\n \"\"\"\n variables = self.model.nodes()\n variable_tag = {}\n for var in sorted(variables):\n variable_tag[var] = etree.SubElement(self.network, \"VARIABLE\", attrib={'TYPE': 'nature'})\n etree.SubElement(variable_tag[var], \"NAME\").text = var\n return variable_tag\n\n def get_states(self):\n \"\"\"\n Add outcome to variables of XMLBIF\n\n Return\n ------\n dict: dict of type {variable: outcome tags}\n\n Examples\n --------\n >>> writer = XMLBIFWriter(model)\n >>> writer.get_states()\n {'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>],\n 'family-out': [<Element OUTCOME at 0x7ffbabfd4108>, <Element OUTCOME at 0x7ffbabfd4148>],\n 'bowel-problem': [<Element OUTCOME at 0x7ffbabfd4088>, <Element OUTCOME at 0x7ffbabfd40c8>],\n 'hear-bark': [<Element OUTCOME at 0x7ffbabfcdf48>, <Element OUTCOME at 0x7ffbabfcdf88>],\n 'light-on': [<Element OUTCOME at 0x7ffbabfcdfc8>, <Element OUTCOME at 0x7ffbabfd4048>]}\n \"\"\"\n outcome_tag = {}\n cpds = self.model.get_cpds()\n for cpd in cpds:\n var = cpd.variable\n outcome_tag[var] = []\n for state in [State(var, state) for state in range(cpd.get_cardinality([var])[var])]:\n # for state in [cpd.variables[var]:\n state_tag = etree.SubElement(self.variables[var], \"OUTCOME\")\n state_tag.text = str(state.state)\n outcome_tag[var].append(state_tag)\n return outcome_tag\n\n def get_properties(self):\n \"\"\"\n Add property to variables in XMLBIF\n\n Return\n ------\n dict: dict of type {variable: property tag}\n\n Examples\n --------\n >>> writer = XMLBIFWriter(model)\n >>> writer.get_property()\n {'light-on': <Element PROPERTY at 0x7f7a2ffac1c8>,\n 'family-out': <Element PROPERTY at 0x7f7a2ffac148>,\n 'hear-bark': <Element PROPERTY at 0x7f7a2ffac188>,\n 'bowel-problem': <Element PROPERTY at 0x7f7a2ffac0c8>,\n 'dog-out': <Element PROPERTY at 0x7f7a2ffac108>}\n \"\"\"\n variables = self.model.nodes()\n property_tag = {}\n for var in sorted(variables):\n properties = self.model.node[var]\n property_tag[var] = etree.SubElement(self.variables[var], \"PROPERTY\")\n for prop, val in properties.items():\n property_tag[var].text = str(prop) + \" = \" + str(val)\n return property_tag\n\n def get_definition(self):\n \"\"\"\n Add Definition to XMLBIF\n\n Return\n ------\n dict: dict of type {variable: definition tag}\n\n Examples\n --------\n >>> writer = XMLBIFWriter(model)\n >>> writer.get_definition()\n {'hear-bark': <Element DEFINITION at 0x7f1d48977408>,\n 'family-out': <Element DEFINITION at 0x7f1d489773c8>,\n 'dog-out': <Element DEFINITION at 0x7f1d48977388>,\n 'bowel-problem': <Element DEFINITION at 0x7f1d48977348>,\n 'light-on': <Element DEFINITION at 0x7f1d48977448>}\n \"\"\"\n cpds = self.model.get_cpds()\n cpds.sort(key=lambda x: x.variable)\n definition_tag = {}\n for cpd in cpds:\n definition_tag[cpd.variable] = etree.SubElement(self.network, \"DEFINITION\")\n etree.SubElement(definition_tag[cpd.variable], \"FOR\").text = cpd.variable\n for child in sorted([] if cpd.evidence is None else cpd.evidence):\n etree.SubElement(definition_tag[cpd.variable], \"GIVEN\").text = child\n\n return definition_tag\n\n def get_cpd(self):\n \"\"\"\n Add Table to XMLBIF.\n\n Return\n ---------------\n dict: dict of type {variable: table tag}\n\n Examples\n -------\n >>> writer = XMLBIFWriter(model)\n >>> writer.get_cpd()\n {'dog-out': <Element TABLE at 0x7f240726f3c8>,\n 'light-on': <Element TABLE at 0x7f240726f488>,\n 'bowel-problem': <Element TABLE at 0x7f240726f388>,\n 'family-out': <Element TABLE at 0x7f240726f408>,\n 'hear-bark': <Element TABLE at 0x7f240726f448>}\n \"\"\"\n cpds = self.model.get_cpds()\n definition_tag = self.definition\n table_tag = {}\n for cpd in cpds:\n table_tag[cpd.variable] = etree.SubElement(definition_tag[cpd.variable], \"TABLE\")\n table_tag[cpd.variable].text = ''\n for val in cpd.values.ravel():\n table_tag[cpd.variable].text += str(val) + ' '\n\n return table_tag\n\n def write_xmlbif(self, filename):\n \"\"\"\n Write the xml data into the file.\n\n Parameters\n ----------\n filename: Name of the file.\n\n Examples\n -------\n >>> writer = XMLBIFWriter(model)\n >>> writer.write_xmlbif(test_file)\n \"\"\"\n writer = self.__str__()[:-1].decode('utf-8')\n with open(filename, 'w') as fout:\n fout.write(writer)\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
peterwauligmann/sparse_mm
[ "344c06c183854f72224c1e88ad2ced2e092d4efb" ]
[ "matmul.py" ]
[ "from typing import Tuple\n\nfrom codegen.ast import *\nfrom codegen.sugar import *\nfrom codegen.forms import *\nfrom codegen.precision import *\n\nimport scripts.old_arm\nimport scripts.max_bn_knl\n\nfrom cursors import *\n\nimport architecture\nimport numpy\n\ndef decompose_pattern(k, n, pattern:Matrix[bool], bk:int, bn:int) -> Tuple[Matrix[int], List[Matrix[bool]]]:\n Bk,Bn = k//bk, n//bn\n patterns = []\n x = 0\n\n n_overhead = n % bn\n k_overhead = k % bk\n\n if n_overhead > 0:\n Bn += 1\n if k_overhead > 0:\n Bk += 1\n\n blocks = Matrix.full(Bk,Bn,-1)\n\n for Bni in range(Bn):\n for Bki in range(Bk):\n if Bni + 1 == Bn and n_overhead > 0 and Bki + 1 == Bk and k_overhead > 0:\n block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni)*bn+n_overhead)]\n elif Bni + 1 == Bn and n_overhead > 0:\n block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni)*bn+n_overhead)]\n elif Bki + 1 == Bk and k_overhead > 0:\n block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni+1)*bn)]\n else:\n block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni+1)*bn)]\n \n blocks[Bki,Bni] = x\n x += 1\n patterns.append(block)\n\n mtx_overhead = [0] * n\n\n for i in range(n):\n for j in range(k, pattern.rows):\n if pattern[j, i]:\n mtx_overhead[i] += 1\n\n return blocks, patterns, mtx_overhead\n\nclass MatMul:\n def __init__(self,\n m: int, \n n: int, \n k: int, \n lda: int, \n ldb: int, \n ldc: int,\n alpha: str,\n beta: str,\n mtx_filename: str,\n mtx_format: str = 'any',\n output_funcname: str = None,\n output_filename: str = None,\n output_overwrite: bool = False,\n bm: int = None, \n bn: int = None, \n bk: int = None,\n arch: str = 'knl',\n precision: str = 'd',\n prefetching: str = None,\n **kwargs # Accept and ignore args which don't belong\n ) -> None:\n\n self.m = m\n self.n = n\n self.k = k\n\n self.lda = lda\n self.ldb = ldb\n self.ldc = ldc\n\n try:\n self.alpha = float(alpha)\n except:\n self.alpha = 'generic'\n try:\n self.beta = float(beta)\n except:\n self.beta = 'generic'\n\n if arch == 'skx':\n arch = 'knl'\n\n self.arch = arch\n assert precision.lower() in ['s', 'd']\n self.precision = Precision.DOUBLE if precision.lower() == 'd' else Precision.SINGLE\n\n architecture.init()\n architecture.arch = arch\n architecture.Generator = architecture.get_class(\"codegen.architectures.\" + arch + \".generator.Generator\")\n architecture.operands = architecture.get_class(\"codegen.architectures.\" + arch + \".operands\")\n\n self.generator = architecture.Generator(self.precision)\n\n self.v_size = self.generator.get_v_size()\n\n if bk == None:\n bk = 2 if arch == 'knl' else 1\n\n if bm == None or bn == None:\n if arch == 'knl':\n (self.bm, self.bn) = scripts.max_bn_knl.getBlocksize(m, n, bk, self.v_size)\n elif arch == 'arm':\n (self.bm, self.bn) = scripts.old_arm.getBlocksize(m, n, bk, self.v_size)\n else: \n self.bm = bm\n self.bn = bn\n\n self.bk = bk\n\n self.prefetching = prefetching\n\n self.mtx_filename = mtx_filename\n self.mtx_format = mtx_format\n\n self.output_funcname = output_funcname\n self.output_filename = output_filename\n self.output_overwrite = output_overwrite\n\n if ldb == 0:\n pattern = Matrix.load(mtx_filename)\n else:\n mtx = numpy.zeros((k, n))\n for i in range(k):\n for j in range(n):\n mtx[i, j] = 1\n pattern = Matrix(mtx)\n\n blocks,patterns,mtx_overhead = decompose_pattern(self.k, self.n, pattern, self.bk, self.bn)\n\n self.nnz = 0\n self.flop = 0\n\n if ldb == 0:\n for i in range(n):\n for j in range(k):\n if pattern[j,i]:\n self.nnz += 1\n self.flop = self.nnz * m * 2\n self.nnz += sum(mtx_overhead)\n else:\n self.nnz = ldb * self.n\n self.flop = m * n * k * 2\n\n prefetchReg = self.generator.init_prefetching(self.prefetching)\n\n assert(self.m % self.v_size == 0)\n\n self.A_regs, self.B_regs, self.C_regs, self.starting_regs, self.alpha_reg, self.beta_reg, self.loop_reg, self.additional_regs = self.generator.make_reg_blocks(self.bm, self.bn, self.bk, self.v_size, self.nnz, self.m, self.n, self.k)\n\n self.A = DenseCursor(\"A\", self.starting_regs[0], self.m, self.k, self.lda, self.bm, self.bk, self.precision.value)\n self.B = BlockCursor(\"B\", self.starting_regs[1], self.k, self.n, self.ldb, self.bk, self.bn, self.precision.value, blocks, patterns,mtx_overhead)\n self.C = DenseCursor(\"C\", self.starting_regs[2], self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value)\n self.C_pf = DenseCursor(\"C_pf\", prefetchReg, self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value) if prefetchReg else None\n\n\n def make_nk_unroll(self):\n\n asm = block(\"Unrolling over bn and bk\")\n A_ptr = CursorLocation()\n B_ptr = self.B.start()\n C_ptr = CursorLocation()\n C_pf_ptr = CursorLocation()\n\n Bn = self.n // self.bn\n Bk = self.k // self.bk\n vm = self.bm // self.v_size\n\n n_overhead = self.n % self.bn\n k_overhead = self.k % self.bk\n\n if n_overhead > 0:\n Bn += 1\n if k_overhead > 0:\n Bk += 1\n\n asm.add(self.generator.make_b_pointers(self.starting_regs[1], self.additional_regs, self.nnz))\n\n for Bni in range(0,Bn):\n \n regs = self.C_regs\n \n if Bni + 1 == Bn and n_overhead > 0:\n regs = self.C_regs[0:vm, 0:n_overhead]\n\n if self.alpha == 1.0 and self.beta != 0.0:\n asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, False))\n if self.beta != 1.0:\n for ic in range(regs.shape[1]):\n for ir in range(regs.shape[0]):\n asm.add(mul(regs[ir,ic], self.beta_reg[1], regs[ir,ic]))\n else:\n asm.add(self.generator.make_zero_block(regs, self.additional_regs))\n\n for Bki in range(0,Bk):\n\n to_A = Coords(right=Bki)\n to_B = Coords(right=Bni, down=Bki, absolute=True)\n\n if self.B.has_nonzero_block(B_ptr, to_B):\n asm.add(self.generator.make_microkernel(self.A, self.B, A_ptr, B_ptr, self.A_regs, self.B_regs, regs, self.v_size, self.additional_regs, to_A, to_B))\n\n if self.alpha != 1.0:\n store_block = block(\"\")\n \n for x in range(0, regs.shape[1], self.A_regs.shape[1]):\n A_regs_cut = self.A_regs[0:min(self.A_regs.shape[0], regs.shape[0]), 0:regs.shape[1]-x]\n if self.beta != 0.0:\n store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, False, None, self.ldc * x))\n\n\n for ir in range(A_regs_cut.shape[0]):\n for ic in range(A_regs_cut.shape[1]):\n if self.beta != 0.0 and self.beta != 1.0:\n store_block.add(mul(A_regs_cut[ir,ic], self.beta_reg[1], A_regs_cut[ir,ic]))\n if self.beta == 0.0:\n store_block.add(mul(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], \"C = C + alpha * AB\"))\n else:\n store_block.add(fma(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], \"C = C + alpha * AB\", False))\n\n store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, True, self.prefetching, self.ldc * x))\n asm.add(store_block)\n\n else:\n asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, True, self.prefetching))\n\n if (Bni != Bn-1):\n move_C, C_ptr = self.C.move(C_ptr, Coords(right=1))\n asm.add(move_C)\n if self.C_pf:\n move_C_pf, C_pf_ptr = self.C_pf.move(C_pf_ptr, Coords(right=1))\n asm.add(move_C_pf)\n\n\n return asm\n\n\n\n def make(self):\n \n A_ptr = CursorLocation()\n C_ptr = CursorLocation()\n C_pf_ptr = CursorLocation()\n\n Bm = self.m // self.bm\n Bn = self.n // self.bn\n Bk = self.k // self.bk\n\n if self.n % self.bn != 0:\n Bn += 1\n\n loopBody = [\n self.make_nk_unroll(),\n self.A.move(A_ptr, Coords(down=1))[0],\n self.C.move(C_ptr, Coords(down=1, right=1-Bn))[0]\n ]\n if self.C_pf:\n loopBody.append(self.C_pf.move(C_pf_ptr, Coords(down=1, right=1-Bn))[0])\n\n asm = block(\"unrolled_{}x{}x{}\".format(self.m,self.n,self.k),\n self.generator.bcst_alpha_beta(self.alpha_reg, self.beta_reg),\n self.generator.make_scaling_offsets(self.additional_regs, self.nnz),\n loop(self.loop_reg, 0, Bm, 1).body(*loopBody)\n )\n\n vm_overhead = (self.m % self.bm) // self.v_size\n\n if vm_overhead > 0:\n self.m = self.m % self.bm\n self.bm = self.m % self.bm\n self.A_regs = self.A_regs[0:self.bm // self.v_size, 0:self.bk]\n self.C_regs = self.C_regs[0:self.bm // self.v_size, 0:self.bn]\n self.A.r = self.m\n asm.add(self.make_nk_unroll())\n\n\n return asm\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]